diff --git a/packages/@jsonql/security/dist/jsonql-security.js b/packages/@jsonql/security/dist/jsonql-security.js index e492277e93abdc4391852a170b577acadbd4caaf..06cd6bc5ac2bbde0aad8e1a4ad980d3c7ed1866c 100644 --- a/packages/@jsonql/security/dist/jsonql-security.js +++ b/packages/@jsonql/security/dist/jsonql-security.js @@ -1,2 +1,2 @@ -!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlSecurity={})}(this,(function(t){"use strict";function r(t){this.message=t}r.prototype=new Error,r.prototype.name="InvalidCharacterError";var e="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new r("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,u=0,a=0,i="";o=e.charAt(a++);~o&&(n=u%4?64*n+o:o,u++%4)?i+=String.fromCharCode(255&n>>(-2*u&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return i};var n=function(t){var r=t.replace(/-/g,"+").replace(/_/g,"/");switch(r.length%4){case 0:break;case 2:r+="==";break;case 3:r+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(e(t).replace(/(.)/g,(function(t,r){var e=r.charCodeAt(0).toString(16).toUpperCase();return e.length<2&&(e="0"+e),"%"+e})))}(r)}catch(t){return e(r)}};function o(t){this.message=t}o.prototype=new Error,o.prototype.name="InvalidTokenError";var u=function(t,r){if("string"!=typeof t)throw new o("Invalid token specified");var e=!0===(r=r||{}).header?0:1;try{return JSON.parse(n(t.split(".")[e]))}catch(t){throw new o("Invalid token specified: "+t.message)}};u.InvalidTokenError=o;var a="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},i="object"==typeof a&&a&&a.Object===Object&&a,c="object"==typeof self&&self&&self.Object===Object&&self,f=i||c||Function("return this")(),l=f.Symbol;function s(t,r){for(var e=-1,n=null==t?0:t.length,o=Array(n);++e=n?t:function(t,r,e){var n=-1,o=t.length;r<0&&(r=-r>o?0:o+r),(e=e>o?o:e)<0&&(e+=o),o=r>e?0:e-r>>>0,r>>>=0;for(var u=Array(o);++n-1;);return e}(n,o),function(t,r){for(var e=t.length;e--&&E(r,t[e],0)>-1;);return e}(n,o)+1).join("")}function q(t){return"string"==typeof t||!p(t)&&j(t)&&"[object String]"==_(t)}var J=function(t){return""!==V(t)&&q(t)},L=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(r,e),r}(Error);function W(t){var r=t.iat||function(t){void 0===t&&(t=!1);var r=Date.now();return t?Math.floor(r/1e3):r}(!0);if(t.exp&&r>=t.exp){var e=new Date(t.exp).toISOString();throw new L("Token has expired on "+e,t)}return t}var G=function(t){return!!p(t)||null!=t&&""!==V(t)};function H(t){return function(t){return"number"==typeof t||j(t)&&"[object Number]"==_(t)}(t)&&t!=+t}var Y=function(t){return!q(t)&&!H(parseFloat(t))},K=function(t){return null!=t&&"boolean"==typeof t},Q=function(t,r){return void 0===r&&(r=!0),void 0!==t&&""!==t&&""!==V(t)&&(!1===r||!0===r&&null!==t)},X=function(t){switch(t){case"number":return Y;case"string":return J;case"boolean":return K;default:return Q}},Z=function(t,r){return void 0===r&&(r=""),!!p(t)&&(""===r||""===V(r)||!(t.filter((function(t){return!X(r)(t)})).length>0))},tt=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var r=t.replace("array.<","").replace(">","");return r.indexOf("|")?r.split("|"):[r]}return!1},rt=function(t,r){var e=t.arg;return r.length>1?!e.filter((function(t){return!(r.length>r.filter((function(r){return!X(r)(t)})).length)})).length:r.length>r.filter((function(t){return!Z(e,t)})).length};function et(t,r){return function(e){return t(r(e))}}var nt=et(Object.getPrototypeOf,Object),ot=Function.prototype,ut=Object.prototype,at=ot.toString,it=ut.hasOwnProperty,ct=at.call(Object);function ft(t){if(!j(t)||"[object Object]"!=_(t))return!1;var r=nt(t);if(null===r)return!0;var e=it.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&at.call(e)==ct}var lt=function(t,r){if(void 0===r&&(r=null),ft(t)){if(!r)return!0;if(Z(r))return!r.filter((function(r){var e=t[r.name];return!(r.type.length>r.type.filter((function(t){var r;return void 0===e||(!1!==(r=tt(t))?!rt({arg:e},r):!X(t)(e))})).length)})).length}return!1},st=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(r,e),r}(Error),pt=function(t,r){var e,n,o,u,a;switch(!0){case"object"===t:return o=(n=r).arg,u=n.param,a=[o],Array.isArray(u.keys)&&u.keys.length&&a.push(u.keys),!Reflect.apply(lt,null,a);case"array"===t:return!Z(r.arg);case!1!==(e=tt(t)):return!rt(r,e);default:return!X(t)(r.arg)}},vt=function(t,r){return void 0!==t?t:!0===r.optional&&void 0!==r.defaultvalue?r.defaultvalue:null};function ht(t,r){return t===r||t!=t&&r!=r}function dt(t,r){for(var e=t.length;e--;)if(ht(t[e][0],r))return e;return-1}var yt=Array.prototype.splice;function bt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},bt.prototype.set=function(t,r){var e=this.__data__,n=dt(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};function _t(t){if(!gt(t))return!1;var r=_(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}var jt,mt=f["__core-js_shared__"],wt=(jt=/[^.]+$/.exec(mt&&mt.keys&&mt.keys.IE_PROTO||""))?"Symbol(src)_1."+jt:"";var Ot=Function.prototype.toString;function kt(t){if(null!=t){try{return Ot.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var At=/^\[object .+?Constructor\]$/,St=Function.prototype,Et=Object.prototype,Pt=St.toString,xt=Et.hasOwnProperty,Tt=RegExp("^"+Pt.call(xt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function zt(t){return!(!gt(t)||(r=t,wt&&wt in r))&&(_t(t)?Tt:At).test(kt(t));var r}function Ct(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return zt(e)?e:void 0}var It=Ct(f,"Map"),Mt=Ct(Object,"create");var Dt=Object.prototype.hasOwnProperty;var Ft=Object.prototype.hasOwnProperty;function $t(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=9007199254740991}function cr(t){return null!=t&&ir(t.length)&&!_t(t)}var fr="object"==typeof t&&t&&!t.nodeType&&t,lr=fr&&"object"==typeof module&&module&&!module.nodeType&&module,sr=lr&&lr.exports===fr?f.Buffer:void 0,pr=(sr?sr.isBuffer:void 0)||function(){return!1},vr={};vr["[object Float32Array]"]=vr["[object Float64Array]"]=vr["[object Int8Array]"]=vr["[object Int16Array]"]=vr["[object Int32Array]"]=vr["[object Uint8Array]"]=vr["[object Uint8ClampedArray]"]=vr["[object Uint16Array]"]=vr["[object Uint32Array]"]=!0,vr["[object Arguments]"]=vr["[object Array]"]=vr["[object ArrayBuffer]"]=vr["[object Boolean]"]=vr["[object DataView]"]=vr["[object Date]"]=vr["[object Error]"]=vr["[object Function]"]=vr["[object Map]"]=vr["[object Number]"]=vr["[object Object]"]=vr["[object RegExp]"]=vr["[object Set]"]=vr["[object String]"]=vr["[object WeakMap]"]=!1;var hr,dr="object"==typeof t&&t&&!t.nodeType&&t,yr=dr&&"object"==typeof module&&module&&!module.nodeType&&module,br=yr&&yr.exports===dr&&i.process,gr=function(){try{var t=yr&&yr.require&&yr.require("util").types;return t||br&&br.binding&&br.binding("util")}catch(t){}}(),_r=gr&&gr.isTypedArray,jr=_r?(hr=_r,function(t){return hr(t)}):function(t){return j(t)&&ir(t.length)&&!!vr[_(t)]};function mr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var wr=Object.prototype.hasOwnProperty;function Or(t,r,e){var n=t[r];wr.call(t,r)&&ht(n,e)&&(void 0!==e||r in t)||Vt(t,r,e)}var kr=/^(?:0|[1-9]\d*)$/;function Ar(t,r){var e=typeof t;return!!(r=null==r?9007199254740991:r)&&("number"==e||"symbol"!=e&&kr.test(t))&&t>-1&&t%1==0&&t0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}($r);function Rr(t,r){return Br(function(t,r,e){return r=Fr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=Fr(n.length-r,0),a=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=Ur.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!gt(e))return!1;var n=typeof r;return!!("number"==n?cr(e)&&Ar(r,e.length):"string"==n&&r in e)&&ht(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++ei))return!1;var f=u.get(t);if(f&&u.get(r))return f==r;var l=-1,s=!0,p=2&e?new Gr:void 0;for(u.set(t,r),u.set(r,t);++lr.length:var n=r.length,o=["any"];return t.map((function(t,e){var u=e>=n||!!r[e].optional,a=r[e]||{type:o,name:"_"+e};return{arg:u?vt(t,a):t,index:e,param:a,optional:u}}));default:throw new L("Could not understand your arguments and parameter structure!",{args:t,params:r})}}(t,r),u=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var r=t.arg,e=t.param;return!!G(r)&&!(e.type.length>e.type.filter((function(r){return pt(r,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(r){return pt(r,t)})).length)}));return e?((n={}).error=u,n.data=o.map((function(t){return t.arg})),n):u})),hn={algorithm:pn("HS256",["string"]),expiresIn:pn(!1,["boolean","number","string"],(rn={},rn.alias="exp",rn.optional=!0,rn)),notBefore:pn(!1,["boolean","number","string"],(en={},en.alias="nbf",en.optional=!0,en)),audience:pn(!1,["boolean","string"],(nn={},nn.alias="iss",nn.optional=!0,nn)),subject:pn(!1,["boolean","string"],(on={},on.alias="sub",on.optional=!0,on)),issuer:pn(!1,["boolean","string"],(un={},un.alias="iss",un.optional=!0,un)),noTimestamp:pn(!1,["boolean"],(an={},an.optional=!0,an)),header:pn(!1,["boolean","string"],(cn={},cn.optional=!0,cn)),keyid:pn(!1,["boolean","string"],(fn={},fn.optional=!0,fn)),mutatePayload:pn(!1,["boolean"],(ln={},ln.optional=!0,ln))};t.decodeToken=function(t){if(J(t))return W(u(t));throw new L("Token must be a string!")},t.tokenValidator=function(t){if(!sn(t))return{};var r={},e=vn(t,hn);for(var n in e)e[n]&&(r[n]=e[n]);return r},Object.defineProperty(t,"__esModule",{value:!0})})); +!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlSecurity={})}(this,(function(t){"use strict";var r=function(t){function r(t){this.message=t}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"InvalidCharacterError"},Object.defineProperties(r.prototype,e),r}(Error);function e(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new r("'atob' failed: The string to be decoded is not correctly encoded.");for(var n=0,o=void 0,u=void 0,a=0,i="";u=e.charAt(a++);~u&&(o=n%4?64*o+u:u,n++%4)?i+=String.fromCharCode(255&o>>(-2*n&6)):0)u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(u);return output}try{"undefined"!=typeof window&&window.atob&&window.atob.bind(window)}catch(t){}function n(t){var r=t.replace(/-/g,"+").replace(/_/g,"/");switch(r.length%4){case 0:break;case 2:r+="==";break;case 3:r+="=";break;default:throw new Error("Illegal base64url string!")}try{return function(t){return decodeURIComponent(e(t).replace(/(.)/g,(function(t,r){var e=r.charCodeAt(0).toString(16).toUpperCase();return e.length<2&&(e="0"+e),"%"+e})))}(r)}catch(t){return e(r)}}var o=function(t){function r(t){this.message=t}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"InvalidTokenError"},Object.defineProperties(r.prototype,e),r}(Error);var u="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},a="object"==typeof u&&u&&u.Object===Object&&u,i="object"==typeof self&&self&&self.Object===Object&&self,c=a||i||Function("return this")(),f=c.Symbol;function l(t,r){for(var e=-1,n=null==t?0:t.length,o=Array(n);++e=n?t:function(t,r,e){var n=-1,o=t.length;r<0&&(r=-r>o?0:o+r),(e=e>o?o:e)<0&&(e+=o),o=r>e?0:e-r>>>0,r>>>=0;for(var u=Array(o);++n-1;);return e}(n,o),function(t,r){for(var e=t.length;e--&&E(r,t[e],0)>-1;);return e}(n,o)+1).join("")}function V(t){return"string"==typeof t||!s(t)&&_(t)&&"[object String]"==g(t)}var B=function(t){return""!==q(t)&&V(t)},L=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(r,e),r}(Error);function J(t){var r=t.iat||function(t){void 0===t&&(t=!1);var r=Date.now();return t?Math.floor(r/1e3):r}(!0);if(t.exp&&r>=t.exp){var e=new Date(t.exp).toISOString();throw new L("Token has expired on "+e,t)}return t}var K=function(t){return!!s(t)||null!=t&&""!==q(t)};function W(t){return function(t){return"number"==typeof t||_(t)&&"[object Number]"==g(t)}(t)&&t!=+t}var H=function(t){return!V(t)&&!W(parseFloat(t))},Y=function(t){return null!=t&&"boolean"==typeof t},G=function(t,r){return void 0===r&&(r=!0),void 0!==t&&""!==t&&""!==q(t)&&(!1===r||!0===r&&null!==t)},Q=function(t){switch(t){case"number":return H;case"string":return B;case"boolean":return Y;default:return G}},X=function(t,r){return void 0===r&&(r=""),!!s(t)&&(""===r||""===q(r)||!(t.filter((function(t){return!Q(r)(t)})).length>0))},Z=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var r=t.replace("array.<","").replace(">","");return r.indexOf("|")?r.split("|"):[r]}return!1},tt=function(t,r){var e=t.arg;return r.length>1?!e.filter((function(t){return!(r.length>r.filter((function(r){return!Q(r)(t)})).length)})).length:r.length>r.filter((function(t){return!X(e,t)})).length};function rt(t,r){return function(e){return t(r(e))}}var et=rt(Object.getPrototypeOf,Object),nt=Function.prototype,ot=Object.prototype,ut=nt.toString,at=ot.hasOwnProperty,it=ut.call(Object);function ct(t){if(!_(t)||"[object Object]"!=g(t))return!1;var r=et(t);if(null===r)return!0;var e=at.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&ut.call(e)==it}var ft=function(t,r){if(void 0===r&&(r=null),ct(t)){if(!r)return!0;if(X(r))return!r.filter((function(r){var e=t[r.name];return!(r.type.length>r.type.filter((function(t){var r;return void 0===e||(!1!==(r=Z(t))?!tt({arg:e},r):!Q(t)(e))})).length)})).length}return!1},lt=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(r,e),r}(Error),st=function(t,r){var e,n,o,u,a;switch(!0){case"object"===t:return o=(n=r).arg,u=n.param,a=[o],Array.isArray(u.keys)&&u.keys.length&&a.push(u.keys),!Reflect.apply(ft,null,a);case"array"===t:return!X(r.arg);case!1!==(e=Z(t)):return!tt(r,e);default:return!Q(t)(r.arg)}},pt=function(t,r){return void 0!==t?t:!0===r.optional&&void 0!==r.defaultvalue?r.defaultvalue:null};function vt(t,r){return t===r||t!=t&&r!=r}function ht(t,r){for(var e=t.length;e--;)if(vt(t[e][0],r))return e;return-1}var dt=Array.prototype.splice;function yt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},yt.prototype.set=function(t,r){var e=this.__data__,n=ht(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};function gt(t){if(!bt(t))return!1;var r=g(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}var _t,jt=c["__core-js_shared__"],mt=(_t=/[^.]+$/.exec(jt&&jt.keys&&jt.keys.IE_PROTO||""))?"Symbol(src)_1."+_t:"";var wt=Function.prototype.toString;function Ot(t){if(null!=t){try{return wt.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var At=/^\[object .+?Constructor\]$/,kt=Function.prototype,Et=Object.prototype,St=kt.toString,Pt=Et.hasOwnProperty,Tt=RegExp("^"+St.call(Pt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function xt(t){return!(!bt(t)||(r=t,mt&&mt in r))&&(gt(t)?Tt:At).test(Ot(t));var r}function zt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return xt(e)?e:void 0}var Ct=zt(c,"Map"),It=zt(Object,"create");var Nt=Object.prototype.hasOwnProperty;var Rt=Object.prototype.hasOwnProperty;function Dt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=9007199254740991}function ir(t){return null!=t&&ar(t.length)&&!gt(t)}var cr="object"==typeof t&&t&&!t.nodeType&&t,fr=cr&&"object"==typeof module&&module&&!module.nodeType&&module,lr=fr&&fr.exports===cr?c.Buffer:void 0,sr=(lr?lr.isBuffer:void 0)||function(){return!1},pr={};pr["[object Float32Array]"]=pr["[object Float64Array]"]=pr["[object Int8Array]"]=pr["[object Int16Array]"]=pr["[object Int32Array]"]=pr["[object Uint8Array]"]=pr["[object Uint8ClampedArray]"]=pr["[object Uint16Array]"]=pr["[object Uint32Array]"]=!0,pr["[object Arguments]"]=pr["[object Array]"]=pr["[object ArrayBuffer]"]=pr["[object Boolean]"]=pr["[object DataView]"]=pr["[object Date]"]=pr["[object Error]"]=pr["[object Function]"]=pr["[object Map]"]=pr["[object Number]"]=pr["[object Object]"]=pr["[object RegExp]"]=pr["[object Set]"]=pr["[object String]"]=pr["[object WeakMap]"]=!1;var vr,hr="object"==typeof t&&t&&!t.nodeType&&t,dr=hr&&"object"==typeof module&&module&&!module.nodeType&&module,yr=dr&&dr.exports===hr&&a.process,br=function(){try{var t=dr&&dr.require&&dr.require("util").types;return t||yr&&yr.binding&&yr.binding("util")}catch(t){}}(),gr=br&&br.isTypedArray,_r=gr?(vr=gr,function(t){return vr(t)}):function(t){return _(t)&&ar(t.length)&&!!pr[g(t)]};function jr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var mr=Object.prototype.hasOwnProperty;function wr(t,r,e){var n=t[r];mr.call(t,r)&&vt(n,e)&&(void 0!==e||r in t)||qt(t,r,e)}var Or=/^(?:0|[1-9]\d*)$/;function Ar(t,r){var e=typeof t;return!!(r=null==r?9007199254740991:r)&&("number"==e||"symbol"!=e&&Or.test(t))&&t>-1&&t%1==0&&t0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(Dr);function Ur(t,r){return Fr(function(t,r,e){return r=Rr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=Rr(n.length-r,0),a=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=$r.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!bt(e))return!1;var n=typeof r;return!!("number"==n?ir(e)&&Ar(r,e.length):"string"==n&&r in e)&&vt(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++ei))return!1;var f=u.get(t);if(f&&u.get(r))return f==r;var l=-1,s=!0,p=2&e?new Kr:void 0;for(u.set(t,r),u.set(r,t);++lr.length:var n=r.length,o=["any"];return t.map((function(t,e){var u=e>=n||!!r[e].optional,a=r[e]||{type:o,name:"_"+e};return{arg:u?pt(t,a):t,index:e,param:a,optional:u}}));default:throw new L("Could not understand your arguments and parameter structure!",{args:t,params:r})}}(t,r),u=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var r=t.arg,e=t.param;return!!K(r)&&!(e.type.length>e.type.filter((function(r){return st(r,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(r){return st(r,t)})).length)}));return e?((n={}).error=u,n.data=o.map((function(t){return t.arg})),n):u})),vn={algorithm:sn("HS256",["string"]),expiresIn:sn(!1,["boolean","number","string"],(tn={},tn.alias="exp",tn.optional=!0,tn)),notBefore:sn(!1,["boolean","number","string"],(rn={},rn.alias="nbf",rn.optional=!0,rn)),audience:sn(!1,["boolean","string"],(en={},en.alias="iss",en.optional=!0,en)),subject:sn(!1,["boolean","string"],(nn={},nn.alias="sub",nn.optional=!0,nn)),issuer:sn(!1,["boolean","string"],(on={},on.alias="iss",on.optional=!0,on)),noTimestamp:sn(!1,["boolean"],(un={},un.optional=!0,un)),header:sn(!1,["boolean","string"],(an={},an.optional=!0,an)),keyid:sn(!1,["boolean","string"],(cn={},cn.optional=!0,cn)),mutatePayload:sn(!1,["boolean"],(fn={},fn.optional=!0,fn))};var hn=require("jsonql-constants"),dn=hn.TOKEN_PARAM_NAME,yn=hn.AUTH_HEADER,bn=hn.TOKEN_DELIVER_LOCATION_PROP_KEY,gn=hn.TOKEN_IN_URL,_n=hn.TOKEN_IN_HEADER,jn=hn.WS_OPT_PROP_KEY;function mn(t){return t[bn]||gn}t.decodeToken=function(t){if(B(t))return J(function(t,r){if("string"!=typeof t)throw new o("Invalid token specified");var e=!0===(r=r||{}).header?0:1;try{return JSON.parse(n(t.split(".")[e]))}catch(t){throw new o("Invalid token specified: "+t.message)}}(t));throw new L("Token must be a string!")},t.extractConfig=mn,t.prepareConnectConfig=function(t,r,e){var n;if(void 0===e&&(e=!1),!1===e)return{url:t,opts:r[jn]||{}};switch(mn(r)){case gn:return{url:t+"?"+dn+"="+e,opts:r[jn]||{}};case _n:return{url:t,opts:Object.assign({},r[jn]||{},{headers:(n={},n[yn]=e,n)})}}},t.tokenValidator=function(t){if(!ln(t))return{};var r={},e=pn(t,vn);for(var n in e)e[n]&&(r[n]=e[n]);return r},Object.defineProperty(t,"__esModule",{value:!0})})); //# sourceMappingURL=jsonql-security.js.map diff --git a/packages/@jsonql/security/dist/jsonql-security.js.map b/packages/@jsonql/security/dist/jsonql-security.js.map index 6fd8220f5c7f75033cc809f8d782eb2e31d7e78e..c92b6faa9ef034f7c1506810accbea32c88c0c7f 100644 --- a/packages/@jsonql/security/dist/jsonql-security.js.map +++ b/packages/@jsonql/security/dist/jsonql-security.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-security.js","sources":["../node_modules/lodash-es/_arraySome.js"],"sourcesContent":["/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n"],"names":["SetCache"],"mappings":"+qhBAAAA"} \ No newline at end of file +{"version":3,"file":"jsonql-security.js","sources":["../node_modules/lodash-es/_arraySome.js"],"sourcesContent":["/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n"],"names":["SetCache"],"mappings":"20hBAAAA"} \ No newline at end of file diff --git a/packages/@jsonql/security/index.js b/packages/@jsonql/security/index.js index 338f4f2516b184583971b467d49d7744300d9bd1..27173ad52a53a509e3a3d4d1ea5c97bfce59481a 100644 --- a/packages/@jsonql/security/index.js +++ b/packages/@jsonql/security/index.js @@ -1,10 +1,24 @@ // main export interface for client side modules +// main export interface for client side modules +// rename this to module and make sure we import just this import { decodeToken, tokenValidator -} from './module' +} from './src/client' +import { + extractConfig, + prepareConnectConfig +} from './src/socket' +/* @TODO do we need this on the client side? +import { + isCacheObj, + getCache +} from './src/cache' +*/ export { + extractConfig, + prepareConnectConfig, decodeToken, tokenValidator } diff --git a/packages/@jsonql/security/main.js b/packages/@jsonql/security/main.js index ac68b36ece3a79d5275655b5edaab0b57c74ebfe..70734f2661243f36fd7288dbb17ea3e4534dc6c2 100644 --- a/packages/@jsonql/security/main.js +++ b/packages/@jsonql/security/main.js @@ -7,23 +7,36 @@ const jwtToken = require('./src/jwt/jwt-token') const jwtDecode = require('./src/jwt/jwt-decode') const jwtRsaToken = require('./src/jwt/jwt-rsa-token') -const { decodeToken, tokenValidator } = require('./src/jwt/decode-token') -const { encryptWithPublicPem, decryptWithPrivatePem } = require('./src/crypto/encrypt-decrypt') - +const { + decodeToken, + tokenValidator +} = require('./src/jwt/decode-token') +const { + encryptWithPublicPem, + decryptWithPrivatePem +} = require('./src/crypto/encrypt-decrypt') const { loginResultToJwt, provideUserdata, createTokenValidator } = require('./src/server') - const { getCache, isCacheObj, - getToken, createCSRFToken, isCSRFTokenExist } = require('./src/cache') +const { + extractConfig, + prepareConnectConfig +} = require('./src/socket/index.cjs') +const { + getTokenFromUrl, + processAuthTokenHeader, + getTokenFromHeader, + getWsAuthToken +} = require('./src/socket/ws-token-fn') // output module.exports = { @@ -50,5 +63,13 @@ module.exports = { getToken, createCSRFToken, - isCSRFTokenExist + isCSRFTokenExist, + + extractConfig, + prepareConnectConfig, + + getTokenFromUrl, + processAuthTokenHeader, + getTokenFromHeader, + getWsAuthToken } diff --git a/packages/@jsonql/security/module.js b/packages/@jsonql/security/module.js deleted file mode 100644 index bb12f948472bd21af7e4553dea228a24a6a75869..0000000000000000000000000000000000000000 --- a/packages/@jsonql/security/module.js +++ /dev/null @@ -1,17 +0,0 @@ -// main export interface for client side modules -// rename this to module and make sure we import just this -import { - decodeToken, - tokenValidator -} from './src/client' -/* // do we need this on the client side? -import { - isCacheObj, - getCache -} from './src/cache' -*/ - -export { - decodeToken, - tokenValidator -} diff --git a/packages/@jsonql/security/package.json b/packages/@jsonql/security/package.json index 8ce6a65d77063d6d65102ab79b4f8b1cd899015f..ef99dd2677fd333cd734f6b166a079ab4664849e 100644 --- a/packages/@jsonql/security/package.json +++ b/packages/@jsonql/security/package.json @@ -1,6 +1,6 @@ { "name": "@jsonql/security", - "version": "0.9.5", + "version": "0.9.9", "description": "jwt authentication helpers library for jsonql browser / node", "main": "main.js", "module": "index.js", @@ -8,16 +8,18 @@ "scripts": { "test": "npm run build && npm run test:run", "test:run": "DEBUG=jsonql-jwt* ava", - "build": "npm run build:decode && npm run build:main", + "build": "npm run build:decode && npm run build:config && npm run build:main", "build:main": "rollup -c", - "build:decode": "rollup -c ./rollup.decode-jwt.config.js", + "build:decode": "TARGET=decode rollup -c ./rollup.config.cjs.js", + "build:config": "TARGET=config rollup -c ./rollup.config.cjs.js", "cmd": "DEBUG=jsonql-jwt* node ./cmd.js", "test:client-utils": "npm run build:clients && DEBUG=jsonql-jwt* ava ./tests/client-utils.test.js", "test:rsa-pem": "DEBUG=jsonql-jwt* ava ./tests/rsa-pem-keys.test.js", "test:rsa": "DEBUG=jsonql-jwt* ava ./tests/rsa-keys.test.js", "test:decode": "DEBUG=jsonql-jwt* ava ./tests/jwt-decode.test.js", "test:cache": "DEBUG=jsonql-security* ava ./tests/cache.test.js", - "prepare": "NODE_ENV=production npm run build" + "test:fn": "DEBUG=jsonql-security* ava ./tests/fn.test.js", + "prepare": "NODE_ENV=production npm run build && npm run test" }, "files": [ "cmd.js", diff --git a/packages/@jsonql/security/rollup.decode-jwt.config.js b/packages/@jsonql/security/rollup.config.cjs.js similarity index 76% rename from packages/@jsonql/security/rollup.decode-jwt.config.js rename to packages/@jsonql/security/rollup.config.cjs.js index bf5b4d94c83efc69d968f87eff93f17fe7d04ea0..7907a66b3f9e09b5a77ad20e7cce6e85ae18941c 100644 --- a/packages/@jsonql/security/rollup.decode-jwt.config.js +++ b/packages/@jsonql/security/rollup.config.cjs.js @@ -19,7 +19,8 @@ import async from 'rollup-plugin-async' // get the version info import { version } from './package.json' -const env = process.env.NODE_ENV +const target = process.env.TARGET + let plugins = [ json({ @@ -37,16 +38,29 @@ let plugins = [ async(), replace({ 'process.env.NODE_ENV': JSON.stringify('production'), - '__PLACEHOLDER__': `version: ${version} module: ${env==='prod' ? 'cjs' : 'umd'}` + '__PLACEHOLDER__': `version: ${version} module: cjs` }), size() ] +let inputFile, outputFile + +switch (target) { + case 'config': + inputFile = join('socket', 'index.js') + outputFile = join('socket', 'index.cjs.js') + break + case 'decode': + default: + inputFile = join('client', 'index.js') + outputFile = join('jwt', 'decode-token.js') +} + let config = { - input: join(__dirname, 'src', 'client', 'index.js'), + input: join(__dirname, 'src', inputFile), output: { - name: 'jsonqlJwtHelpers', - file: join(__dirname, 'src', 'jwt', 'decode-token.js'), + // name: 'jsonqlJwtHelpers', + file: join(__dirname, 'src', outputFile), format: 'cjs', sourcemap: false, globals: { diff --git a/packages/@jsonql/security/src/client/decode-token/decode-token.js b/packages/@jsonql/security/src/client/decode-token/decode-token.js index 8a7817d809eed4c59ac134618637b8a7a5123d4b..4d5c12df499fdf54e717c8e9d8fc64cca3ce0093 100644 --- a/packages/@jsonql/security/src/client/decode-token/decode-token.js +++ b/packages/@jsonql/security/src/client/decode-token/decode-token.js @@ -2,20 +2,11 @@ // we use call this to decode the token and then add the payload // to the resolver so the user can call ResolverName.userdata // and get back the payload -import jwt_decode from 'jwt-decode' +import { jwtDecode as localJwtDecode } from '../jwt-decode' import isString from 'jsonql-params-validator/src/string' +import { timestamp } from 'jsonql-utils/src/timestamp' import JsonqlError from 'jsonql-errors/src/error' -/** - * Use the jsonql-utils version in the future - * @param {boolean} sec use second - * @return {integer} the timestamp in second or milsecond - */ -const timestamp = function (sec = false) { - var time = Date.now() - return sec ? Math.floor( time / 1000 ) : time -} - /** * We only check the nbf and exp * @param {object} token for checking @@ -42,7 +33,7 @@ function validate(token) { */ export default function jwtDecode(token) { if (isString(token)) { - const t = jwt_decode(token) + const t = localJwtDecode(token) return validate(t) } throw new JsonqlError('Token must be a string!') diff --git a/packages/@jsonql/security/src/client/jwt-decode/README.md b/packages/@jsonql/security/src/client/jwt-decode/README.md new file mode 100644 index 0000000000000000000000000000000000000000..317e24fbd4079cda42e051f3138dc8f799768901 --- /dev/null +++ b/packages/@jsonql/security/src/client/jwt-decode/README.md @@ -0,0 +1,16 @@ +# JWT library + +This is the client side jwt-decode, using [jwt-decode](https://npmjs.com/package/jwt-decode) + +Rewritten using ES6. + +The main change is using named export (rollup keep complaining about missing default export) + +```js + +import { jwtDecode } from './jwt' + +// do your thing +const payload = jwtDecode(token, {}) + +``` \ No newline at end of file diff --git a/packages/@jsonql/security/src/client/jwt-decode/atob.js b/packages/@jsonql/security/src/client/jwt-decode/atob.js new file mode 100644 index 0000000000000000000000000000000000000000..6fcfad02986b62b3773d8aec5cf40ebb66630abc --- /dev/null +++ b/packages/@jsonql/security/src/client/jwt-decode/atob.js @@ -0,0 +1,42 @@ +/** + * The code was extracted from: + * https://github.com/davidchambers/Base64.js + */ +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' +import { InvalidCharacterError } from './invalid-character-error' + +/** + * Polyfill the non ASCII code + * @param {*} input + * @return {*} usable output + */ +function atob(input) { + var str = String(input).replace(/=+$/, '') + if (str.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.") + } + for ( + // initialize result and counters + let bc = 0, bs, buffer, idx = 0, output = ''; + // get next character + buffer = str.charAt(idx++); + // character found in table? initialize bit storage and add its ascii value; + ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, + // and if not first of each 4 characters, + // convert the first 8 bits to one ascii character + bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 + ) { + // try to find character in table (0-63, not found => -1) + buffer = chars.indexOf(buffer) + } + return output +} + +// polyfill the window object +try { + typeof window !== 'undefined' && window.atob && window.atob.bind(window) || atob +} catch(e) {} + +export { atob } + + diff --git a/packages/@jsonql/security/src/client/jwt-decode/base64_url_decode.js b/packages/@jsonql/security/src/client/jwt-decode/base64_url_decode.js new file mode 100644 index 0000000000000000000000000000000000000000..c72359608163b32f4ac14a3cd8ecbff7e546e078 --- /dev/null +++ b/packages/@jsonql/security/src/client/jwt-decode/base64_url_decode.js @@ -0,0 +1,47 @@ +// handle the actual base64 decode + +import { atob } from './atob' + +/** + * Use this when encounter non ASCII payload + * @param {string} str the token + * @return {*} decoded payload + */ +function b64DecodeUnicode(str) { + return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { + var code = p.charCodeAt(0).toString(16).toUpperCase(); + if (code.length < 2) { + code = '0' + code + } + return '%' + code + })) +} + +/** + * the main interface to handle the base64 url decode + * @param {string} str the token + * @return {*} decoded base64 payload + */ +function base64UrlDecode(str) { + var output = str.replace(/-/g, "+").replace(/_/g, "/") + switch (output.length % 4) { + case 0: + break; + case 2: + output += "==" + break; + case 3: + output += "=" + break; + default: + throw new Error("Illegal base64url string!") + } + + try{ + return b64DecodeUnicode(output) + } catch (err) { + return atob(output) + } +} + +export { base64UrlDecode } \ No newline at end of file diff --git a/packages/@jsonql/security/src/client/jwt-decode/index.js b/packages/@jsonql/security/src/client/jwt-decode/index.js new file mode 100644 index 0000000000000000000000000000000000000000..587a1f5bb833be4173c407eef86580ec1596dffd --- /dev/null +++ b/packages/@jsonql/security/src/client/jwt-decode/index.js @@ -0,0 +1,32 @@ +// JWT library entry point + +import { base64UrlDecode } from './base64_url_decode' +import { InvalidTokenError } from './invalid-token-error' + + +/** + * the main interface to decode a jwt token + * @param {string} token + * @param {object} options + * @return {*} decoded token payload + */ +function jwtDecode(token,options) { + if (typeof token !== 'string') { + throw new InvalidTokenError('Invalid token specified') + } + + options = options || {}; + var pos = options.header === true ? 0 : 1 + try { + return JSON.parse(base64UrlDecode(token.split('.')[pos])) + } catch (e) { + throw new InvalidTokenError('Invalid token specified: ' + e.message) + } +} + +// using name export +export { + jwtDecode, + InvalidTokenError +} + diff --git a/packages/@jsonql/security/src/client/jwt-decode/invalid-character-error.js b/packages/@jsonql/security/src/client/jwt-decode/invalid-character-error.js new file mode 100644 index 0000000000000000000000000000000000000000..dc21423115c5bf66e73c37f12cb29a79b877ba04 --- /dev/null +++ b/packages/@jsonql/security/src/client/jwt-decode/invalid-character-error.js @@ -0,0 +1,24 @@ +// same with the invalid-token-error + +/* +function InvalidCharacterError(message) { + this.message = message; +} + +InvalidCharacterError.prototype = new Error(); +InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + +*/ + +class InvalidCharacterError extends Error { + + constructor(message) { + this.message = message + } + + get name() { + return 'InvalidCharacterError' + } +} + +export { InvalidCharacterError } \ No newline at end of file diff --git a/packages/@jsonql/security/src/client/jwt-decode/invalid-token-error.js b/packages/@jsonql/security/src/client/jwt-decode/invalid-token-error.js new file mode 100644 index 0000000000000000000000000000000000000000..962f045018cc277ddc15ba6744d89017ef651fa5 --- /dev/null +++ b/packages/@jsonql/security/src/client/jwt-decode/invalid-token-error.js @@ -0,0 +1,23 @@ +// rewrote this in class syntax instead of the function prototype + +/* +function InvalidTokenError(message) { + this.message = message +} + +InvalidTokenError.prototype = new Error() +InvalidTokenError.prototype.name = 'InvalidTokenError' +*/ + +class InvalidTokenError extends Error { + + constructor(message) { + this.message = message + } + + get name() { + return 'InvalidTokenError' + } +} + +export { InvalidTokenError } \ No newline at end of file diff --git a/packages/@jsonql/security/src/jwt/decode-token.js b/packages/@jsonql/security/src/jwt/decode-token.js index b5e0f1ba0ebef9773dae1a9bbf8981dc44c99ab2..6afa24eaae8ebbb9c3479f4f59cf1f6132e01774 100644 --- a/packages/@jsonql/security/src/jwt/decode-token.js +++ b/packages/@jsonql/security/src/jwt/decode-token.js @@ -2,11 +2,176 @@ Object.defineProperty(exports, '__esModule', { value: true }); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var jwt_decode = _interopDefault(require('jwt-decode')); var jsonqlParamsValidator = require('jsonql-params-validator'); +// same with the invalid-token-error + +/* +function InvalidCharacterError(message) { + this.message = message; +} + +InvalidCharacterError.prototype = new Error(); +InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + +*/ + +var InvalidCharacterError = /*@__PURE__*/(function (Error) { + function InvalidCharacterError(message) { + this.message = message; + } + + if ( Error ) InvalidCharacterError.__proto__ = Error; + InvalidCharacterError.prototype = Object.create( Error && Error.prototype ); + InvalidCharacterError.prototype.constructor = InvalidCharacterError; + + var prototypeAccessors = { name: { configurable: true } }; + + prototypeAccessors.name.get = function () { + return 'InvalidCharacterError' + }; + + Object.defineProperties( InvalidCharacterError.prototype, prototypeAccessors ); + + return InvalidCharacterError; +}(Error)); + +/** + * The code was extracted from: + * https://github.com/davidchambers/Base64.js + */ +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +/** + * Polyfill the non ASCII code + * @param {*} input + * @return {*} usable output + */ +function atob(input) { + var str = String(input).replace(/=+$/, ''); + if (str.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.") + } + for ( + // initialize result and counters + var bc = 0, bs = (void 0), buffer = (void 0), idx = 0, output$1 = ''; + // get next character + buffer = str.charAt(idx++); + // character found in table? initialize bit storage and add its ascii value; + ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, + // and if not first of each 4 characters, + // convert the first 8 bits to one ascii character + bc++ % 4) ? output$1 += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 + ) { + // try to find character in table (0-63, not found => -1) + buffer = chars.indexOf(buffer); + } + return output +} + +// polyfill the window object +try { + typeof window !== 'undefined' && window.atob && window.atob.bind(window) || atob; +} catch(e) {} + +// handle the actual base64 decode + +/** + * Use this when encounter non ASCII payload + * @param {string} str the token + * @return {*} decoded payload + */ +function b64DecodeUnicode(str) { + return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { + var code = p.charCodeAt(0).toString(16).toUpperCase(); + if (code.length < 2) { + code = '0' + code; + } + return '%' + code + })) +} + +/** + * the main interface to handle the base64 url decode + * @param {string} str the token + * @return {*} decoded base64 payload + */ +function base64UrlDecode(str) { + var output = str.replace(/-/g, "+").replace(/_/g, "/"); + switch (output.length % 4) { + case 0: + break; + case 2: + output += "=="; + break; + case 3: + output += "="; + break; + default: + throw new Error("Illegal base64url string!") + } + + try{ + return b64DecodeUnicode(output) + } catch (err) { + return atob(output) + } +} + +// rewrote this in class syntax instead of the function prototype + +/* +function InvalidTokenError(message) { + this.message = message +} + +InvalidTokenError.prototype = new Error() +InvalidTokenError.prototype.name = 'InvalidTokenError' +*/ + +var InvalidTokenError = /*@__PURE__*/(function (Error) { + function InvalidTokenError(message) { + this.message = message; + } + + if ( Error ) InvalidTokenError.__proto__ = Error; + InvalidTokenError.prototype = Object.create( Error && Error.prototype ); + InvalidTokenError.prototype.constructor = InvalidTokenError; + + var prototypeAccessors = { name: { configurable: true } }; + + prototypeAccessors.name.get = function () { + return 'InvalidTokenError' + }; + + Object.defineProperties( InvalidTokenError.prototype, prototypeAccessors ); + + return InvalidTokenError; +}(Error)); + +// JWT library entry point + + +/** + * the main interface to decode a jwt token + * @param {string} token + * @param {object} options + * @return {*} decoded token payload + */ +function jwtDecode(token,options) { + if (typeof token !== 'string') { + throw new InvalidTokenError('Invalid token specified') + } + + options = options || {}; + var pos = options.header === true ? 0 : 1; + try { + return JSON.parse(base64UrlDecode(token.split('.')[pos])) + } catch (e) { + throw new InvalidTokenError('Invalid token specified: ' + e.message) + } +} + var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); @@ -576,6 +741,17 @@ var checkIsString = function(value) { return (trim(value) !== '') ? isString(value) : false }; +/** + * @param {boolean} sec return in second or not + * @return {number} timestamp + */ +var timestamp = function (sec) { + if ( sec === void 0 ) sec = false; + + var time = Date.now(); + return sec ? Math.floor( time / 1000 ) : time +}; + var NO_STATUS_CODE = -1; /** @@ -623,18 +799,6 @@ var JsonqlError = /*@__PURE__*/(function (Error) { // when the user is login with the jwt -/** - * Use the jsonql-utils version in the future - * @param {boolean} sec use second - * @return {integer} the timestamp in second or milsecond - */ -var timestamp = function (sec) { - if ( sec === void 0 ) sec = false; - - var time = Date.now(); - return sec ? Math.floor( time / 1000 ) : time -}; - /** * We only check the nbf and exp * @param {object} token for checking @@ -659,9 +823,9 @@ function validate(token) { * @param {string} token to decrypted * @return {object} decrypted object */ -function jwtDecode(token) { +function jwtDecode$1(token) { if (checkIsString(token)) { - var t = jwt_decode(token); + var t = jwtDecode(token); return validate(t) } throw new JsonqlError('Token must be a string!') @@ -711,5 +875,5 @@ function tokenValidator(config) { return result } -exports.decodeToken = jwtDecode; +exports.decodeToken = jwtDecode$1; exports.tokenValidator = tokenValidator; diff --git a/packages/@jsonql/security/src/socket/index.cjs.js b/packages/@jsonql/security/src/socket/index.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..2c8a8ec5f85dac69af3f4229c02a915e10d03326 --- /dev/null +++ b/packages/@jsonql/security/src/socket/index.cjs.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +// this method is re-use in several clients +// therefore it's better to share here +var ref = require('jsonql-constants'); +var TOKEN_PARAM_NAME = ref.TOKEN_PARAM_NAME; +var AUTH_HEADER = ref.AUTH_HEADER; +var TOKEN_DELIVER_LOCATION_PROP_KEY = ref.TOKEN_DELIVER_LOCATION_PROP_KEY; +var TOKEN_IN_URL = ref.TOKEN_IN_URL; +var TOKEN_IN_HEADER = ref.TOKEN_IN_HEADER; +var WS_OPT_PROP_KEY = ref.WS_OPT_PROP_KEY; +/** + * extract the new options for authorization + * @param {*} opts configuration + * @return {string} the header option + */ +function extractConfig(opts) { + // we don't really need to do any validation here + // because the opts should be clean before calling here + return opts[TOKEN_DELIVER_LOCATION_PROP_KEY] || TOKEN_IN_URL +} + +/** + * prepare the url and options to the WebSocket + * @param {*} url + * @param {*} config + * @param {*} [token = false] + * @return {object} with url and opts key + */ +function prepareConnectConfig(url, config, token) { + var obj; + + if ( token === void 0 ) token = false; + if (token === false) { + return { + url: url, + opts: config[WS_OPT_PROP_KEY] || {} + } + } + + var tokenOpt = extractConfig(config); + switch (tokenOpt) { + case TOKEN_IN_URL: + return { + url: (url + "?" + TOKEN_PARAM_NAME + "=" + token), + opts: config[WS_OPT_PROP_KEY] || {} + } + case TOKEN_IN_HEADER: + return { + url: url, + opts: Object.assign({}, config[WS_OPT_PROP_KEY] || {}, { + headers: ( obj = {}, obj[AUTH_HEADER] = token, obj ) + }) + } + } +} + +exports.extractConfig = extractConfig; +exports.prepareConnectConfig = prepareConnectConfig; diff --git a/packages/@jsonql/security/src/socket/index.js b/packages/@jsonql/security/src/socket/index.js new file mode 100644 index 0000000000000000000000000000000000000000..089ba0bf5826f83d8e53ede9c1818bae9acd6f7b --- /dev/null +++ b/packages/@jsonql/security/src/socket/index.js @@ -0,0 +1,9 @@ +import { + extractConfig, + prepareConnectConfig +} from './token-header-opts' + +export { + extractConfig, + prepareConnectConfig +} \ No newline at end of file diff --git a/packages/@jsonql/security/src/socket/token-header-opts.js b/packages/@jsonql/security/src/socket/token-header-opts.js new file mode 100644 index 0000000000000000000000000000000000000000..7ab2be4fac067090b0e3cb080d6b5cd07aa4d86f --- /dev/null +++ b/packages/@jsonql/security/src/socket/token-header-opts.js @@ -0,0 +1,55 @@ +// this method is re-use in several clients +// therefore it's better to share here +const { + TOKEN_PARAM_NAME, + AUTH_HEADER, + TOKEN_DELIVER_LOCATION_PROP_KEY, + TOKEN_IN_URL, + TOKEN_IN_HEADER, + WS_OPT_PROP_KEY +} = require('jsonql-constants') +/** + * extract the new options for authorization + * @param {*} opts configuration + * @return {string} the header option + */ +export function extractConfig(opts) { + // we don't really need to do any validation here + // because the opts should be clean before calling here + return opts[TOKEN_DELIVER_LOCATION_PROP_KEY] || TOKEN_IN_URL +} + +/** + * prepare the url and options to the WebSocket + * @param {*} url + * @param {*} config + * @param {*} [token = false] + * @return {object} with url and opts key + */ +export function prepareConnectConfig(url, config, token = false) { + if (token === false) { + return { + url, + opts: config[WS_OPT_PROP_KEY] || {} + } + } + + const tokenOpt = extractConfig(config, token) + switch (tokenOpt) { + case TOKEN_IN_URL: + return { + url: `${url}?${TOKEN_PARAM_NAME}=${token}`, + opts: config[WS_OPT_PROP_KEY] || {} + } + case TOKEN_IN_HEADER: + return { + url, + opts: Object.assign({}, config[WS_OPT_PROP_KEY] || {}, { + headers: { + [AUTH_HEADER]: token + } + }) + } + default: + } +} diff --git a/packages/@jsonql/security/src/socket/ws-token-fn.js b/packages/@jsonql/security/src/socket/ws-token-fn.js new file mode 100644 index 0000000000000000000000000000000000000000..02acc19fe95dd127ccfb5ae7558d4f4ae7a9efa9 --- /dev/null +++ b/packages/@jsonql/security/src/socket/ws-token-fn.js @@ -0,0 +1,76 @@ +// collection of WebSocket extra token for server side +// ported from ws-server +const { + TOKEN_PARAM_NAME, + TOKEN_DELIVER_LOCATION_PROP_KEY, + TOKEN_IN_URL, + TOKEN_IN_HEADER, + AUTH_CHECK_HEADER, + BEARER +} = require('jsonql-constants') +const url = require('url') +const { parse } = require('querystring') + +/** + * What the name said + * @param {string} uri to decode + * @return {string|boolean} token or false means didn't find it + */ +function getTokenFromUrl(uri) { + const { query } = url.parse(uri) + if (query) { + const params = parse(query) + return params[TOKEN_PARAM_NAME] || false + } + return false +} + +/** + * Check if there is the Bearer in the header string as well + * @param {string} header extracted Authorisation header + * @return {string} token + */ +function processAuthTokenHeader(header) { + return header && typeof header === 'string' ? header.replace(BEARER, '').trim() : false +} + +/** + * new method to get the token from the header + * @param {*} req request object + * @return {string} token + */ +function getTokenFromHeader(headers) { + + return processAuthTokenHeader(headers[AUTH_CHECK_HEADER]) || false +} + +/** + * New combine get token method using the options to switch + * @param {object} opts configuration + * @param {object} req request object + * @return {string|boolean} false on failed + */ +function getWsAuthToken(opts, req) { + switch (opts[TOKEN_DELIVER_LOCATION_PROP_KEY]) { + case TOKEN_IN_URL: + if (req.url) { + return getTokenFromUrl(req.url) + } + case TOKEN_IN_HEADER: + if (req.headers) { + return getTokenFromHeader(req.headers) + } + default: + + return false + } +} + + +module.exports = { + getTokenFromUrl, + processAuthTokenHeader, + getTokenFromHeader, + getWsAuthToken +} + diff --git a/packages/@jsonql/security/tests/cache.test.js b/packages/@jsonql/security/tests/cache.test.js index 6bc16a5ce39c8640e7a4fc5d4d208a8254c583c4..589ea86fb0b10c6d69e1acae08fbe074db7379c1 100644 --- a/packages/@jsonql/security/tests/cache.test.js +++ b/packages/@jsonql/security/tests/cache.test.js @@ -26,7 +26,7 @@ test(`Test the CSRF token get and store`, t => { }) -test(`Test our own DiyCache`, t => { +test(`Test the new JsonqlStore features`, t => { const store = getCache() const check = isCacheObj(store) diff --git a/packages/@jsonql/security/tests/encrypt-decrypt.test.js b/packages/@jsonql/security/tests/encrypt-decrypt.test.js index cf9bcbd5ab1665b85ba40b77950902e07607f98b..b8c4a492779981d613ec597373024cac31531e11 100644 --- a/packages/@jsonql/security/tests/encrypt-decrypt.test.js +++ b/packages/@jsonql/security/tests/encrypt-decrypt.test.js @@ -1,5 +1,5 @@ const test = require('ava') -const fsx = require('fs-extra') +// const fsx = require('fs-extra') const { join } = require('path') const { encryptWithPublicPem, diff --git a/packages/@jsonql/security/tests/fn.test.js b/packages/@jsonql/security/tests/fn.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b5245e3f0c795b2654fc2d6c0467f2516f8d8645 --- /dev/null +++ b/packages/@jsonql/security/tests/fn.test.js @@ -0,0 +1,45 @@ +// just testing if some function exist or not +const test = require('ava') +const { + BEARER, + AUTH_CHECK_HEADER +} = require('jsonql-constants') +const { + extractConfig, + prepareConnectConfig, + + getTokenFromUrl, + processAuthTokenHeader, + getTokenFromHeader, + getWsAuthToken +} = require('../main') + +const isf = f => typeof f === 'function' + + +test(`import bunch of methods should be in the export for node`, t => { + + t.true(isf(extractConfig)) + + t.true(isf(prepareConnectConfig)) + + t.true(isf( getTokenFromUrl)) + + t.true(isf(processAuthTokenHeader)) + + t.true(isf(getTokenFromHeader)) + + t.true(isf(getWsAuthToken)) + +}) + +test(`Try to see if we pass different authorisation header and come out with the same token`, t => { + const token = '123456789' + const header1 = {[AUTH_CHECK_HEADER]: token} + const header2 = {[AUTH_CHECK_HEADER]: `${BEARER} ${token}`} + + const result1 = getTokenFromHeader(header1) + const result2 = getTokenFromHeader(header2) + + t.is(result1, result2) +}) \ No newline at end of file diff --git a/packages/@jsonql/security/tests/jwt-decode.test.js b/packages/@jsonql/security/tests/jwt-decode.test.js index 105290b1cf5baed374bd06341df4a2734a4aaee3..e7001f1852fa17f365bf26e2b2d80f9e981a62e8 100644 --- a/packages/@jsonql/security/tests/jwt-decode.test.js +++ b/packages/@jsonql/security/tests/jwt-decode.test.js @@ -5,7 +5,7 @@ const { join } = require('path') const fsx = require('fs-extra') // const jwtDecode = require('jwt-decode') const debug = require('debug')('jsonql-jwt:test:jwt-decode') -const { RSA_ALGO } = require('jsonql-constants') +// const { RSA_ALGO } = require('jsonql-constants') const { loginResultToJwt, createTokenValidator, @@ -13,12 +13,12 @@ const { tokenValidator } = require('../main') -const payload = {name: 'Joel', msg: 'Hello world!'}; -const baseDir = join(__dirname, 'fixtures', 'keys'); +const payload = {name: 'Joel', msg: 'Hello world!'} +const baseDir = join(__dirname, 'fixtures', 'keys') // start test test.before( t => { - let publicKey = fsx.readFileSync(join(baseDir, 'publicKey.pem')); - t.context.privateKey = fsx.readFileSync(join(baseDir, 'privateKey.pem')); + let publicKey = fsx.readFileSync(join(baseDir, 'publicKey.pem')) + t.context.privateKey = fsx.readFileSync(join(baseDir, 'privateKey.pem')) t.context.validator = createTokenValidator({ useJwt: true, @@ -26,9 +26,9 @@ test.before( t => { }) t.context.publicKey = publicKey - const options = {exp: 5}; // expired in 5 seconds + const options = {exp: 5} // expired in 5 seconds const token = loginResultToJwt(t.context.privateKey, options)(payload) - t.context.token = token; + t.context.token = token }); test('try to see if its able to decode the token encrypted by rsa key', t => { @@ -40,7 +40,7 @@ test('try to see if its able to decode the token encrypted by rsa key', t => { test('Check if the tokenValidator able to return the correct configuration', t => { let time = Math.floor(Date.now() / 1000) + (60 * 60) - let config = { exp: time }; + let config = { exp: time } let opts = tokenValidator(config) debug(opts) diff --git a/packages/@jsonql/security/tests/rsa-keys.test.js b/packages/@jsonql/security/tests/rsa-keys.test.js index 5d810c50a642deaecf381982867f2c2c0789a513..8755cbe3e188fb66bf6d9a5a659da347a72ca67d 100644 --- a/packages/@jsonql/security/tests/rsa-keys.test.js +++ b/packages/@jsonql/security/tests/rsa-keys.test.js @@ -1,5 +1,5 @@ // testing if the rsa generate key pair are working or not -const test = require('ava'); +const test = require('ava') const { join } = require('path') const fsx = require('fs-extra') const debug = require('debug')('jsonql-jwt:test:rsa-keys') diff --git a/packages/@jsonql/security/tests/rsa-pem-keys.test.js b/packages/@jsonql/security/tests/rsa-pem-keys.test.js index 3b54c03ebb5bf1e7205b8fe70b3c72015924b2d7..0417bd6e88c3c920b26563db96c226591d8b7a29 100644 --- a/packages/@jsonql/security/tests/rsa-pem-keys.test.js +++ b/packages/@jsonql/security/tests/rsa-pem-keys.test.js @@ -22,15 +22,15 @@ test.cb('It should able to generate pair of public and private keys', t => { 'rsa-pem', '--outputDir', outputDir - ]); + ]) t.context.ps.stdout.on('data', data => { - debug('stdout: ', data.toString()); - }); + debug('stdout: ', data.toString()) + }) t.context.ps.stderr.on('data', data => { - debug('stderr: ', data.toString()); - }); + debug('stderr: ', data.toString()) + }) t.context.ps.on('close', code => { debug(`(1) Exited with ${code}`) @@ -38,8 +38,8 @@ test.cb('It should able to generate pair of public and private keys', t => { t.truthy(fsx.existsSync(pubKey)) t.truthy(fsx.existsSync(prvKey)) - t.end(); - }); + t.end() + }) }) diff --git a/packages/@jsonql/socketio/src/options.js b/packages/@jsonql/socketio/src/options.js new file mode 100644 index 0000000000000000000000000000000000000000..de2eeafcfeb8131b2d05b217d743c4f8f65a038f --- /dev/null +++ b/packages/@jsonql/socketio/src/options.js @@ -0,0 +1,9 @@ +// this should move to the framework specific module +/* +const AVAILABLE_METHODS = [ + IO_ROUNDTRIP_LOGIN, + IO_HANDSHAKE_LOGIN +] +// this is for socket.io +loginMethod: createConfig(IO_HANDSHAKE_LOGIN, [STRING_TYPE], {[ENUM_KEY]: AVAILABLE_METHODS}), +*/ \ No newline at end of file diff --git a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js index 252d36824cbdf5875b80a019a45100b013c37f09..ffff9b2ad3f123656dcbb097fd7520732202c75c 100644 --- a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js +++ b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlWsClient=e()}(this,(function(){"use strict";var t=Array.isArray,e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},r="object"==typeof e&&e&&e.Object===Object&&e,n="object"==typeof self&&self&&self.Object===Object&&self,o=r||n||Function("return this")(),i=o.Symbol,a=Object.prototype,u=a.hasOwnProperty,c=a.toString,s=i?i.toStringTag:void 0;var f=Object.prototype.toString;var l=i?i.toStringTag:void 0;function p(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":l&&l in Object(t)?function(t){var e=u.call(t,s),r=t[s];try{t[s]=void 0;var n=!0}catch(t){}var o=c.call(t);return n&&(e?t[s]=r:delete t[s]),o}(t):function(t){return f.call(t)}(t)}function h(t,e){return function(r){return t(e(r))}}var v=h(Object.getPrototypeOf,Object);function g(t){return null!=t&&"object"==typeof t}var d=Function.prototype,y=Object.prototype,_=d.toString,b=y.hasOwnProperty,m=_.call(Object);function j(t){if(!g(t)||"[object Object]"!=p(t))return!1;var e=v(t);if(null===e)return!0;var r=b.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&_.call(r)==m}function w(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&A(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var B=function(e){return t(e)?e:[e]},V=function(t,e){void 0===e&&(e=!0);try{return JSON.parse(t)}catch(r){if(e)return t;throw new Error(r)}},G=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},H=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},K=function(t){return V("string"==typeof t?t:JSON.stringify(t))},Y=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},Q=function(){return!1},X=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,B(t))}),Reflect.apply(t,null,r))}};function Z(t,e){return t===e||t!=t&&e!=e}function tt(t,e){for(var r=t.length;r--;)if(Z(t[r][0],e))return r;return-1}var et=Array.prototype.splice;function rt(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},rt.prototype.set=function(t,e){var r=this.__data__,n=tt(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function ot(t){if(!nt(t))return!1;var e=p(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var it,at=o["__core-js_shared__"],ut=(it=/[^.]+$/.exec(at&&at.keys&&at.keys.IE_PROTO||""))?"Symbol(src)_1."+it:"";var ct=Function.prototype.toString;function st(t){if(null!=t){try{return ct.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ft=/^\[object .+?Constructor\]$/,lt=Function.prototype,pt=Object.prototype,ht=lt.toString,vt=pt.hasOwnProperty,gt=RegExp("^"+ht.call(vt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function dt(t){return!(!nt(t)||(e=t,ut&&ut in e))&&(ot(t)?gt:ft).test(st(t));var e}function yt(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return dt(r)?r:void 0}var _t=yt(o,"Map"),bt=yt(Object,"create");var mt=Object.prototype.hasOwnProperty;var jt=Object.prototype.hasOwnProperty;function wt(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Gt(t){return null!=t&&Vt(t.length)&&!ot(t)}var Ht="object"==typeof exports&&exports&&!exports.nodeType&&exports,Kt=Ht&&"object"==typeof module&&module&&!module.nodeType&&module,Yt=Kt&&Kt.exports===Ht?o.Buffer:void 0,Qt=(Yt?Yt.isBuffer:void 0)||function(){return!1},Xt={};Xt["[object Float32Array]"]=Xt["[object Float64Array]"]=Xt["[object Int8Array]"]=Xt["[object Int16Array]"]=Xt["[object Int32Array]"]=Xt["[object Uint8Array]"]=Xt["[object Uint8ClampedArray]"]=Xt["[object Uint16Array]"]=Xt["[object Uint32Array]"]=!0,Xt["[object Arguments]"]=Xt["[object Array]"]=Xt["[object ArrayBuffer]"]=Xt["[object Boolean]"]=Xt["[object DataView]"]=Xt["[object Date]"]=Xt["[object Error]"]=Xt["[object Function]"]=Xt["[object Map]"]=Xt["[object Number]"]=Xt["[object Object]"]=Xt["[object RegExp]"]=Xt["[object Set]"]=Xt["[object String]"]=Xt["[object WeakMap]"]=!1;var Zt,te="object"==typeof exports&&exports&&!exports.nodeType&&exports,ee=te&&"object"==typeof module&&module&&!module.nodeType&&module,re=ee&&ee.exports===te&&r.process,ne=function(){try{var t=ee&&ee.require&&ee.require("util").types;return t||re&&re.binding&&re.binding("util")}catch(t){}}(),oe=ne&&ne.isTypedArray,ie=oe?(Zt=oe,function(t){return Zt(t)}):function(t){return g(t)&&Vt(t.length)&&!!Xt[p(t)]};function ae(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ue=Object.prototype.hasOwnProperty;function ce(t,e,r){var n=t[e];ue.call(t,e)&&Z(n,r)&&(void 0!==r||e in t)||kt(t,e,r)}var se=/^(?:0|[1-9]\d*)$/;function fe(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&se.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(we);function Ee(t,e){return Se(function(t,e,r){return e=je(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=je(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=$e.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!nt(r))return!1;var n=typeof e;return!!("number"==n?Gt(r)&&fe(e,r.length):"string"==n&&e in r)&&Z(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0))},ar=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ur=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!or(e)(t)})).length)})).length:e.length>e.filter((function(t){return!ir(r,t)})).length},cr=function(t,e){if(void 0===e&&(e=null),j(t)){if(!e)return!0;if(ir(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return void 0===r||(!1!==(e=ar(t))?!ur({arg:r},e):!or(t)(r))})).length)})).length}return!1},sr=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(cr,null,a);case"array"===t:return!ir(e.arg);case!1!==(r=ar(t)):return!ur(e,r);default:return!or(t)(e.arg)}},fr=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},lr=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!ir(e))throw new We("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!ir(t))throw console.info(t),new We("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?fr(t,a):t,index:r,param:a,optional:i}}));default:throw new De("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Xe(e)&&!(r.type.length>r.type.filter((function(e){return sr(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return sr(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},pr=h(Object.keys,Object),hr=Object.prototype.hasOwnProperty;function vr(t){return Gt(t)?pe(t):function(t){if(!Wt(t))return pr(t);var e=[];for(var r in Object(t))hr.call(t,r)&&"constructor"!=r&&e.push(r);return e}(t)}function gr(t,e){return t&&Nt(t,e,vr)}function dr(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new St;++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=2&r?new dr:void 0;for(i.set(t,e),i.set(e,t);++f0){if(!1!==this.$get(t,!0)){var n=this.searchMapEvt(t);if(n.length){var o=n[0][3],i=(this.checkMaxStore(t,e),this);return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var a=i.getMaxStore(t),u=-1;if(a>0){var c=i.$call(t,o,r);if(Reflect.apply(c,i,e),-1===(u=i.checkMaxStore(t)))return i.$off(t),-1}return u}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,n))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var a=Array.from(i.get(t)),u=a.length,c=!1,s=0;s0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,r=t[3];return e=r,!!Nn.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var n=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',n),r.delete(t),n}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];var o=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||o.add(r)}else this.checkContentExist(r,o)||(this.logger("(addToStore) insert new",r),o.add(r));else o.add(r);return t.set(e,o),[t,o.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,this.logger("(addToLazyStore) size: "+u),u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Cn.set(this,t)},r.normalStore.get=function(){return Cn.get(this)},r.lazyStore.set=function(t){Rn.set(this,t)},r.lazyStore.get=function(){return Rn.get(this)},Object.defineProperties(e.prototype,r),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=null,this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(t){var e=function(t){switch(!0){case!0===Tn(t):return t;case!0===Pn(t):return new RegExp(t);default:return!1}}(t);if(Tn(e))return this.__pattern__=e,this.$suspend();throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof e+'" instead')},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];if(this.logger("($queue) get called"),!0===this.__suspend_state__){if(Tn(this.__pattern__)){var n=this.__pattern__.test(t);if(!n)return!1}this.logger("($queue) added to $queue",e),this.queueStore.add([t].concat(e))}return!!this.__suspend_state__},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=null,this.logger("(release) was called with "+e+(r?' for "'+r+'"':"")+" item"+(e>1?"s":"")),e>0){var n=Array.from(this.queueStore);this.queueStore.clear(),this.logger("(release queue)",n),n.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(Mn)))),Ln=function(t){var e=t.toLowerCase();return e.indexOf("http")>-1?e.indexOf("https")>-1?e.replace("https","wss"):e.replace("http","ws"):e},Wn=function(t,e){B(e).forEach((function(e){t.$off(H(e,"emit_reply"))}))};function Dn(t,e,r){G(t,"error")?r(t.error):G(t,"data")?Reflect.apply(e,null,[].concat(t.data)):r({message:"UKNNOWN RESULT!",error:t})}function Jn(t,e,r,n,o){void 0===n&&(n=[]);var i=H(e,"emit_reply");return o("actionCall: "+i+" --\x3e "+r,n),t.$trigger(i,[r,B(n)]),new Promise((function(n,i){var a=H(e,r,"onResult");t.$on(a,(function(t){o("got the first result",t),Dn(t,n,i)}))}))}var Un=function(t,e,r,n,o,i){return xe(t,"send",Q,(function(){return i("running call getter method"),function(){for(var t=[],a=arguments.length;a--;)t[a]=arguments[a];return On(t,o.params,!0).then((function(t){return i("execute send",r,n,t),Jn(e,r,n,t,i)})).catch((function(t){i("send error",t),e.$call(H(r,n,"onError"),[new We(n,t)])}))}}))};function In(t,e,r,n,o){return function(){for(var i=[],a=arguments.length;a--;)i[a]=arguments[a];return On(i,n.params,!0).then((function(n){return Jn(t,e,r,n,o)})).catch(Ue)}}var Bn=function(t,e,r,n,o,i){return[Ae(t,"myNamespace",r),e,r,n,o,i]},Vn=function(t,e,r,n,o,i){return[xe(t,"onResult",(function(t){Y(t)&&e.$on(H(r,n,"onResult"),(function(o){Dn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(H(r,n,"onError"),t)}))}))})),e,r,n,o,i]},Gn=function(t,e,r,n,o,i){return[xe(t,"onMessage",(function(t){if(Y(t)){e.$only(H(r,n,"onMessage"),(function(o){i("onMessageCallback",o),Dn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(H(r,n,"onError"),t)}))}))}})),e,r,n,o,i]},Hn=function(t,e,r,n,o,i){return[xe(t,"onError",(function(t){Y(t)&&e.$only(H(r,n,"onError"),t)})),e,r,n,o,i]};function Kn(t,e,r,n,o,i){var a=[Bn,Vn,Gn,Hn,Un];return Reflect.apply(X,null,a)(n,o,t,e,r,i)}function Yn(t,e,r){var n=t.log,o={};for(var i in r){var a=r[i];for(var u in a){var c=a[u];o=Ae(o,u,Kn(i,u,c,In(e,i,u,c,n),e,n))}}return[o,t,e,r]}function Qn(t,e,r){return[xe(t,"onReady",(function(t){Y(t)&&r.$only("onReady",t)})),e,r]}function Xn(t,e,r,n){return[xe(t,"onError",(function(t){if(Y(t))for(var e in n)r.$on(H(e,"onError"),t)})),e,r]}var Zn,to,eo,ro=function(t,e,r){return[Ae(t,e.loginHandlerName,(function(t){if(t&&wn(t))return e.log("Received __login__ with "+t),r.$trigger("__login__",[t]);throw new We(e.loginHandlerName,"Unexpected token "+t)})),e,r]},no=function(t,e,r){return[Ae(t,e.logoutHandlerName,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__logout__",t)})),e,r]},oo=function(t,e,r){return[xe(t,"onLogin",(function(t){Y(t)&&r.$only("onLogin",t)})),e,r]};function io(t,e,r){return X(ro,no,oo)(t,e,r)}function ao(t,e,r){return(0,e.log)("[1] setupConnectPropKey"),[t=Ae(t,"connected",!1,!0),e,r]}function uo(t,e,r){var n=e.log;return n("[2] setupConnectEvtListener"),r.$on("__connect__",(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];n("setupConnectEvtListener pass and do nothing at the moment",t)})),[t,e,r]}function co(t,e,r){var n=e.log;return n("[3] setupConnectedEvtListener"),r.$on("__connected__",(function(){var e;t.connected=!0;var o=r.$release();return n("CONNECTED_EVENT_NAME",!0,"queue count",o),(e={}).connected=!0,e})),[t,e,r]}function so(t,e,r){var n=e.log;return n("[4] setupDisconnectListener"),r.$on("__disconnect__",(function(){var e;return t.connected=!1,n("CONNECTED_EVENT_NAME",!1),(e={}).connected=!1,e})),[t,e,r]}function fo(t,e,r){var n=e.disconnectHandlerName;return(0,e.log)("[5] setupDisconectAction"),Ae(t,n,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__disconnect__",t)}))}function lo(t,e,r){var n=function(t,e,r){var n=[ao,uo,co,so,fo];return Reflect.apply(X,null,n)(t,e,r)}(t,e,r);return n.verifyEventEmitter=function(){return r.is},n.eventEmitter=e.eventEmitter,n.log=e.log,r.$trigger("__connect__",[e,r]),!0===e.suspendOnStart&&e.$releaseNamespace(),n}var po=["roundtip","handshake"],ho={};ho.standalone=Sn(!1,["boolean"]),ho.debugOn=Sn(!1,["boolean"]),ho.loginHandlerName=Sn("login",["string"]),ho.logoutHandlerName=Sn("logout",["string"]),ho.disconnectHandlerName=Sn("disconnect",["string"]),ho.switchUserHandlerName=Sn("switch-user",["string"]),ho.hostname=Sn(!1,["string"]),ho.namespace=Sn("jsonql",["string"]),ho.wsOptions=Sn({},["object"]),ho.contract=Sn({},["object"],((Zn={}).checker=function(t){return!!function(t){return j(t)&&(G(t,"query")||G(t,"mutation")||G(t,"socket"))}(t)&&t},Zn)),ho.enableAuth=Sn(!1,["boolean"]),ho.token=Sn(!1,["string"]),ho.loginMethod=Sn("handshake",["string"],((to={}).enumv=po,to)),ho.useJwt=Sn(!0,["boolean","string"]),ho.authStrKey=Sn(null,["string"]),ho.suspendOnStart=Sn(!1,["boolean"]);var vo={};vo.serverType=Sn(null,["string"],((eo={}).alias="socketClientType",eo));var go=Object.assign(ho,vo),yo={log:null,eventEmitter:null,nspClient:null,nspAuthClient:null,wssPath:"",publicNamespace:"public",privateNamespace:"private"};function _o(t){return Promise.resolve(t).then((function(t){return t.hostname||(t.hostname=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new We(t)}}()),t.wssPath=Ln([t.hostname,t.namespace].join("/"),t.serverType),t.log=kn(t),t.eventEmitter=function(t){var e=t.log,r=t.eventEmitter;return r?(e("eventEmitter is:",r.name),r):new Fn(t.log)}(t),t}))}function bo(t){var e=function(t){var e=t.contract,r=t.enableAuth,n=function(t){var e="jsonql";return t.enableAuth?[[e,t.privateNamespace].join("/"),[e,t.publicNamespace].join("/")]:[e]}(t),o=r?He(e):function(t,e){var r,n={};for(var o in t){var i=t[o];n[o]=i}return{size:1,nspGroup:(r={},r[e]=n,r),publicNamespace:e}}(e.socket,n[0]);return Object.assign(o,{namespaces:n})}(t),r=t.eventEmitter,n=t.log,o=e.namespaces;return n("namespaces",o),!0===t.suspendOnStart&&(t.$suspendNamepsace=function(){return o.forEach((function(t){return r.$suspendEvent(t)}))},t.$releaseNamespace=function(){return r.$release()},t.$suspendNamepsace()),{opts:t,nspMap:e,ee:r}}function mo(t){return function(e){return void 0===e&&(e={}),_o(e).then(bo).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return function(t,e,r){var n=[Yn,Qn,Xn];return t.enableAuth&&n.push(io),n.push(lo),Reflect.apply(X,null,n)(t,r,e.nspGroup)}(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("[jsonql-ws-core-client init error]",t)}))}}function jo(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),function(n){return void 0===n&&(n={}),function(t,e,r){var n=Object.assign(go,e),o=Object.assign(yo,r);return En(t,n,o)}(n,e,r).then(mo(t))}}function wo(t,e){var r=e.hostname,n=e.wssPath,o=e.wsOptions,i=e.nspClient,a=e.log,u=t?[r,t].join("/"):n;return a("createNspClient --\x3e ",u),i(u,o)}var Oo=function(t,e,r,n){var o=n.log;r.$on("__logout__",(function(){var i=getPrivateNamespace(e);o("__logout__ event triggered"),function(t,e,r){e.forEach((function(e){t.$trigger(H(e,"onError"),[{message:r,namespace:e}])}))}(r,[i],"__logout__"),o("logout from "+i),Wn(r,i),t[i]=null,notLoginWsListerner(i,r,n)}))};function So(t,e){return function(r,n,o){var i=r.log,a=n.namespaces,u=function(t){return t.length>1&&t[0]}(a);return a.map((function(n){var c=u===n;if(i(n," --\x3e "+(c?"private":"public")+" nsp --\x3e ",!1!==e[n]),e[n]){i("[call bindWsHandler]",c,n);var s=[n,e[n],o,c,r];Reflect.apply(t,null,s)}else i("binding notLoginWsHandler to "+n),function(t,e,r){var n=r.log;e.$only(H(t,"emit_reply"),(function(r,o){n("[notLoginListerner] hijack the ws call",t,r,o);var i={message:"NOT LOGIN"};e.$call(H(t,r,"onError"),[i]),e.$call(H(t,r,"onResult"),[{error:i}])}))}(n,o,r);return c&&(i("Has private and add logoutEvtHandler"),Oo(e,a,o,r)),c}))}}var Eo={version:"version: 1.2.0 module: umd",serverType:"ws"},$o=null;"undefined"!=typeof WebSocket?$o=WebSocket:"undefined"!=typeof MozWebSocket?$o=MozWebSocket:void 0!==e?$o=e.WebSocket||e.MozWebSocket:"undefined"!=typeof window?$o=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&($o=self.WebSocket||self.MozWebSocket);var ko=$o;function xo(t,e,r,n,o,i){return t.onopen=function(){t.send(Ge("__intercom__",["__ping__",Ie()]))},t.onmessage=function(a){try{var u=Qe(a.data);setTimeout((function(){t.terminate()}),50);var c=new e(r,Object.assign(i,u));n(c)}catch(t){o(t)}},t.onerror=function(t){o(t)},t}function Ao(t,e,r){return new Promise((function(n,o){return xo(new t(e,r),t,e,n,o,r)}))}function No(t,e,r){var n=r.log;return!1===e?function(e,r){void 0===r&&(r={});var o=Ln(e);return n("nspClient: \n"+o+"\n",r),Ao(t,o,r)}:function(e,r,o){void 0===o&&(o={});var i=Ln(e),a=r&&"string"==typeof r?i+"?token="+r:i;return n("nspAuthClient: \n"+a+"\n",o),Ao(t,a,o)}}var To="object"==typeof e&&e&&e.Object===Object&&e,Po="object"==typeof self&&self&&self.Object===Object&&self,zo=To||Po||Function("return this")(),Co=zo.Symbol,Ro=Object.prototype,Mo=Ro.hasOwnProperty,qo=Ro.toString,Fo=Co?Co.toStringTag:void 0;var Lo=Object.prototype.toString;var Wo=Co?Co.toStringTag:void 0;function Do(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":Wo&&Wo in Object(t)?function(t){var e=Mo.call(t,Fo),r=t[Fo];try{t[Fo]=void 0;var n=!0}catch(t){}var o=qo.call(t);return n&&(e?t[Fo]=r:delete t[Fo]),o}(t):function(t){return Lo.call(t)}(t)}var Jo=function(t,e){return function(r){return t(e(r))}}(Object.getPrototypeOf,Object);function Uo(t){return null!=t&&"object"==typeof t}var Io=Function.prototype,Bo=Object.prototype,Vo=Io.toString,Go=Bo.hasOwnProperty,Ho=Vo.call(Object);function Ko(t){if(!Uo(t)||"[object Object]"!=Do(t))return!1;var e=Jo(t);if(null===e)return!0;var r=Go.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&Vo.call(r)==Ho}function Yo(t,e){return t===e||t!=t&&e!=e}function Qo(t,e){for(var r=t.length;r--;)if(Yo(t[r][0],e))return r;return-1}var Xo=Array.prototype.splice;function Zo(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},Zo.prototype.set=function(t,e){var r=this.__data__,n=Qo(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function ei(t){if(!ti(t))return!1;var e=Do(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var ri=zo["__core-js_shared__"],ni=function(){var t=/[^.]+$/.exec(ri&&ri.keys&&ri.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();var oi=Function.prototype.toString;var ii=/^\[object .+?Constructor\]$/,ai=Function.prototype,ui=Object.prototype,ci=ai.toString,si=ui.hasOwnProperty,fi=RegExp("^"+ci.call(si).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function li(t){return!(!ti(t)||function(t){return!!ni&&ni in t}(t))&&(ei(t)?fi:ii).test(function(t){if(null!=t){try{return oi.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function pi(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return li(r)?r:void 0}var hi=pi(zo,"Map"),vi=pi(Object,"create");var gi=Object.prototype.hasOwnProperty;var di=Object.prototype.hasOwnProperty;function yi(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Ji(t){return null!=t&&Di(t.length)&&!ei(t)}var Ui="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ii=Ui&&"object"==typeof module&&module&&!module.nodeType&&module,Bi=Ii&&Ii.exports===Ui?zo.Buffer:void 0,Vi=(Bi?Bi.isBuffer:void 0)||function(){return!1},Gi={};Gi["[object Float32Array]"]=Gi["[object Float64Array]"]=Gi["[object Int8Array]"]=Gi["[object Int16Array]"]=Gi["[object Int32Array]"]=Gi["[object Uint8Array]"]=Gi["[object Uint8ClampedArray]"]=Gi["[object Uint16Array]"]=Gi["[object Uint32Array]"]=!0,Gi["[object Arguments]"]=Gi["[object Array]"]=Gi["[object ArrayBuffer]"]=Gi["[object Boolean]"]=Gi["[object DataView]"]=Gi["[object Date]"]=Gi["[object Error]"]=Gi["[object Function]"]=Gi["[object Map]"]=Gi["[object Number]"]=Gi["[object Object]"]=Gi["[object RegExp]"]=Gi["[object Set]"]=Gi["[object String]"]=Gi["[object WeakMap]"]=!1;var Hi="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ki=Hi&&"object"==typeof module&&module&&!module.nodeType&&module,Yi=Ki&&Ki.exports===Hi&&To.process,Qi=function(){try{var t=Ki&&Ki.require&&Ki.require("util").types;return t||Yi&&Yi.binding&&Yi.binding("util")}catch(t){}}(),Xi=Qi&&Qi.isTypedArray,Zi=Xi?function(t){return function(e){return t(e)}}(Xi):function(t){return Uo(t)&&Di(t.length)&&!!Gi[Do(t)]};function ta(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ea=Object.prototype.hasOwnProperty;function ra(t,e,r){var n=t[e];ea.call(t,e)&&Yo(n,r)&&(void 0!==r||e in t)||wi(t,e,r)}var na=/^(?:0|[1-9]\d*)$/;function oa(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&na.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(da);function ba(t,e){return _a(function(t,e,r){return e=ga(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=ga(n.length-e,0),a=Array(i);++o1?r[o-1]:void 0,a=o>2?r[2]:void 0;for(i=t.length>3&&"function"==typeof i?(o--,i):void 0,a&&function(t,e,r){if(!ti(r))return!1;var n=typeof e;return!!("number"==n?Ji(r)&&oa(e,r.length):"string"==n&&e in r)&&Yo(r[e],t)}(r[0],r[1],a)&&(i=o<3?void 0:i,o=1),e=Object(e);++n0;)e[r]=arguments[r+1];var n=Ie(),o=[t].concat(e);return o.push(n),Ge("__intercom__",o)}(LOGOUT_EVENT_NAME)),log("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var Ca=function(t,e,r,n){var o=[e];r&&o.push(r),o.push("onError");var i=Reflect.apply(Oa,null,o),a=n.data||n;t.$trigger(i,[a])};function Ra(t,e,r,n,o){var i=o.log,a=2;return n&&(i("Private namespace",t," binding to the DISCONNECT ws.terminate"),za(r,e)),e.onopen=function(){i("=== ws.onopen listened --\x3e",t),r.$trigger("onReady",[t]),0===--a&&r.$off("onReady"),n&&(i("isPrivate and fire the onLogin"),r.$call("onLogin")(t)),r.$only(Oa(t,"emit_reply"),(function(t,r){var n=function(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(Na(t,e,r))}(t,r);i("ws.onopen.send",t,r,n),e.send(n)}))},e.onmessage=function(e){i("ws.onmessage raw payload",e.data);try{var n=function(t,e){void 0===e&&(e=Ea);try{var r,n=Sa(t);if(!1!==(r=Pa(n)))return e("_data",r),{data:Sa(r.__data__),resolverName:r.__event__,type:r.__reply__};throw new ka("payload can not decoded",t)}catch(t){return e("error",t)}}(e.data),o=n.resolverName,a=n.type;switch(i("Respond from server",a,n),a){case"emit_reply":var u=Oa(t,o,"onMessage"),c=r.$call(u)(n);i("EMIT_REPLY_TYPE",u,c);break;case"emit_acknowledge":var s=Oa(t,o,"onResult"),f=r.$call(s)(n);i("ACKNOWLEDGE_REPLY_TYPE",s,f);break;case"error":i("ERROR_KEY"),Ca(r,t,o,n);break;default:i("Unhandled event!",n),Ca(r,t,o,n)}}catch(e){i("ws.onmessage error",e),Ca(r,t,!1,e)}},e.onclose=function(){i("ws.onclose callback")},e.onerror=function(e){i("ws.onerror",e),function(t,e,r){t.$trigger(H(e,"onError"),[r])}(r,t,e)},e}var Ma,qa=(Ma=ko,function(t,e,r){var n=t.log;return n("There is problem here with passing the opts",t),t.nspClient=No(Ma,!1,t),t.nspAuthClient=No(Ma,!0,t),n("[1] bindWebsocketToJsonql",r.name,e),function(t,e,r){r("[2] setup the CONNECT_EVENT_NAME"),e.$only("__connect__",(function(e,n){return r("[3] CONNECT_EVENT_NAME",n),ja(e,t).then((function(t){return So(Ra,t)})).then((function(r){return r(e,t,n)}))}))}(e,r,n),function(t,e,r){var n=t.log,o=e.namespaces;n("[4] loginEventHandler"),r.$only("__login__",(function(e){n("createClient LOGIN_EVENT_NAME $only handler"),Wn(r,o),t.token=e,r.$trigger("__connect__",[t,r])}))}(t,e,r),n("just before returing the values for the next operation from createClientBindingAction"),{opts:t,nspMap:e,ee:r}});return function(t,e){return void 0===t&&(t={}),void 0===e&&(e={}),jo(qa,{},Object.assign({},Eo,e))(t)}})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlWsClient=e()}(this,(function(){"use strict";var t=Array.isArray,e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},r="object"==typeof e&&e&&e.Object===Object&&e,n="object"==typeof self&&self&&self.Object===Object&&self,o=r||n||Function("return this")(),i=o.Symbol,a=Object.prototype,u=a.hasOwnProperty,c=a.toString,s=i?i.toStringTag:void 0;var f=Object.prototype.toString;var l=i?i.toStringTag:void 0;function p(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":l&&l in Object(t)?function(t){var e=u.call(t,s),r=t[s];try{t[s]=void 0;var n=!0}catch(t){}var o=c.call(t);return n&&(e?t[s]=r:delete t[s]),o}(t):function(t){return f.call(t)}(t)}function h(t,e){return function(r){return t(e(r))}}var v=h(Object.getPrototypeOf,Object);function d(t){return null!=t&&"object"==typeof t}var g=Function.prototype,y=Object.prototype,_=g.toString,b=y.hasOwnProperty,m=_.call(Object);function j(t){if(!d(t)||"[object Object]"!=p(t))return!1;var e=v(t);if(null===e)return!0;var r=b.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&_.call(r)==m}function w(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&N(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var B=function(e){return t(e)?e:[e]},H=function(t,e){void 0===e&&(e=!0);try{return JSON.parse(t)}catch(r){if(e)return t;throw new Error(r)}},V=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},G=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},K=function(t){return H("string"==typeof t?t:JSON.stringify(t))},Y=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},Q=function(){return!1},X=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,B(t))}),Reflect.apply(t,null,r))}};function Z(t,e){return t===e||t!=t&&e!=e}function tt(t,e){for(var r=t.length;r--;)if(Z(t[r][0],e))return r;return-1}var et=Array.prototype.splice;function rt(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},rt.prototype.set=function(t,e){var r=this.__data__,n=tt(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function ot(t){if(!nt(t))return!1;var e=p(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var it,at=o["__core-js_shared__"],ut=(it=/[^.]+$/.exec(at&&at.keys&&at.keys.IE_PROTO||""))?"Symbol(src)_1."+it:"";var ct=Function.prototype.toString;function st(t){if(null!=t){try{return ct.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ft=/^\[object .+?Constructor\]$/,lt=Function.prototype,pt=Object.prototype,ht=lt.toString,vt=pt.hasOwnProperty,dt=RegExp("^"+ht.call(vt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function gt(t){return!(!nt(t)||(e=t,ut&&ut in e))&&(ot(t)?dt:ft).test(st(t));var e}function yt(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return gt(r)?r:void 0}var _t=yt(o,"Map"),bt=yt(Object,"create");var mt=Object.prototype.hasOwnProperty;var jt=Object.prototype.hasOwnProperty;function wt(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Vt(t){return null!=t&&Ht(t.length)&&!ot(t)}var Gt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Kt=Gt&&"object"==typeof module&&module&&!module.nodeType&&module,Yt=Kt&&Kt.exports===Gt?o.Buffer:void 0,Qt=(Yt?Yt.isBuffer:void 0)||function(){return!1},Xt={};Xt["[object Float32Array]"]=Xt["[object Float64Array]"]=Xt["[object Int8Array]"]=Xt["[object Int16Array]"]=Xt["[object Int32Array]"]=Xt["[object Uint8Array]"]=Xt["[object Uint8ClampedArray]"]=Xt["[object Uint16Array]"]=Xt["[object Uint32Array]"]=!0,Xt["[object Arguments]"]=Xt["[object Array]"]=Xt["[object ArrayBuffer]"]=Xt["[object Boolean]"]=Xt["[object DataView]"]=Xt["[object Date]"]=Xt["[object Error]"]=Xt["[object Function]"]=Xt["[object Map]"]=Xt["[object Number]"]=Xt["[object Object]"]=Xt["[object RegExp]"]=Xt["[object Set]"]=Xt["[object String]"]=Xt["[object WeakMap]"]=!1;var Zt,te="object"==typeof exports&&exports&&!exports.nodeType&&exports,ee=te&&"object"==typeof module&&module&&!module.nodeType&&module,re=ee&&ee.exports===te&&r.process,ne=function(){try{var t=ee&&ee.require&&ee.require("util").types;return t||re&&re.binding&&re.binding("util")}catch(t){}}(),oe=ne&&ne.isTypedArray,ie=oe?(Zt=oe,function(t){return Zt(t)}):function(t){return d(t)&&Ht(t.length)&&!!Xt[p(t)]};function ae(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ue=Object.prototype.hasOwnProperty;function ce(t,e,r){var n=t[e];ue.call(t,e)&&Z(n,r)&&(void 0!==r||e in t)||kt(t,e,r)}var se=/^(?:0|[1-9]\d*)$/;function fe(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&se.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(we);function Ee(t,e){return Se(function(t,e,r){return e=je(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=je(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=$e.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!nt(r))return!1;var n=typeof e;return!!("number"==n?Vt(r)&&fe(e,r.length):"string"==n&&e in r)&&Z(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0))},ar=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ur=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!or(e)(t)})).length)})).length:e.length>e.filter((function(t){return!ir(r,t)})).length},cr=function(t,e){if(void 0===e&&(e=null),j(t)){if(!e)return!0;if(ir(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return void 0===r||(!1!==(e=ar(t))?!ur({arg:r},e):!or(t)(r))})).length)})).length}return!1},sr=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(cr,null,a);case"array"===t:return!ir(e.arg);case!1!==(r=ar(t)):return!ur(e,r);default:return!or(t)(e.arg)}},fr=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},lr=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!ir(e))throw new De("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!ir(t))throw console.info(t),new De("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?fr(t,a):t,index:r,param:a,optional:i}}));default:throw new We("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Xe(e)&&!(r.type.length>r.type.filter((function(e){return sr(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return sr(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},pr=h(Object.keys,Object),hr=Object.prototype.hasOwnProperty;function vr(t){return Vt(t)?pe(t):function(t){if(!Dt(t))return pr(t);var e=[];for(var r in Object(t))hr.call(t,r)&&"constructor"!=r&&e.push(r);return e}(t)}function dr(t,e){return t&&xt(t,e,vr)}function gr(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new St;++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=2&r?new gr:void 0;for(i.set(t,e),i.set(e,t);++f0){if(!1!==this.$get(t,!0)){var n=this.searchMapEvt(t);if(n.length){var o=n[0][3],i=(this.checkMaxStore(t,e),this);return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var a=i.getMaxStore(t),u=-1;if(a>0){var c=i.$call(t,o,r);if(Reflect.apply(c,i,e),-1===(u=i.checkMaxStore(t)))return i.$off(t),-1}return u}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,n))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var a=Array.from(i.get(t)),u=a.length,c=!1,s=0;s0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,r=t[3];return e=r,!!xn.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var n=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',n),r.delete(t),n}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];var o=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||o.add(r)}else this.checkContentExist(r,o)||(this.logger("(addToStore) insert new",r),o.add(r));else o.add(r);return t.set(e,o),[t,o.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,this.logger("(addToLazyStore) size: "+u),u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Cn.set(this,t)},r.normalStore.get=function(){return Cn.get(this)},r.lazyStore.set=function(t){Rn.set(this,t)},r.lazyStore.get=function(){return Rn.get(this)},Object.defineProperties(e.prototype,r),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=null,this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(t){var e=function(t){switch(!0){case!0===Tn(t):return t;case!0===Pn(t):return new RegExp(t);default:return!1}}(t);if(Tn(e))return this.__pattern__=e,this.$suspend();throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof e+'" instead')},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];if(this.logger("($queue) get called"),!0===this.__suspend_state__){if(Tn(this.__pattern__)){var n=this.__pattern__.test(t);if(!n)return!1}this.logger("($queue) added to $queue",e),this.queueStore.add([t].concat(e))}return!!this.__suspend_state__},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=null,this.logger("(release) was called with "+e+(r?' for "'+r+'"':"")+" item"+(e>1?"s":"")),e>0){var n=Array.from(this.queueStore);this.queueStore.clear(),this.logger("(release queue)",n),n.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(Mn)))),Fn=function(t){var e=t.toLowerCase();return e.indexOf("http")>-1?e.indexOf("https")>-1?e.replace("https","wss"):e.replace("http","ws"):e},Dn=function(t,e){B(e).forEach((function(e){t.$off(G(e,"emit_reply"))}))};function Wn(t,e,r){V(t,"error")?r(t.error):V(t,"data")?Reflect.apply(e,null,[].concat(t.data)):r({message:"UKNNOWN RESULT!",error:t})}function Un(t,e,r,n,o){void 0===n&&(n=[]);var i=G(e,"emit_reply");return o("actionCall: "+i+" --\x3e "+r,n),t.$trigger(i,[r,B(n)]),new Promise((function(n,i){var a=G(e,r,"onResult");t.$on(a,(function(t){o("got the first result",t),Wn(t,n,i)}))}))}var In=function(t,e,r,n,o,i){return Ae(t,"send",Q,(function(){return i("running call getter method"),function(){for(var t=[],a=arguments.length;a--;)t[a]=arguments[a];return On(t,o.params,!0).then((function(t){return i("execute send",r,n,t),Un(e,r,n,t,i)})).catch((function(t){i("send error",t),e.$call(G(r,n,"onError"),[new De(n,t)])}))}}))};function Jn(t,e,r,n,o){return function(){for(var i=[],a=arguments.length;a--;)i[a]=arguments[a];return On(i,n.params,!0).then((function(n){return Un(t,e,r,n,o)})).catch(Ie)}}var Bn=function(t,e,r,n,o,i){return[Ne(t,"myNamespace",r),e,r,n,o,i]},Hn=function(t,e,r,n,o,i){return[Ae(t,"onResult",(function(t){Y(t)&&e.$on(G(r,n,"onResult"),(function(o){Wn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(G(r,n,"onError"),t)}))}))})),e,r,n,o,i]},Vn=function(t,e,r,n,o,i){return[Ae(t,"onMessage",(function(t){if(Y(t)){e.$only(G(r,n,"onMessage"),(function(o){i("onMessageCallback",o),Wn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(G(r,n,"onError"),t)}))}))}})),e,r,n,o,i]},Gn=function(t,e,r,n,o,i){return[Ae(t,"onError",(function(t){Y(t)&&e.$only(G(r,n,"onError"),t)})),e,r,n,o,i]};function Kn(t,e,r,n,o,i){var a=[Bn,Hn,Vn,Gn,In];return Reflect.apply(X,null,a)(n,o,t,e,r,i)}function Yn(t,e,r){var n=t.log,o={};for(var i in r){var a=r[i];for(var u in a){var c=a[u];o=Ne(o,u,Kn(i,u,c,Jn(e,i,u,c,n),e,n))}}return[o,t,e,r]}function Qn(t,e,r){return[Ae(t,"onReady",(function(t){Y(t)&&r.$only("onReady",t)})),e,r]}function Xn(t,e,r,n){return[Ae(t,"onError",(function(t){if(Y(t))for(var e in n)r.$on(G(e,"onError"),t)})),e,r]}var Zn,to,eo=function(t,e,r){return[Ne(t,e.loginHandlerName,(function(t){if(t&&wn(t))return e.log("Received __login__ with "+t),r.$trigger("__login__",[t]);throw new De(e.loginHandlerName,"Unexpected token "+t)})),e,r]},ro=function(t,e,r){return[Ne(t,e.logoutHandlerName,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__logout__",t)})),e,r]},no=function(t,e,r){return[Ae(t,"onLogin",(function(t){Y(t)&&r.$only("onLogin",t)})),e,r]};function oo(t,e,r){return X(eo,ro,no)(t,e,r)}function io(t,e,r){return(0,e.log)("[1] setupConnectPropKey"),[t=Ne(t,"connected",!1,!0),e,r]}function ao(t,e,r){var n=e.log;return n("[2] setupConnectEvtListener"),r.$on("__connect__",(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];n("setupConnectEvtListener pass and do nothing at the moment",t)})),[t,e,r]}function uo(t,e,r){var n=e.log;return n("[3] setupConnectedEvtListener"),r.$on("__connected__",(function(){var e;t.connected=!0;var o=r.$release();return n("CONNECTED_EVENT_NAME",!0,"queue count",o),(e={}).connected=!0,e})),[t,e,r]}function co(t,e,r){var n=e.log;return n("[4] setupDisconnectListener"),r.$on("__disconnect__",(function(){var e;return t.connected=!1,n("CONNECTED_EVENT_NAME",!1),(e={}).connected=!1,e})),[t,e,r]}function so(t,e,r){var n=e.disconnectHandlerName;return(0,e.log)("[5] setupDisconectAction"),Ne(t,n,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__disconnect__",t)}))}function fo(t,e,r){var n=function(t,e,r){var n=[io,ao,uo,co,so];return Reflect.apply(X,null,n)(t,e,r)}(t,e,r);return n.verifyEventEmitter=function(){return r.is},n.eventEmitter=e.eventEmitter,n.log=e.log,r.$trigger("__connect__",[e,r]),!0===e.suspendOnStart&&e.$releaseNamespace(),n}var lo={};lo.standalone=Sn(!1,["boolean"]),lo.debugOn=Sn(!1,["boolean"]),lo.loginHandlerName=Sn("login",["string"]),lo.logoutHandlerName=Sn("logout",["string"]),lo.disconnectHandlerName=Sn("disconnect",["string"]),lo.switchUserHandlerName=Sn("switch-user",["string"]),lo.hostname=Sn(!1,["string"]),lo.namespace=Sn("jsonql",["string"]),lo.wsOptions=Sn({},["object"]),lo.contract=Sn({},["object"],((Zn={}).checker=function(t){return!!function(t){return j(t)&&(V(t,"query")||V(t,"mutation")||V(t,"socket"))}(t)&&t},Zn)),lo.enableAuth=Sn(!1,["boolean"]),lo.token=Sn(!1,["string"]),lo.csrf=Sn("X-CSRF-Token",["string"]),lo.useJwt=Sn(!0,["boolean","string"]),lo.suspendOnStart=Sn(!1,["boolean"]);var po={};po.serverType=Sn(null,["string"],((to={}).alias="socketClientType",to));var ho=Object.assign(lo,po),vo={log:null,eventEmitter:null,nspClient:null,nspAuthClient:null,wssPath:"",publicNamespace:"public",privateNamespace:"private"};function go(t){return Promise.resolve(t).then((function(t){return t.hostname||(t.hostname=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new De(t)}}()),t.wssPath=Fn([t.hostname,t.namespace].join("/"),t.serverType),t.log=kn(t),t.eventEmitter=function(t){var e=t.log,r=t.eventEmitter;return r?(e("eventEmitter is:",r.name),r):new Ln(t.log)}(t),t}))}function yo(t){var e=function(t){var e=t.contract,r=t.enableAuth,n=function(t){var e="jsonql";return t.enableAuth?[[e,t.privateNamespace].join("/"),[e,t.publicNamespace].join("/")]:[e]}(t),o=r?Ge(e):function(t,e){var r,n={};for(var o in t){var i=t[o];n[o]=i}return{size:1,nspGroup:(r={},r[e]=n,r),publicNamespace:e}}(e.socket,n[0]);return Object.assign(o,{namespaces:n})}(t),r=t.eventEmitter,n=t.log,o=e.namespaces;return n("namespaces",o),!0===t.suspendOnStart&&(t.$suspendNamepsace=function(){return o.forEach((function(t){return r.$suspendEvent(t)}))},t.$releaseNamespace=function(){return r.$release()},t.$suspendNamepsace()),{opts:t,nspMap:e,ee:r}}function _o(t){return function(e){return void 0===e&&(e={}),go(e).then(yo).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return function(t,e,r){var n=[Yn,Qn,Xn];return t.enableAuth&&n.push(oo),n.push(fo),Reflect.apply(X,null,n)(t,r,e.nspGroup)}(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("[jsonql-ws-core-client init error]",t)}))}}function bo(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),function(n){return void 0===n&&(n={}),function(t,e,r){var n=Object.assign(ho,e),o=Object.assign(vo,r);return En(t,n,o)}(n,e,r).then(_o(t))}}var mo=function(t,e,r,n){var o=n.log;r.$on("__logout__",(function(){var i=getPrivateNamespace(e);o("__logout__ event triggered"),function(t,e,r){e.forEach((function(e){t.$trigger(G(e,"onError"),[{message:r,namespace:e}])}))}(r,[i],"__logout__"),o("logout from "+i),Dn(r,i),t[i]=null,notLoginWsListerner(i,r,n)}))};function jo(t,e){return function(r,n,o){var i=r.log,a=n.namespaces,u=function(t){return t.length>1&&t[0]}(a);return a.map((function(n){var c=u===n;if(i(n," --\x3e "+(c?"private":"public")+" nsp --\x3e ",!1!==e[n]),e[n]){i("[call bindWsHandler]",c,n);var s=[n,e[n],o,c,r];Reflect.apply(t,null,s)}else i("binding notLoginWsHandler to "+n),function(t,e,r){var n=r.log;e.$only(G(t,"emit_reply"),(function(r,o){n("[notLoginListerner] hijack the ws call",t,r,o);var i={message:"NOT LOGIN"};e.$call(G(t,r,"onError"),[i]),e.$call(G(t,r,"onResult"),[{error:i}])}))}(n,o,r);return c&&(i("Has private and add logoutEvtHandler"),mo(e,a,o,r)),c}))}}function wo(t,e){var r=e.hostname,n=e.wssPath,o=e.nspClient,i=e.log,a=t?[r,t].join("/"):n;return i("createNspClient --\x3e ",a),o(a,e)}var Oo,So,Eo,$o,ko,Ao,No,xo,To;Error;try{"undefined"!=typeof window&&window.atob&&window.atob.bind(window)}catch(t){}Sn("HS256",["string"]),Sn(!1,["boolean","number","string"],((Oo={}).alias="exp",Oo.optional=!0,Oo)),Sn(!1,["boolean","number","string"],((So={}).alias="nbf",So.optional=!0,So)),Sn(!1,["boolean","string"],((Eo={}).alias="iss",Eo.optional=!0,Eo)),Sn(!1,["boolean","string"],(($o={}).alias="sub",$o.optional=!0,$o)),Sn(!1,["boolean","string"],((ko={}).alias="iss",ko.optional=!0,ko)),Sn(!1,["boolean"],((Ao={}).optional=!0,Ao)),Sn(!1,["boolean","string"],((No={}).optional=!0,No)),Sn(!1,["boolean","string"],((xo={}).optional=!0,xo)),Sn(!1,["boolean"],((To={}).optional=!0,To));var Po=require("jsonql-constants"),zo=Po.TOKEN_PARAM_NAME,Co=Po.AUTH_HEADER,Ro=Po.TOKEN_DELIVER_LOCATION_PROP_KEY,Mo=Po.TOKEN_IN_URL,qo=Po.TOKEN_IN_HEADER,Lo=Po.WS_OPT_PROP_KEY;function Fo(t,e,r){var n;if(void 0===r&&(r=!1),!1===r)return{url:t,opts:e[Lo]||{}};switch(e[Ro]||Mo){case Mo:return{url:t+"?"+zo+"="+r,opts:e[Lo]||{}};case qo:return{url:t,opts:Object.assign({},e[Lo]||{},{headers:(n={},n[Co]=r,n)})}}}var Do="object"==typeof e&&e&&e.Object===Object&&e,Wo="object"==typeof self&&self&&self.Object===Object&&self,Uo=Do||Wo||Function("return this")(),Io=Uo.Symbol;var Jo=Array.isArray,Bo=Object.prototype,Ho=Bo.hasOwnProperty,Vo=Bo.toString,Go=Io?Io.toStringTag:void 0;var Ko=Object.prototype.toString;var Yo=Io?Io.toStringTag:void 0;function Qo(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":Yo&&Yo in Object(t)?function(t){var e=Ho.call(t,Go),r=t[Go];try{t[Go]=void 0;var n=!0}catch(t){}var o=Vo.call(t);return n&&(e?t[Go]=r:delete t[Go]),o}(t):function(t){return Ko.call(t)}(t)}function Xo(t){return null!=t&&"object"==typeof t}var Zo=Io?Io.prototype:void 0,ti=Zo?Zo.toString:void 0;function ei(t){if("string"==typeof t)return t;if(Jo(t))return function(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(o,i),function(t,e){for(var r=t.length;r--&&oi(e,t[r],0)>-1;);return r}(o,i)+1).join("")}function bi(t){return function(t){return"number"==typeof t||Xo(t)&&"[object Number]"==Qo(t)}(t)&&t!=+t}function mi(t){return"string"==typeof t||!Jo(t)&&Xo(t)&&"[object String]"==Qo(t)}var ji=function(t){return!mi(t)&&!bi(parseFloat(t))},wi=function(t){return""!==_i(t)&&mi(t)},Oi=function(t){return null!=t&&"boolean"==typeof t},Si=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==_i(t)&&(!1===e||!0===e&&null!==t)},Ei=function(t,e){return void 0===e&&(e=""),!!Jo(t)&&(""===e||""===_i(e)||!(t.filter((function(t){return!function(t){switch(t){case"number":return ji;case"string":return wi;case"boolean":return Oi;default:return Si}}(e)(t)})).length>0))};var $i=function(t,e){return function(r){return t(e(r))}}(Object.getPrototypeOf,Object),ki=Function.prototype,Ai=Object.prototype,Ni=ki.toString,xi=Ai.hasOwnProperty,Ti=Ni.call(Object);function Pi(t){if(!Xo(t)||"[object Object]"!=Qo(t))return!1;var e=$i(t);if(null===e)return!0;var r=xi.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&Ni.call(r)==Ti}var zi=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Ci=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error);function Ri(t,e){return t===e||t!=t&&e!=e}function Mi(t,e){for(var r=t.length;r--;)if(Ri(t[r][0],e))return r;return-1}var qi=Array.prototype.splice;function Li(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},Li.prototype.set=function(t,e){var r=this.__data__,n=Mi(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function Di(t){if(!Fi(t))return!1;var e=Qo(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var Wi=Uo["__core-js_shared__"],Ui=function(){var t=/[^.]+$/.exec(Wi&&Wi.keys&&Wi.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();var Ii=Function.prototype.toString;var Ji=/^\[object .+?Constructor\]$/,Bi=Function.prototype,Hi=Object.prototype,Vi=Bi.toString,Gi=Hi.hasOwnProperty,Ki=RegExp("^"+Vi.call(Gi).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Yi(t){return!(!Fi(t)||function(t){return!!Ui&&Ui in t}(t))&&(Di(t)?Ki:Ji).test(function(t){if(null!=t){try{return Ii.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function Qi(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return Yi(r)?r:void 0}var Xi=Qi(Uo,"Map"),Zi=Qi(Object,"create");var ta=Object.prototype.hasOwnProperty;var ea=Object.prototype.hasOwnProperty;function ra(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function $a(t){return null!=t&&Ea(t.length)&&!Di(t)}var ka="object"==typeof exports&&exports&&!exports.nodeType&&exports,Aa=ka&&"object"==typeof module&&module&&!module.nodeType&&module,Na=Aa&&Aa.exports===ka?Uo.Buffer:void 0,xa=(Na?Na.isBuffer:void 0)||function(){return!1},Ta={};Ta["[object Float32Array]"]=Ta["[object Float64Array]"]=Ta["[object Int8Array]"]=Ta["[object Int16Array]"]=Ta["[object Int32Array]"]=Ta["[object Uint8Array]"]=Ta["[object Uint8ClampedArray]"]=Ta["[object Uint16Array]"]=Ta["[object Uint32Array]"]=!0,Ta["[object Arguments]"]=Ta["[object Array]"]=Ta["[object ArrayBuffer]"]=Ta["[object Boolean]"]=Ta["[object DataView]"]=Ta["[object Date]"]=Ta["[object Error]"]=Ta["[object Function]"]=Ta["[object Map]"]=Ta["[object Number]"]=Ta["[object Object]"]=Ta["[object RegExp]"]=Ta["[object Set]"]=Ta["[object String]"]=Ta["[object WeakMap]"]=!1;var Pa="object"==typeof exports&&exports&&!exports.nodeType&&exports,za=Pa&&"object"==typeof module&&module&&!module.nodeType&&module,Ca=za&&za.exports===Pa&&Do.process,Ra=function(){try{var t=za&&za.require&&za.require("util").types;return t||Ca&&Ca.binding&&Ca.binding("util")}catch(t){}}(),Ma=Ra&&Ra.isTypedArray,qa=Ma?function(t){return function(e){return t(e)}}(Ma):function(t){return Xo(t)&&Ea(t.length)&&!!Ta[Qo(t)]};function La(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var Fa=Object.prototype.hasOwnProperty;function Da(t,e,r){var n=t[e];Fa.call(t,e)&&Ri(n,r)&&(void 0!==r||e in t)||ua(t,e,r)}var Wa=/^(?:0|[1-9]\d*)$/;function Ua(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&Wa.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(tu);function nu(t,e){return ru(function(t,e,r){return e=Za(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Za(n.length-e,0),a=Array(i);++o1?r[o-1]:void 0,a=o>2?r[2]:void 0;for(i=t.length>3&&"function"==typeof i?(o--,i):void 0,a&&function(t,e,r){if(!Fi(r))return!1;var n=typeof e;return!!("number"==n?$a(r)&&Ua(e,r.length):"string"==n&&e in r)&&Ri(r[e],t)}(r[0],r[1],a)&&(i=o<3?void 0:i,o=1),e=Object(e);++n0;)e[r]=arguments[r+1];var n=Je(),o=[t].concat(e);return o.push(n),Ve("__intercom__",o)}(LOGOUT_EVENT_NAME)),log("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var Eu=function(t,e,r,n){var o=[e];r&&o.push(r),o.push("onError");var i=Reflect.apply(yu,null,o),a=n.data||n;t.$trigger(i,[a])};function $u(t,e,r,n,o){var i=o.log,a=2;return n&&(i("Private namespace",t," binding to the DISCONNECT ws.terminate"),Su(r,e)),e.onopen=function(){i("=== ws.onopen listened --\x3e",t),r.$trigger("onReady",[t]),0===--a&&r.$off("onReady"),n&&(i("isPrivate and fire the onLogin"),r.$call("onLogin")(t)),r.$only(yu(t,"emit_reply"),(function(t,r){var n=function(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(ju(t,e,r))}(t,r);i("ws.onopen.send",t,r,n),e.send(n)}))},e.onmessage=function(e){i("ws.onmessage raw payload",e.data);try{var n=function(t,e){void 0===e&&(e=bu);try{var r,n=_u(t);if(!1!==(r=Ou(n)))return e("_data",r),{data:_u(r.__data__),resolverName:r.__event__,type:r.__reply__};throw new Ci("payload can not decoded",t)}catch(t){return e("error",t)}}(e.data),o=n.resolverName,a=n.type;switch(i("Respond from server",a,n),a){case"emit_reply":var u=yu(t,o,"onMessage"),c=r.$call(u)(n);i("EMIT_REPLY_TYPE",u,c);break;case"emit_acknowledge":var s=yu(t,o,"onResult"),f=r.$call(s)(n);i("ACKNOWLEDGE_REPLY_TYPE",s,f);break;case"error":i("ERROR_KEY"),Eu(r,t,o,n);break;default:i("Unhandled event!",n),Eu(r,t,o,n)}}catch(e){i("ws.onmessage error",e),Eu(r,t,!1,e)}},e.onclose=function(){i("ws.onclose callback")},e.onerror=function(e){i("ws.onerror",e),function(t,e,r){t.$trigger(G(e,"onError"),[r])}(r,t,e)},e}var ku,Au=(ku=lu,function(t,e,r){var n=t.log;return n("There is problem here with passing the opts",t),t.nspClient=vu(ku),!0===t.enableAuth&&(t.nspAuthClient=vu(ku,!0)),n("[1] bindWebsocketToJsonql",r.$name,e),function(t,e,r){r("[2] setup the CONNECT_EVENT_NAME"),e.$only("__connect__",(function(e,n){return r("[3] CONNECT_EVENT_NAME",n),du(e,t).then((function(t){return jo($u,t)})).then((function(r){return r(e,t,n)}))}))}(e,r,n),function(t,e,r){var n=t.log,o=e.namespaces;n("[4] loginEventHandler"),r.$only("__login__",(function(e){n("createClient LOGIN_EVENT_NAME $only handler"),Dn(r,o),t.token=e,r.$trigger("__connect__",[t,r])}))}(t,e,r),n("just before returing the values for the next operation from createClientBindingAction"),{opts:t,nspMap:e,ee:r}});return function(t,e){return void 0===t&&(t={}),void 0===e&&(e={}),bo(Au,fu,Object.assign({},su,e))(t)}})); //# sourceMappingURL=jsonql-ws-client.umd.js.map diff --git a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js.map b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js.map index 3b57c88f9abfb6e6cb40a89df044e9c3166c78cd..30eb2e1d70347aa1b3b2e5c393ffceb6c0204d9b 100644 --- a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js.map +++ b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-ws-client.umd.js","sources":["../../../ws-client-core/node_modules/lodash-es/_arraySome.js"],"sourcesContent":["/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n"],"names":["SetCache"],"mappings":"2vxBAAAA"} \ No newline at end of file +{"version":3,"file":"jsonql-ws-client.umd.js","sources":["../../../ws-client-core/node_modules/lodash-es/isObjectLike.js","../../../ws-client-core/node_modules/lodash-es/_arraySome.js","../../../ws-client-core/node_modules/@to1source/event/src/suspend.js","../node_modules/lodash-es/_strictIndexOf.js","../node_modules/lodash-es/_unicodeToArray.js","../node_modules/lodash-es/_hasUnicode.js","../node_modules/jsonql-params-validator/src/string.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/_apply.js","../node_modules/jsonql-params-validator/src/options/construct-config.js"],"sourcesContent":["/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n/*\nwe use a different way to do the same watch thing now\nthis.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n})\n*/\nimport { getRegex, isRegExp } from './utils'\n\nimport BaseClass from './base'\n\nexport default class SuspendClass extends BaseClass {\n\n constructor() {\n super()\n\n // suspend, release and queue\n this.__suspend_state__ = null\n // to do this proper we don't use a new prop to hold the event name pattern\n this.__pattern__ = null\n\n\n this.queueStore = new Set()\n }\n\n /**\n * start suspend\n * @return {void}\n */\n $suspend() {\n this.logger(`---> SUSPEND ALL OPS <---`)\n this.__suspend__(true)\n }\n\n /**\n * release the queue\n * @return {void}\n */\n $release() {\n this.logger(`---> RELEASE SUSPENDED QUEUE <---`)\n this.__suspend__(false)\n }\n\n /**\n * suspend event by pattern\n * @param {string} pattern the pattern search matches the event name\n * @return {void}\n */\n $suspendEvent(pattern) {\n const regex = getRegex(pattern)\n if (isRegExp(regex)) {\n this.__pattern__ = regex\n return this.$suspend()\n }\n throw new Error(`We expect a pattern variable to be string or RegExp, but we got \"${typeof regex}\" instead`)\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {string} evt the event name\n * @param {*} args unknown number of arguments\n * @return {boolean} true when added or false when it's not\n */\n $queue(evt, ...args) {\n this.logger('($queue) get called')\n if (this.__suspend_state__ === true) {\n if (isRegExp(this.__pattern__)) { // it's better then check if its not null\n // check the pattern and decide if we want to suspend it or not\n let found = this.__pattern__.test(evt)\n if (!found) {\n return false\n }\n }\n this.logger('($queue) added to $queue', args)\n // @TODO there shouldn't be any duplicate, but how to make sure?\n this.queueStore.add([evt].concat(args))\n // return this.queueStore.size\n }\n return !!this.__suspend_state__\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n __suspend__(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend_state__\n this.__suspend_state__ = value\n this.logger(`($suspend) Change from \"${lastValue}\" --> \"${value}\"`)\n if (lastValue === true && value === false) {\n this.__release__()\n }\n } else {\n throw new Error(`$suspend only accept Boolean value! we got ${typeof value}`)\n }\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n __release__() {\n let size = this.queueStore.size\n let pattern = this.__pattern__\n this.__pattern__ = null\n this.logger(`(release) was called with ${size}${pattern ? ' for \"' + pattern + '\"': ''} item${size > 1 ? 's' : ''}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('(release queue)', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n\n return size\n }\n}\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false\n}\n\nexport default checkIsString\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\n// import checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n }\n if (optional === true) {\n base[OPTIONAL_KEY] = true\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias\n }\n return base\n}\n"],"names":["SetCache","Object"],"mappings":"g5BAAA,w9vBCAAA,qnWCAAC,sooBCAA,qxBCAA,yECAA,yiBCAA,+lGCAA,o5DCAA,0DCAA,o3JCAA,oxBCAA"} \ No newline at end of file diff --git a/packages/@jsonql/ws/main.js.map b/packages/@jsonql/ws/main.js.map deleted file mode 100644 index d0663bcd385568b38b8c24ffff9af6a7fbe9beab..0000000000000000000000000000000000000000 --- a/packages/@jsonql/ws/main.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"main.js","sources":["../../ws-client-core/node_modules/lodash-es/isArray.js","node_modules/rollup-plugin-node-globals/src/global.js","../../ws-client-core/node_modules/lodash-es/_objectToString.js","../../ws-client-core/node_modules/lodash-es/_overArg.js","../../ws-client-core/node_modules/lodash-es/isObjectLike.js","../../ws-client-core/node_modules/lodash-es/_arrayMap.js","../../ws-client-core/node_modules/lodash-es/_baseSlice.js","../../ws-client-core/node_modules/lodash-es/_baseFindIndex.js","../../ws-client-core/node_modules/lodash-es/_baseIsNaN.js","../../ws-client-core/node_modules/lodash-es/_strictIndexOf.js","../../ws-client-core/node_modules/lodash-es/_asciiToArray.js","../../ws-client-core/node_modules/lodash-es/_hasUnicode.js","../../ws-client-core/node_modules/lodash-es/_unicodeToArray.js","../../ws-client-core/node_modules/jsonql-utils/src/generic.js","../../ws-client-core/node_modules/lodash-es/_listCacheClear.js","../../ws-client-core/node_modules/lodash-es/eq.js","../../ws-client-core/node_modules/lodash-es/_stackDelete.js","../../ws-client-core/node_modules/lodash-es/_stackGet.js","../../ws-client-core/node_modules/lodash-es/_stackHas.js","../../ws-client-core/node_modules/lodash-es/isObject.js","../../ws-client-core/node_modules/lodash-es/_toSource.js","../../ws-client-core/node_modules/lodash-es/_getValue.js","../../ws-client-core/node_modules/lodash-es/_hashDelete.js","../../ws-client-core/node_modules/lodash-es/_isKeyable.js","../../ws-client-core/node_modules/lodash-es/_createBaseFor.js","../../ws-client-core/node_modules/lodash-es/_copyArray.js","../../ws-client-core/node_modules/lodash-es/_isPrototype.js","../../ws-client-core/node_modules/lodash-es/isLength.js","../../ws-client-core/node_modules/lodash-es/stubFalse.js","../../ws-client-core/node_modules/lodash-es/_baseUnary.js","../../ws-client-core/node_modules/lodash-es/_safeGet.js","../../ws-client-core/node_modules/lodash-es/_baseTimes.js","../../ws-client-core/node_modules/lodash-es/_isIndex.js","../../ws-client-core/node_modules/lodash-es/_nativeKeysIn.js","../../ws-client-core/node_modules/lodash-es/identity.js","../../ws-client-core/node_modules/lodash-es/_apply.js","../../ws-client-core/node_modules/lodash-es/constant.js","../../ws-client-core/node_modules/lodash-es/_shortOut.js","../../ws-client-core/node_modules/jsonql-errors/src/enum-error.js","../../ws-client-core/node_modules/jsonql-errors/src/type-error.js","../../ws-client-core/node_modules/jsonql-errors/src/checker-error.js","../../ws-client-core/node_modules/jsonql-errors/src/validation-error.js","../../ws-client-core/node_modules/jsonql-utils/src/contract.js","../../ws-client-core/node_modules/jsonql-utils/src/timestamp.js","../../ws-client-core/node_modules/jsonql-utils/src/params-api.js","../../ws-client-core/node_modules/jsonql-utils/src/namespace.js","../../ws-client-core/node_modules/jsonql-utils/src/socket.js","../../ws-client-core/src/callers/intercom-methods.js","../../ws-client-core/node_modules/jsonql-params-validator/src/number.js","../../ws-client-core/node_modules/jsonql-params-validator/src/string.js","../../ws-client-core/node_modules/jsonql-params-validator/src/boolean.js","../../ws-client-core/node_modules/jsonql-params-validator/src/any.js","../../ws-client-core/node_modules/jsonql-params-validator/src/constants.js","../../ws-client-core/node_modules/jsonql-params-validator/src/combine.js","../../ws-client-core/node_modules/jsonql-params-validator/src/array.js","../../ws-client-core/node_modules/jsonql-params-validator/src/object.js","../../ws-client-core/node_modules/jsonql-params-validator/src/validator.js","../../ws-client-core/node_modules/lodash-es/_setCacheAdd.js","../../ws-client-core/node_modules/lodash-es/_setCacheHas.js","../../ws-client-core/node_modules/lodash-es/_arraySome.js","../../ws-client-core/node_modules/lodash-es/_cacheHas.js","../../ws-client-core/node_modules/lodash-es/_mapToArray.js","../../ws-client-core/node_modules/lodash-es/_setToArray.js","../../ws-client-core/node_modules/lodash-es/_arrayPush.js","../../ws-client-core/node_modules/lodash-es/_arrayFilter.js","../../ws-client-core/node_modules/lodash-es/stubArray.js","../../ws-client-core/node_modules/lodash-es/_matchesStrictComparable.js","../../ws-client-core/node_modules/lodash-es/_baseHasIn.js","../../ws-client-core/node_modules/lodash-es/_baseProperty.js","../../ws-client-core/node_modules/lodash-es/negate.js","../../ws-client-core/node_modules/lodash-es/_baseFindKey.js","../../ws-client-core/node_modules/jsonql-params-validator/src/is-in-array.js","../../ws-client-core/node_modules/jsonql-params-validator/src/options/run-validation.js","../../ws-client-core/node_modules/jsonql-params-validator/src/options/check-options-async.js","../../ws-client-core/node_modules/jsonql-params-validator/src/options/construct-config.js","../../ws-client-core/node_modules/jsonql-params-validator/src/options/index.js","../../ws-client-core/node_modules/jsonql-params-validator/index.js","../../ws-client-core/src/utils/get-log-fn.js","../../ws-client-core/node_modules/@to1source/event/src/constants.js","../../ws-client-core/node_modules/@to1source/event/src/utils.js","../../ws-client-core/node_modules/@to1source/event/src/store.js","../../ws-client-core/node_modules/@to1source/event/src/base.js","../../ws-client-core/node_modules/@to1source/event/src/suspend.js","../../ws-client-core/node_modules/@to1source/event/src/store-service.js","../../ws-client-core/node_modules/@to1source/event/src/event-service.js","../../ws-client-core/node_modules/@to1source/event/index.js","../../ws-client-core/src/utils/get-event-emitter.js","../../ws-client-core/src/utils/helpers.js","../../ws-client-core/src/options/constants.js","../../ws-client-core/src/callers/respond-handler.js","../../ws-client-core/src/callers/action-call.js","../../ws-client-core/src/callers/setup-send-method.js","../../ws-client-core/src/callers/setup-resolver.js","../../ws-client-core/src/callers/generator-methods.js","../../ws-client-core/src/callers/global-listener.js","../../ws-client-core/src/callers/setup-auth-methods.js","../../ws-client-core/src/callers/setup-intercom.js","../../ws-client-core/src/callers/setup-final-step.js","../../ws-client-core/src/callers/callers-generator.js","../../ws-client-core/src/options/index.js","../../ws-client-core/src/api.js","../../ws-client-core/src/listener/create-nsp-clients.js","../../ws-client-core/src/listener/trigger-namespaces-on-error.js","../../ws-client-core/src/listener/event-listeners.js","../../ws-client-core/src/listener/namespace-event-listener.js","src/options/index.js","src/core/create-websocket-binding/init-websocket-client.js","src/core/listeners/login-event-listener.js","node_modules/lodash-es/_objectToString.js","node_modules/lodash-es/_overArg.js","node_modules/lodash-es/isObjectLike.js","node_modules/lodash-es/_listCacheClear.js","node_modules/lodash-es/eq.js","node_modules/lodash-es/_stackDelete.js","node_modules/lodash-es/_stackGet.js","node_modules/lodash-es/_stackHas.js","node_modules/lodash-es/isObject.js","node_modules/lodash-es/_toSource.js","node_modules/lodash-es/_getValue.js","node_modules/lodash-es/_hashDelete.js","node_modules/lodash-es/_isKeyable.js","node_modules/lodash-es/_createBaseFor.js","node_modules/lodash-es/_copyArray.js","node_modules/lodash-es/_isPrototype.js","node_modules/lodash-es/isArray.js","node_modules/lodash-es/isLength.js","node_modules/lodash-es/stubFalse.js","node_modules/lodash-es/_baseUnary.js","node_modules/lodash-es/_safeGet.js","node_modules/lodash-es/_baseTimes.js","node_modules/lodash-es/_isIndex.js","node_modules/lodash-es/_nativeKeysIn.js","node_modules/lodash-es/identity.js","node_modules/lodash-es/_apply.js","node_modules/lodash-es/constant.js","node_modules/lodash-es/_shortOut.js","node_modules/jsonql-utils/src/chain-promises.js","src/core/create-nsp.js","node_modules/jsonql-utils/src/generic.js","node_modules/jsonql-errors/src/validation-error.js","node_modules/jsonql-utils/src/timestamp.js","node_modules/jsonql-utils/src/params-api.js","node_modules/jsonql-utils/src/socket.js","src/core/listeners/disconnect-event-listener.js","src/core/listeners/bind-socket-event-handler.js","src/core/listeners/connect-event-listener.js","src/core/create-websocket-binding/bind-websocket-to-jsonql.js","src/node/setup-socket-client-listener.js","src/node-ws-client.js"],"sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg]\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @param {boolean} [t=true] or throw\n * @return {*} json object on success\n */\nexport const parseJson = function(n, t=true) {\n try {\n return JSON.parse(n)\n } catch(e) {\n if (t) {\n return n\n }\n throw new Error(e)\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = n => {\n if (typeof n === 'string') {\n return parseJson(n)\n }\n return parseJson(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== ''\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n\n/**\n * Shorthand method for Object.assign \n * @param {array} args \n * @return {object} merge together object by key \n */\nexport const assign = (...args) => Reflect.apply(Object.assign, Object, args)\n \n/** \n * generic placeholder function\n * @return {boolean} false \n */\nexport const nil = () => false\n\n/**\n * generic turn config into immutatble \n */\nexport const freeze = config => Object.freeze(config)","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError)\n }\n }\n\n static get name() {\n return 'JsonqlEnumError'\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlTypeError.name\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError)\n }\n }\n\n static get name() {\n return 'JsonqlTypeError'\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args)\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError)\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError'\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError'\n }\n}\n","// split the contract into the node side and the generic side\nimport { isObjectHasKey } from './generic'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n SOCKET_NAME,\n QUERY_ARG_NAME,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlResolverNotFoundError } from 'jsonql-errors'\n/**\n * Check if the json is a contract file or not\n * @param {object} contract json object\n * @return {boolean} true\n */\nexport function checkIsContract(contract) {\n return isPlainObject(contract)\n && (\n isObjectHasKey(contract, QUERY_NAME)\n || isObjectHasKey(contract, MUTATION_NAME)\n || isObjectHasKey(contract, SOCKET_NAME)\n )\n}\n\n/**\n * Wrapper method that check if it's contract then return the contract or false\n * @param {object} contract the object to check\n * @return {boolean | object} false when it's not\n */\nexport function isContract(contract) {\n return checkIsContract(contract) ? contract : false\n}\n\n/**\n * Ported from jsonql-params-validator but different\n * if we don't find the socket part then return false\n * @param {object} contract the contract object\n * @return {object|boolean} false on failed\n */\nexport function extractSocketPart(contract) {\n if (isObjectHasKey(contract, SOCKET_NAME)) {\n return contract[SOCKET_NAME]\n }\n return false\n}\n\n/**\n * Extract the args from the payload\n * @param {object} payload to work with\n * @param {string} type of call\n * @return {array} args\n */\nexport function extractArgsFromPayload(payload, type) {\n switch (type) {\n case QUERY_NAME:\n return payload[QUERY_ARG_NAME]\n case MUTATION_NAME:\n return [\n payload[PAYLOAD_PARAM_NAME],\n payload[CONDITION_PARAM_NAME]\n ]\n default:\n throw new JsonqlError(`Unknown ${type} to extract argument from!`)\n }\n}\n\n/**\n * Like what the name said\n * @param {object} contract the contract json\n * @param {string} type query|mutation\n * @param {string} name of the function\n * @return {object} the params part of the contract\n */\nexport function extractParamsFromContract(contract, type, name) {\n try {\n const result = contract[type][name]\n // debug('extractParamsFromContract', result)\n if (!result) {\n // debug(name, type, contract)\n throw new JsonqlResolverNotFoundError(name, type)\n }\n return result\n } catch(e) {\n throw new JsonqlResolverNotFoundError(name, e)\n }\n}\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time\n}\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\n\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isString from 'lodash-es/isString'\nimport isPlainObject from 'lodash-es/isPlainObject'\n\nimport { timestamp } from './timestamp'\nimport { parseJson } from './generic'\n\n/**\n * check if the payload has a timestamp field, then append a new timestamp to it\n * @param {object} payload from the com\n * @return {array} timestamp field with an array value\n */\nexport const handleTimestamp = payload => {\n let ts = payload[TIMESTAMP_PARAM_NAME]\n if (!isArray(ts)) {\n ts = [ts]\n }\n ts.push( timestamp() )\n\n return ts\n}\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? parseJson(payload) : payload\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * extract the resolver name from the payload \n * @param {object} payload\n * @return {string} resolver name \n */\nexport function getResolverFromPayload(payload) {\n const keys = Object.keys(payload)\n return keys.filter(key => key !== TIMESTAMP_PARAM_NAME)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName name of the resolver\n * @param {*} payload what is sending \n * @param {object} extra additonal property we want to merge into the deliverable\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload, extra = {}) {\n return Object.assign({\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }, extra)\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError('utils:params-api:createQuery', { \n message: `expect resolverName to be string and args to be array!`,\n resolverName, \n args \n })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getResolverFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// take out all the namespace related methods in one place for easy to find\nimport {\n JSONQL_PATH,\n PUBLIC_KEY,\n NSP_GROUP,\n PUBLIC_NAMESPACE\n} from 'jsonql-constants'\nimport { extractSocketPart } from './contract'\nconst SOCKET_NOT_FOUND_ERR = `socket not found in contract!`\nconst SIZE = 'size'\n\n/**\n * create the group using publicNamespace when there is only public\n * @param {object} socket from contract\n * @param {string} publicNamespace\n */\nfunction groupPublicNamespace(socket, publicNamespace) {\n let g = {}\n for (let resolverName in socket) {\n let params = socket[resolverName]\n g[resolverName] = params\n }\n return { size: 1, nspGroup: {[publicNamespace]: g}, publicNamespace}\n}\n\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport function groupByNamespace(contract) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n throw new JsonqlError('groupByNamespace', SOCKET_NOT_FOUND_ERR)\n }\n let prop = {\n [NSP_GROUP]: {},\n [PUBLIC_NAMESPACE]: null,\n [SIZE]: 0 \n }\n\n for (let resolverName in socket) {\n let params = socket[resolverName]\n let { namespace } = params\n if (namespace) {\n if (!prop[NSP_GROUP][namespace]) {\n ++prop[SIZE]\n prop[NSP_GROUP][namespace] = {}\n }\n prop[NSP_GROUP][namespace][resolverName] = params\n // get the public namespace\n if (!prop[PUBLIC_NAMESPACE] && params[PUBLIC_KEY]) {\n prop[PUBLIC_NAMESPACE] = namespace\n }\n }\n }\n \n return prop \n}\n\n/**\n * @NOTE ported from jsonql-ws-client\n * Got to make sure the connection order otherwise\n * it will hang\n * @param {object} nspGroup contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspGroup, publicNamespace) {\n let names = [] // need to make sure the order!\n for (let namespace in nspGroup) {\n if (namespace === publicNamespace) {\n names[1] = namespace\n } else {\n names[0] = namespace\n }\n }\n return names\n}\n\n/**\n * @TODO this might change, what if we want to do room with ws\n * 1. there will only be max two namespace\n * 2. when it's normal we will have the stock path as namespace\n * 3. when enableAuth then we will have two, one is jsonql/public + private\n * @param {object} config options\n * @return {array} of namespace(s)\n */\nexport function getNamespace(config) {\n const base = JSONQL_PATH\n if (config.enableAuth) {\n // the public come first @1.0.1 we use the constants instead of the user supplied value\n // @1.0.4 we use the config value again, because we could control this via the post init\n return [\n [ base , config.privateNamespace ].join('/'),\n [ base , config.publicNamespace ].join('/')\n ]\n }\n return [ base ]\n}\n\n/**\n * get the private namespace\n * @param {array} namespaces array\n * @return {*} string on success\n */\nexport function getPrivateNamespace(namespaces) {\n return namespaces.length > 1 ? namespaces[0] : false\n}\n\n/**\n * Got a problem with a contract that is public only the groupByNamespace is wrong\n * which is actually not a problem when using a fallback, but to be sure things in order\n * we could combine with the config to group it\n * @param {object} config configuration\n * @return {object} nspInfo object\n */\nexport function getNspInfoByConfig(config) {\n const { contract, enableAuth } = config\n const namespaces = getNamespace(config)\n let nspInfo = enableAuth ? groupByNamespace(contract)\n : groupPublicNamespace(contract.socket, namespaces[0])\n // add the namespaces into it as well\n return Object.assign(nspInfo, { namespaces })\n}\n\n","// There are the socket related methods ported back from \n// ws-server-core and ws-client-core \nimport {\n WS_REPLY_TYPE,\n WS_EVT_NAME,\n WS_DATA_NAME,\n TIMESTAMP_PARAM_NAME,\n ERROR_KEY,\n EMIT_REPLY_TYPE,\n EMIT_SEND_TYPE,\n ACKNOWLEDGE_REPLY_TYPE\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlValidationError } from 'jsonql-errors' \nimport isString from 'lodash-es/isString'\nimport isArray from 'lodash-es/isArray'\n\nimport { createDeliverable, formatPayload } from './params-api'\nimport { toJson, isObjectHasKey, nil } from './generic'\nimport { timestamp } from './timestamp'\n\nconst PAYLOAD_NOT_DECODED_ERR = 'payload can not decoded'\nconst WS_KEYS = [\n WS_REPLY_TYPE,\n WS_EVT_NAME,\n WS_DATA_NAME\n]\n\n/////////////////////////////////////\n// REPLY FROM SERVER //\n/////////////////////////////////////\n\n/**\n * This will be a event emit from the client using the send method \n * But we have to change the server to understand it\n * @param {string} resolverName name of resolver ot call \n * @param {array} args for the resolver\n * @param {boolean} str true then stringify it \n * @return {object} formatted payload\n */\nexport const createSendPayload = (resolverName, args, str = false) => {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n // the different is we add a additonal type in the payload \n const result = createDeliverable(resolverName, payload, {type: EMIT_SEND_TYPE})\n return str ? JSON.stringify(result) : result\n }\n throw new JsonqlValidationError(`utils:socket:createSendMsg`, { \n resolverName, \n args, \n message: 'expect resolverName to be string and args to be array!'\n })\n}\n\n/**\n * We need to find the TS field and take it out from the previous payload \n * otherwise it will keep on rolling into the structure which is not what we wanted\n * @param {object} data for inspection\n * @return {object} { data: for the data to use, TS if there is any }\n */\nconst getTsFieldFromData = (data) => {\n let obj = {[TIMESTAMP_PARAM_NAME]: [], data: {}}\n if (data[TIMESTAMP_PARAM_NAME]) {\n const ts = data[TIMESTAMP_PARAM_NAME]\n obj[TIMESTAMP_PARAM_NAME] = Array.isArray(ts) ? ts : [ts]\n delete data[TIMESTAMP_PARAM_NAME]\n } \n obj.data = data\n \n return obj\n}\n\n\n/**\n * The ws doesn't have a acknowledge callback like socket.io\n * so we have to DIY one for ws and other that doesn't have it\n * @param {string} type of reply\n * @param {string} resolverName which is replying\n * @param {*} data payload\n * @param {array} [ts= []] the last received ts, if any \n * @return {string} stringify json\n */\nexport const createWsReply = (type, resolverName, data, ts = []) => {\n const obj = getTsFieldFromData(toJson(data))\n ts = ts.concat(obj[TIMESTAMP_PARAM_NAME])\n if (!ts.length) {\n ts.push(timestamp())\n }\n return JSON.stringify({\n data: {\n [WS_REPLY_TYPE]: type,\n [WS_EVT_NAME]: resolverName,\n [WS_DATA_NAME]: obj.data \n },\n [TIMESTAMP_PARAM_NAME]: ts \n })\n}\n\n// extended function \nexport const createReplyMsg = (resolverName, data, ts = []) => (\n createWsReply(EMIT_REPLY_TYPE, resolverName, data, ts)\n)\n\nexport const createAcknowledgeMsg = (resolverName, data, ts = []) => (\n createWsReply(ACKNOWLEDGE_REPLY_TYPE, resolverName, data, ts)\n)\n\n/**\n * @param {string|object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nexport const isWsReply = payload => {\n const json = isString(payload) ? toJson(payload) : payload\n const { data } = json\n if (data) {\n let result = WS_KEYS.filter(key => isObjectHasKey(data, key))\n return (result.length === WS_KEYS.length) ? data : false\n }\n return false\n}\n\n/**\n * @param {string|object} data received data\n * @param {function} [cb=nil] this is for extracting the TS field or when it's error\n * @return {object} false on failed\n */\nexport const extractWsPayload = (payload, cb = nil) => {\n try {\n const json = toJson(payload)\n // now handle the data\n let _data\n if ((_data = isWsReply(json)) !== false) {\n // note the ts property is on its own \n cb('_data', _data)\n \n return {\n data: toJson(_data[WS_DATA_NAME]),\n resolverName: _data[WS_EVT_NAME],\n type: _data[WS_REPLY_TYPE]\n }\n }\n throw new JsonqlError(PAYLOAD_NOT_DECODED_ERR, payload)\n } catch(e) {\n return cb(ERROR_KEY, e)\n }\n}\n","// this will be part of the init client sequence\n// as soon as we create a ws client\n// we listen to the on.connect event \n// then we send a init-ping event back to the server\n// and server issue a csrf token back to use \n// we use this token to create a new client and destroy the old one\nimport {\n INTERCOM_RESOLVER_NAME, \n SOCKET_PING_EVENT_NAME,\n HEADERS_KEY,\n DATA_KEY,\n CSRF_HEADER_KEY\n} from 'jsonql-constants'\nimport { \n createQueryStr, \n extractWsPayload,\n timestamp,\n toJson \n} from 'jsonql-utils/module'\nimport {\n JsonqlError\n} from 'jsonql-errors'\nconst CSRF_HEADER_NOT_EXIST_ERR = 'CSRF header is not in the received payload'\n\n/**\n * Util method \n * @param {string} payload return from server\n * @return {object} the useful bit \n */\nfunction extractSrvPayload(payload) {\n let json = toJson(payload)\n \n if (json && typeof json === 'object') {\n // note this method expect the json.data inside\n return extractWsPayload(json)\n }\n \n throw new JsonqlError('extractSrvPayload', json)\n}\n\n/**\n * call the server to get a csrf token \n * @return {string} formatted payload to send to the server \n */\nfunction createInitPing() {\n const ts = timestamp()\n\n return createQueryStr(INTERCOM_RESOLVER_NAME, [SOCKET_PING_EVENT_NAME, ts])\n}\n\n/**\n * Take the raw on.message result back then decoded it \n * @param {*} payload the raw result from server\n * @return {object} the csrf payload\n */\nfunction extractPingResult(payload) {\n const result = extractSrvPayload(payload)\n \n if (result && result[DATA_KEY] && result[DATA_KEY][CSRF_HEADER_KEY]) {\n return {\n [HEADERS_KEY]: result[DATA_KEY]\n }\n }\n\n throw new JsonqlError('extractPingResult', CSRF_HEADER_NOT_EXIST_ERR)\n}\n\n\n/**\n * Create a generic intercom method\n * @param {string} type the event type \n * @param {array} args if any \n * @return {string} formatted payload to send\n */\nfunction createIntercomPayload(type, ...args) {\n const ts = timestamp()\n let payload = [type].concat(args)\n payload.push(ts)\n return createQueryStr(INTERCOM_RESOLVER_NAME, payload)\n}\n\n\nexport { \n extractSrvPayload,\n createInitPing, \n extractPingResult, \n createIntercomPayload \n}","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false\n}\n\nexport default checkIsString\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nconst ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`\nconst PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`\nconst EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'\nconst UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread'\n\nconst RETURNS_NAME = 'returns'\n\nimport {\n \n DEFAULT_TYPE, // this is a mistake should move back to the validation\n DATA_KEY, \n ERROR_KEY,\n\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n \n ARRAY_TYPE,\n OBJECT_TYPE,\n STRING_TYPE,\n BOOLEAN_TYPE,\n NUMBER_TYPE,\n KEY_WORD,\n OR_SEPERATOR\n} from 'jsonql-constants'\n\n// group all export in one \nexport {\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR,\n DEFAULT_TYPE,\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n ARRAY_TYPE,\n OBJECT_TYPE,\n STRING_TYPE,\n BOOLEAN_TYPE,\n NUMBER_TYPE,\n KEY_WORD,\n OR_SEPERATOR,\n\n RETURNS_NAME,\n\n DATA_KEY, \n ERROR_KEY \n}","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber\n case STRING_TYPE:\n return checkIsString\n case BOOLEAN_TYPE:\n return checkIsBoolean\n default:\n return checkIsAny\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length\n}\n","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\n// import filter from 'lodash-es/filter'\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (_value !== undefined) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true\n }).length)\n }).length;\n }\n }\n return false\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p\n let _args = [arg]\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return Reflect.apply(checkIsObject, null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\n\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n combineFn,\n notEmpty\n} from './index'\n\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n DATA_KEY, \n ERROR_KEY \n} from './constants'\n\n\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\nimport JsonqlError from 'jsonql-errors/src/error'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (arg !== undefined) {\n return arg\n }\n return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlValidationError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return []\n }\n if (!checkIsArray(args)) {\n console.info(args)\n throw new JsonqlValidationError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ))\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ))\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ))\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length:\n let ctn = params.length;\n // this happens when we have those array. type\n let _type = [ DEFAULT_TYPE ]\n // we only looking at the first one, this might be a @BUG\n /*\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n } */\n // if we use the params as guide then the rest will get throw out\n // which is not what we want, instead, anything without the param\n // will get a any type and optional flag\n return args.map((arg, i) => {\n let optional = i >= ctn ? true : !!params[i].optional\n let param = params[i] || { type: _type, name: `_${i}` }\n return {\n arg: optional ? getOptionalValue(arg, param) : arg,\n index: i,\n param,\n optional\n }\n })\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n // v1.4.4 this fixed the problem, the root level optional is from the last fn\n if (p.optional === true || p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport isFunction from 'lodash-es/isFunction'\nimport merge from 'lodash-es/merge'\nimport mapValues from 'lodash-es/mapValues'\n\nimport JsonqlEnumError from 'jsonql-errors/src/enum-error'\nimport JsonqlTypeError from 'jsonql-errors/src/type-error'\nimport JsonqlCheckerError from 'jsonql-errors/src/checker-error'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false\n } catch (e) {\n return false\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // log('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n // log(ENUM_KEY, value[ENUM_KEY])\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n // log(CHECKER_KEY, value[CHECKER_KEY])\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","/// this is port back from the client to share across all projects\n\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:check-options-async')\n\n/**\n * Quick transform\n * @param {object} config that one\n * @param {object} appProps mutation configuration options\n * @return {object} put that arg into the args\n */\nconst configToArgs = (config, appProps) => {\n return Promise.resolve(\n prepareArgsForValidation(config, appProps)\n )\n}\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return configToArgs(config, appProps)\n .then(args1 => runValidation(args1, cb))\n // next if every thing good then pass to final merging\n .then(args2 => merge({}, args2, constProps))\n}\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\n// import checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n }\n if (optional === true) {\n base[OPTIONAL_KEY] = true\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias\n }\n return base\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__'\n\n/**\n * construct the actual end user method, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfigAsync = function(validateSync) {\n /**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n/**\n * copy of above but it's sync, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n getCheckConfigAsync,\n getCheckConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\nimport * as validator from './src/validator'\n// configuration checking\nimport * as jsonqlOptions from './src/options'\n// the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nconst isObject = checkIsObject\nconst isAny = checkIsAny\nconst isString = checkIsString\nconst isBoolean = checkIsBoolean\nconst isNumber = checkIsNumber\nconst isArray = checkIsArray\nconst isNotEmpty = notEmpty\n\nconst normalizeArgs = validator.normalizeArgs\nconst validateSync = validator.validateSync\nconst validateAsync = validator.validateAsync\n\nconst JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO\n\nconst createConfig = jsonqlOptions.createConfig\nconst constructConfig = jsonqlOptions.constructConfigFn\n// construct the final output 1.5.2\nconst checkConfigAsync = jsonqlOptions.getCheckConfigAsync(validator.validateSync)\nconst checkConfig = jsonqlOptions.getCheckConfig(validator.validateSync)\n\nconst inArray = isInArray\nconst isObjectHasKey = isObjectHasKeyFn\n\n// check returns methods \nimport { \n checkReturns, \n checkReturnsAsync, \n checkResolverReturns, \n checkResolverReturnsAsync \n} from './src/returns'\n\n\n// group the in one \nexport {\n JSONQL_PARAMS_VALIDATOR_INFO,\n \n isObject,\n isAny,\n isString,\n isBoolean,\n isNumber,\n isArray,\n isNotEmpty,\n \n inArray,\n isObjectHasKey,\n\n normalizeArgs,\n validateSync,\n validateAsync,\n\n createConfig,\n constructConfig,\n checkConfig,\n checkConfigAsync,\n\n checkReturns, \n checkReturnsAsync, \n checkResolverReturns, \n checkResolverReturnsAsync\n}\n\n\n\n\n\n","// move the get logger stuff here\n\n// it does nothing\nconst dummyLogger = () => {}\n\n/**\n * re-use the debugOn prop to control this log method\n * @param {object} opts configuration\n * @return {function} the log function\n */\nconst getLogger = (opts) => {\n const { debugOn } = opts \n if (debugOn) {\n return (...args) => {\n Reflect.apply(console.info, console, ['[jsonql-ws-client-core]', ...args])\n }\n }\n return dummyLogger\n}\n\n/**\n * Make sure there is a log method\n * @param {object} opts configuration\n * @return {object} opts\n */\nconst getLogFn = opts => {\n const { log } = opts // 1.3.9 if we pass a log method here then we use this\n if (!log || typeof log !== 'function') {\n return getLogger(opts)\n }\n opts.log('---> getLogFn user supplied log function <---', opts)\n return log\n}\n\nexport { getLogFn }","// group all the repetitive message here\n\nexport const TAKEN_BY_OTHER_TYPE_ERR = 'You are trying to register an event already been taken by other type:'\n\n// use constants for type\nexport const ON_TYPE = 'on'\nexport const ONLY_TYPE = 'only'\nexport const ONCE_TYPE = 'once'\nexport const ONLY_ONCE_TYPE = 'onlyOnce'\nexport const MAX_CALL_TYPE = 'maxAllowCall'\nexport const NEG_RETURN = -1\n\nexport const AVAILABLE_TYPES = [\n ON_TYPE,\n ONLY_TYPE,\n ONCE_TYPE,\n ONLY_ONCE_TYPE\n]\n// the type which the callMax can execute on\nexport const ON_MAX_TYPES = [\n ON_TYPE,\n ONLY_TYPE\n]\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n\n/**\n * wrapper to make sure it string\n * @param {*} input whatever\n * @return {string} output\n */\nexport function hashCode2Str(s) {\n return hashCode(s) + ''\n}\n\n/**\n * Just check if a pattern is an RegExp object\n * @param {*} pat whatever\n * @return {boolean} false when its not\n */\nexport function isRegExp(pat) {\n return pat instanceof RegExp\n}\n\n/**\n * check if its string\n * @param {*} arg whatever\n * @return {boolean} false when it's not\n */\nexport function isString(arg) {\n return typeof arg === 'string'\n}\n\n/**\n * check if it's an integer\n * @param {*} num input number\n * @return {boolean}\n */\nexport function isInt(num) {\n if (isString(num)) {\n throw new Error(`Wrong type, we want number!`)\n }\n return !isNaN(parseInt(num))\n}\n\n/**\n * Find from the array by matching the pattern\n * @param {*} pattern a string or RegExp object\n * @return {object} regex object or false when we can not id the input\n */\nexport function getRegex(pattern) {\n switch (true) {\n case isRegExp(pattern) === true:\n return pattern\n case isString(pattern) === true:\n return new RegExp(pattern)\n default:\n return false\n }\n}\n\n\n/**\n * in array\n * @param {array} arr to search\n * @param {*} prop to search\n */\n export const inArray = (arr, prop) => !!arr.filter(v => prop === v).length\n","// Create two WeakMap store as a private keys\nexport const NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap()\nexport const NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap()\n","// setup a base class to put all the don't know where to put methods \nimport { hashCode2Str, isString } from './utils'\nimport { AVAILABLE_TYPES } from './constants'\n\nexport default class BaseClass {\n\n constructor() {}\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n // for id if the instance is this class\n get $name() {\n return 'to1source-event'\n }\n\n // take this down in the next release\n get is() {\n return this.$name\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (!isString(e)) {\n this.logger('(validateEvt)', e)\n\n throw new Error(`Event name must be string type! we got ${typeof e}`)\n }\n })\n\n return true\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n\n return true\n }\n }\n throw new Error(`callback required to be function type! we got ${typeof callback}`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n this.validateEvt(type)\n \n return !!AVAILABLE_TYPES.filter(t => type === t).length\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run) callback:', callback, 'payload:', payload, 'context:', ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n\n return this.$done // return it here first \n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n\n return hashCode2Str(fn.toString())\n }\n} ","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n/*\nwe use a different way to do the same watch thing now\nthis.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n})\n*/\nimport { getRegex, isRegExp } from './utils'\n\nimport BaseClass from './base'\n\nexport default class SuspendClass extends BaseClass {\n\n constructor() {\n super()\n\n // suspend, release and queue\n this.__suspend_state__ = null\n // to do this proper we don't use a new prop to hold the event name pattern\n this.__pattern__ = null\n\n\n this.queueStore = new Set()\n }\n\n /**\n * start suspend\n * @return {void}\n */\n $suspend() {\n this.logger(`---> SUSPEND ALL OPS <---`)\n this.__suspend__(true)\n }\n\n /**\n * release the queue\n * @return {void}\n */\n $release() {\n this.logger(`---> RELEASE SUSPENDED QUEUE <---`)\n this.__suspend__(false)\n }\n\n /**\n * suspend event by pattern\n * @param {string} pattern the pattern search matches the event name\n * @return {void}\n */\n $suspendEvent(pattern) {\n const regex = getRegex(pattern)\n if (isRegExp(regex)) {\n this.__pattern__ = regex\n return this.$suspend()\n }\n throw new Error(`We expect a pattern variable to be string or RegExp, but we got \"${typeof regex}\" instead`)\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {string} evt the event name\n * @param {*} args unknown number of arguments\n * @return {boolean} true when added or false when it's not\n */\n $queue(evt, ...args) {\n this.logger('($queue) get called')\n if (this.__suspend_state__ === true) {\n if (isRegExp(this.__pattern__)) { // it's better then check if its not null\n // check the pattern and decide if we want to suspend it or not\n let found = this.__pattern__.test(evt)\n if (!found) {\n return false\n }\n }\n this.logger('($queue) added to $queue', args)\n // @TODO there shouldn't be any duplicate, but how to make sure?\n this.queueStore.add([evt].concat(args))\n // return this.queueStore.size\n }\n return !!this.__suspend_state__\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n __suspend__(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend_state__\n this.__suspend_state__ = value\n this.logger(`($suspend) Change from \"${lastValue}\" --> \"${value}\"`)\n if (lastValue === true && value === false) {\n this.__release__()\n }\n } else {\n throw new Error(`$suspend only accept Boolean value! we got ${typeof value}`)\n }\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n __release__() {\n let size = this.queueStore.size\n let pattern = this.__pattern__\n this.__pattern__ = null\n this.logger(`(release) was called with ${size}${pattern ? ' for \"' + pattern + '\"': ''} item${size > 1 ? 's' : ''}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('(release queue)', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n\n return size\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport {\n NEG_RETURN,\n ON_MAX_TYPES\n} from './constants'\nimport { isInt, inArray } from './utils'\n\nimport SuspendClass from './suspend'\n\nexport default class StoreService extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger\n }\n this.keep = config.keep\n // for the $done setter\n this.result = config.keep ? [] : null\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n // this is the new throw away map\n this.maxCountStore = new Map()\n }\n\n /**\n * We need this to pre-check the store, otherwise\n * the execution will be unable to determine the number of calls\n * @param {string} evtName event name\n * @return {number} the count of this store\n */\n getMaxStore(evtName) {\n return this.maxCountStore.get(evtName) || NEG_RETURN\n }\n\n /**\n * This is one stop shop to check and munipulate the maxStore\n * @param {*} evtName\n * @param {*} [max=null]\n * @return {number} when return -1 means removed\n */\n checkMaxStore(evtName, max = null) {\n this.logger(`===========================================`)\n this.logger('checkMaxStore start', evtName, max)\n // init the store\n if (max !== null && isInt(max)) {\n // because this is the setup phrase we just return the max value\n this.maxCountStore.set(evtName, max)\n this.logger(`Setup max store for ${evtName} with ${max}`)\n return max\n }\n if (max === null) {\n // first check if this exist in the maxStore\n let value = this.getMaxStore(evtName)\n\n this.logger('getMaxStore value', value)\n\n if (value !== NEG_RETURN) {\n if (value > 0) {\n --value\n }\n if (value > 0) {\n this.maxCountStore.set(evtName, value) // just update the value\n } else {\n this.maxCountStore.delete(evtName) // just remove it\n this.logger(`remove ${evtName} from maxStore`)\n return NEG_RETURN\n }\n }\n return value\n }\n throw new Error(`Expect max to be an integer, but we got ${typeof max} ${max}`)\n }\n\n /**\n * Wrap several get filter ops together to return the callback we are looking for\n * @param {string} evtName to search for\n * @return {array} empty array when not found\n */\n searchMapEvt(evtName) {\n const evts = this.$get(evtName, true) // return in full\n const search = evts.filter(result => {\n const [ ,,,type ] = result\n\n return inArray(ON_MAX_TYPES, type)\n })\n\n return search.length ? search : []\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName] // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger(`(takeFromStore) has \"${evt}\"`, content)\n store.delete(evt)\n\n return content\n }\n\n return false\n }\n throw new Error(`\"${storeName}\" is not supported!`)\n }\n\n /**\n * This was part of the $get. We take it out\n * so we could use a regex to remove more than one event\n * @param {object} store the store to return from\n * @param {string} evt event name\n * @param {boolean} full return just the callback or everything\n * @return {array|boolean} false when not found\n */\n findFromStore(evt, store, full = false) {\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l\n }\n let [, callback,] = l\n\n return callback\n })\n }\n return false\n }\n\n /**\n * Similar to the findFromStore, but remove\n * @param {string} evt event name\n * @param {object} store the store to remove from\n * @return {boolean} false when not found\n */\n removeFromStore(evt, store) {\n if (store.has(evt)) {\n this.logger('($off)', evt)\n\n store.delete(evt)\n\n return true\n }\n return false\n }\n\n /**\n * Take out from addToStore for reuse\n * @param {object} store the store to use\n * @param {string} evt event name\n * @return {object} the set within the store\n */\n getStoreSet(store, evt) {\n let fnSet\n if (store.has(evt)) {\n this.logger(`(addToStore) \"${evt}\" existed`)\n fnSet = store.get(evt)\n } else {\n this.logger(`(addToStore) create new Set for \"${evt}\"`)\n // this is new\n fnSet = new Set()\n }\n return fnSet\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n const fnSet = this.getStoreSet(store, evt)\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger(`(addToStore) insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(li => {\n let [hash,] = li\n return hash === args[0]\n }).length\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list\n return type !== t\n }).length\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n\n this.logger('(checkTypeInLazyStore)', store)\n\n if (store) {\n\n return !!Array\n .from(store)\n .filter(li => {\n let [,,t] = li\n return t !== type\n }).length\n }\n\n return false\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger(`(addToNormalStore) try to add \"${type}\" --> \"${evt}\" to normal store`)\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n\n this.logger('(addToNormalStore)', `\"${type}\" --> \"${evt}\" can add to normal store`)\n\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store\n\n return size\n }\n\n return false\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store\n this.logger(`(addToLazyStore) size: ${size}`)\n\n return size\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg]\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n\n}\n","// The top level\nimport {\n ON_TYPE,\n ONLY_TYPE,\n ONCE_TYPE,\n ONLY_ONCE_TYPE,\n MAX_CALL_TYPE,\n ON_MAX_TYPES,\n TAKEN_BY_OTHER_TYPE_ERR,\n NEG_RETURN\n} from './constants'\nimport { isInt, inArray } from './utils'\nimport StoreService from './store-service'\n// export\nexport default class EventService extends StoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on'\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger(`($on) \"${evt}\" is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger(`($on) ${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content\n if (t && t !== type) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger(`($on)`, `call run \"${evt}\"`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n\n this.logger(`($on) return size ${size}`)\n return size\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n // let nStore = this.normalStore\n if (lazyStoreContent === false) {\n this.logger(`($once) \"${evt}\" is not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, ONCE_TYPE, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== ONCE_TYPE) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger('($once)', `call run \"${evt}\"`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n\n let added = false\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore\n\n if (!nStore.has(evt)) {\n this.logger(`($only) \"${evt}\" add to normalStore`)\n\n added = this.addToNormalStore(evt, ONLY_TYPE, callback, context)\n }\n\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger(`($only) \"${evt}\" found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( li => {\n const [ payload, ctx, t ] = li\n if (t && t !== ONLY_TYPE) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger(`($only) call run \"${evt}\"`)\n this.run(callback, payload, context || ctx)\n })\n }\n\n return added\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD added in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n\n let added = false\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce) \"${evt}\" add to normalStore`)\n\n added = this.addToNormalStore(evt, ONLY_ONCE_TYPE, callback, context)\n }\n\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== ONLY_ONCE_TYPE) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger(`($onlyOnce) call run \"${evt}\"`)\n\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added\n }\n\n /**\n * change the way how it suppose to work, instead of create another new store\n * We perform this check on the trigger end, so we set the number max\n * whenever we call the callback, we increment a value in the store\n * once it reaches that number we remove that event from the store,\n * also this will not get add to the lazy store,\n * which means the event must register before we can fire it\n * therefore we don't have to deal with the backward check\n * @param {string} evtName the event to get pre-registered\n * @param {number} max pass the max amount of callback can add to this event\n * @param {*} [ctx=null] the context the callback execute in\n * @return {function} the event handler\n */\n $max(evtName, max, ctx = null) {\n this.validateEvt(evtName)\n if (isInt(max) && max > 0) {\n // find this in the normalStore\n const fnSet = this.$get(evtName, true)\n if (fnSet !== false) {\n const evts = this.searchMapEvt(evtName)\n if (evts.length) {\n // should only have one anyway\n const [,,,type] = evts[0]\n // now init the max store\n const value = this.checkMaxStore(evtName, max)\n const _self = this\n /**\n * construct the callback\n * @param {array<*>} args\n * @return {number} \n */\n return function executeMaxCall(...args) {\n const ctn = _self.getMaxStore(evtName)\n let value = NEG_RETURN\n if (ctn > 0) {\n const fn = _self.$call(evtName, type, ctx)\n Reflect.apply(fn, _self, args)\n\n value = _self.checkMaxStore(evtName)\n if (value === NEG_RETURN) {\n _self.$off(evtName)\n return NEG_RETURN\n }\n }\n return value\n }\n }\n }\n // change in 1.1.1 because we might just call it without knowing if it's register or not\n this.logger(`The ${evtName} is not registered, can not execute non-existing event at the moment`)\n return NEG_RETURN\n }\n throw new Error(`Expect max to be an integer and greater than zero! But we got [${typeof max}]${max} instead`)\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {*}\n */\n $replace(evt, callback, context = null, type = ON_TYPE) {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n\n this.logger(`($replace)`, evt, callback)\n\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0\n // first check the normal store\n let nStore = this.normalStore\n this.logger('($trigger) normalStore', nStore)\n if (nStore.has(evt)) {\n this.logger(`($trigger) \"${evt}\" found`)\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n if (added) {\n this.logger(`($trigger) Currently suspended \"${evt}\" added to queue, nothing executed. Exit now.`)\n return false // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length\n let hasOnce = false\n // let hasOnly = false\n for (let i=0; i < ctn; ++i) {\n ++found\n // this.logger('found', found)\n let [ _, callback, ctx, _type ] = nSet[i]\n this.logger(`($trigger) call run for ${type}:${evt}`)\n\n this.run(callback, payload, context || ctx)\n\n if (_type === 'once' || _type === 'onlyOnce') {\n hasOnce = true\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter aroun\n * @NOTE breaking change: v1.9.1 it return an function to accept the params as spread\n * @param {string} evt event name\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, type = false, context = null) {\n const ctx = this\n\n return function executeCall(...args) {\n let _args = [evt, args, context, type]\n\n return Reflect.apply(ctx.$trigger, ctx, _args)\n }\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n // @TODO we will allow a regex pattern to mass remove event\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n\n return !!stores\n .filter(store => store.has(evt))\n .map(store => this.removeFromStore(evt, store))\n .length\n }\n\n /**\n * return all the listener bind to that event name\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n // @TODO should we allow the same Regex to search for all?\n this.validateEvt(evt)\n let store = this.normalStore\n return this.findFromStore(evt, store, full)\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done) set value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n this.logger('($done) get result:', this.result)\n if (this.keep) {\n return this.result[this.result.length - 1]\n }\n return this.result\n }\n\n /**\n * Take a look inside the stores\n * @param {number|null} idx of the store, null means all\n * @return {void}\n */\n $debug(idx = null) {\n let names = ['lazyStore', 'normalStore']\n let stores = [this.lazyStore, this.normalStore]\n if (stores[idx]) {\n this.logger(names[idx], stores[idx])\n } else {\n stores.map((store, i) => {\n this.logger(names[i], store)\n })\n }\n }\n}\n","// default\nimport To1sourceEvent from './src/event-service'\n\nexport default To1sourceEvent\n","// this will generate a event emitter and will be use everywhere\nimport EventEmitterClass from '@to1source/event'\n// create a clone version so we know which one we actually is using\nclass JsonqlWsEvt extends EventEmitterClass {\n\n constructor(logger) {\n if (typeof logger !== 'function') {\n throw new Error(`Just die here the logger is not a function!`)\n }\n logger(`---> Create a new EventEmitter <---`)\n // this ee will always come with the logger\n // because we should take the ee from the configuration\n super({ logger })\n }\n\n get name() {\n return'jsonql-ws-client-core'\n }\n}\n\n/**\n * getting the event emitter\n * @param {object} opts configuration\n * @return {object} the event emitter instance\n */\nconst getEventEmitter = opts => {\n const { log, eventEmitter } = opts\n \n if (eventEmitter) {\n log(`eventEmitter is:`, eventEmitter.name)\n return eventEmitter\n }\n \n return new JsonqlWsEvt( opts.log )\n}\n\nexport { \n getEventEmitter, \n EventEmitterClass // for other module to build from \n}\n","// group all the small functions here\nimport { EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/src/generic'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\n\n/**\n * WebSocket is strict about the path, therefore we need to make sure before it goes in\n * @param {string} url input url\n * @return {string} url with correct path name\n */\nexport const fixWss = url => {\n const uri = url.toLowerCase()\n if (uri.indexOf('http') > -1) {\n if (uri.indexOf('https') > -1) {\n return uri.replace('https', 'wss')\n }\n return uri.replace('http', 'ws')\n }\n return uri\n}\n\n\n/**\n * get a stock host name from browser\n */\nexport const getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n throw new JsonqlValidationError(e)\n }\n}\n\n/**\n * Unbind the event\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nexport const clearMainEmitEvt = (ee, namespace) => {\n let nsps = toArray(namespace)\n nsps.forEach(n => {\n ee.$off(createEvt(n, EMIT_REPLY_TYPE))\n })\n}\n\n\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME\nconst WS = JS_WS_NAME\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!'\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!'\n\nconst MISSING_PROP_ERR = 'Missing property in contract!'\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!'\n\nconst EMIT_EVT = EMIT_REPLY_TYPE\n\nconst NAMESPACE_KEY = 'namespaceMap'\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!'\n\nconst NOT_ALLOW_OP = 'This operation is not allow!'\n\nconst MY_NAMESPACE = 'myNamespace'\n\nconst CB_FN_NAME = 'on'\n// this is a socket only (for now) feature so we just put it here \nconst DISCONNECTED_ERROR_MSG = `You have disconnected from the socket server, please reconnect.`\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME,\n DISCONNECTED_ERROR_MSG\n}\n","// breaking it up further to share between methods\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { UNKNOWN_RESULT } from '../options/constants'\nimport { isObjectHasKey } from '../utils'\n\n/**\n * break out to use in different places to handle the return from server\n * @param {object} data from server\n * @param {function} resolver NOT from promise\n * @param {function} rejecter NOT from promise\n * @return {void} nothing\n */\nexport function respondHandler(data, resolver, rejecter) {\n if (isObjectHasKey(data, ERROR_KEY)) {\n // debugFn('-- rejecter called --', data[ERROR_KEY])\n rejecter(data[ERROR_KEY])\n } else if (isObjectHasKey(data, DATA_KEY)) {\n // debugFn('-- resolver called --', data[DATA_KEY])\n // @NOTE we change from calling it directly to use reflect \n // this could have another problem later when the return data is no in an array structure\n Reflect.apply(resolver, null, [...data[DATA_KEY]])\n } else {\n // debugFn('-- UNKNOWN_RESULT --', data)\n rejecter({message: UNKNOWN_RESULT, error: data})\n }\n}\n","// the actual trigger call method\nimport { ON_RESULT_FN_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { createEvt, toArray } from '../utils'\nimport { respondHandler } from './respond-handler'\n\n/**\n * just wrapper\n * @param {object} ee EventEmitter\n * @param {string} namespace where this belongs\n * @param {string} resolverName resolver\n * @param {array} args arguments\n * @param {function} log function \n * @return {void} nothing\n */\nexport function actionCall(ee, namespace, resolverName, args = [], log) {\n // reply event \n const outEventName = createEvt(namespace, EMIT_REPLY_TYPE)\n\n log(`actionCall: ${outEventName} --> ${resolverName}`, args)\n // This is the out going call \n ee.$trigger(outEventName, [resolverName, toArray(args)])\n \n // then we need to listen to the event callback here as well\n return new Promise((resolver, rejecter) => {\n const inEventName = createEvt(namespace, resolverName, ON_RESULT_FN_NAME)\n // this cause the onResult got the result back first \n // and it should be the promise resolve first\n // @TODO we need to rewrote the respondHandler to change the problem stated above \n ee.$on(\n inEventName,\n function actionCallResultHandler(result) {\n log(`got the first result`, result)\n respondHandler(result, resolver, rejecter)\n }\n )\n })\n}\n","// setting up the send method \nimport { JsonqlValidationError } from 'jsonql-errors'\nimport {\n ON_ERROR_FN_NAME,\n SEND_MSG_FN_NAME\n} from 'jsonql-constants'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { objDefineProps, createEvt, toArray, nil } from '../utils'\nimport { actionCall } from './action-call'\n\n/** \n * pairing with the server vesrion SEND_MSG_FN_NAME\n * last of the chain so only return the resolver (fn)\n * This is now change to a getter / setter method \n * and call like this: resolver.send(...args)\n * @param {function} fn the resolver function \n * @param {object} ee event emitter instance \n * @param {string} namespace the namespace it belongs to \n * @param {string} resolverName name of the resolver \n * @param {object} params from contract \n * @param {function} log a logger function\n * @return {function} return the resolver itself \n */ \nexport const setupSendMethod = (fn, ee, namespace, resolverName, params, log) => (\n objDefineProps(\n fn, \n SEND_MSG_FN_NAME, \n nil, \n function sendHandler() {\n log(`running call getter method`)\n // let _log = (...args) => Reflect.apply(console.info, console, ['[SEND]'].concat(args))\n /** \n * This will follow the same pattern like the resolver \n * @param {array} args list of unknown argument follow the resolver \n * @return {promise} resolve the result \n */\n return function sendCallback(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => {\n // @TODO check the result \n // because the validation could failed with the list of fail properties \n log('execute send', namespace, resolverName, _args)\n return actionCall(ee, namespace, resolverName, _args, log)\n })\n .catch(err => {\n // @TODO it shouldn't be just a validation error \n // it could be server return error, so we need to check \n // what error we got back here first \n log('send error', err)\n // @TODO it might not an validation error need the finalCatch here\n ee.$call(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n [new JsonqlValidationError(resolverName, err)]\n )\n })\n } \n })\n)\n","// break up the original setup resolver method here\n// import { JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport {\n ON_ERROR_FN_NAME,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME\n} from 'jsonql-constants'\nimport { finalCatch } from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { actionCall } from './action-call'\n// local\nimport { MY_NAMESPACE } from '../options/constants'\nimport { chainFns, objDefineProps, injectToFn, createEvt, isFunc } from '../utils'\nimport { respondHandler } from './respond-handler'\nimport { setupSendMethod } from './setup-send-method'\n\n\n/**\n * moved back from generator-methods \n * create the actual function to send message to server\n * @param {object} ee EventEmitter instance\n * @param {string} namespace this resolver end point\n * @param {string} resolverName name of resolver as event name\n * @param {object} params from contract\n * @param {function} log pass the log function\n * @return {function} resolver\n */\nfunction createResolver(ee, namespace, resolverName, params, log) {\n // note we pass the new withResult=true option\n return function resolver(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => actionCall(ee, namespace, resolverName, _args, log))\n .catch(finalCatch)\n }\n}\n\n/**\n * The first one in the chain, just setup a namespace prop\n * the rest are passing through\n * @param {function} fn the resolver function\n * @param {object} ee the event emitter\n * @param {string} resolverName what it said\n * @param {object} params for resolver from contract\n * @param {function} log the logger function\n * @return {array}\n */\nconst setupNamespace = (fn, ee, namespace, resolverName, params, log) => [\n injectToFn(fn, MY_NAMESPACE, namespace),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * onResult handler\n */\nconst setupOnResult = (fn, ee, namespace, resolverName, params, log) => [\n objDefineProps(fn, ON_RESULT_FN_NAME, function(resultCallback) {\n if (isFunc(resultCallback)) {\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_FN_NAME),\n function resultHandler(result) {\n respondHandler(result, resultCallback, (error) => {\n log(`Catch error: \"${resolverName}\"`, error)\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n error\n )\n })\n }\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * we do need to add the send prop back because it's the only way to deal with\n * bi-directional data stream\n */\nconst setupOnMessage = (fn, ee, namespace, resolverName, params, log) => [\n objDefineProps(fn, ON_MESSAGE_FN_NAME, function(messageCallback) {\n // we expect this to be a function\n if (isFunc(messageCallback)) {\n // did that add to the callback\n let onMessageCallback = (args) => {\n log(`onMessageCallback`, args)\n respondHandler(\n args, \n messageCallback, \n (error) => {\n log(`Catch error: \"${resolverName}\"`, error)\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n error\n )\n })\n }\n // register the handler for this message event\n ee.$only(\n createEvt(namespace, resolverName, ON_MESSAGE_FN_NAME),\n onMessageCallback\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * ON_ERROR_FN_NAME handler\n */\nconst setupOnError = (fn, ee, namespace, resolverName, params, log) => [\n objDefineProps(fn, ON_ERROR_FN_NAME, function(resolverErrorHandler) {\n if (isFunc(resolverErrorHandler)) {\n // please note ON_ERROR_FN_NAME can add multiple listners\n ee.$only(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n resolverErrorHandler\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * Add extra property / listeners to the resolver\n * @param {string} namespace where this belongs\n * @param {string} resolverName name as event name\n * @param {object} params from contract\n * @param {function} fn resolver function\n * @param {object} ee EventEmitter\n * @param {function} log function\n * @return {function} resolver\n */ \nfunction setupResolver(namespace, resolverName, params, fn, ee, log) {\n let fns = [\n setupNamespace,\n setupOnResult,\n setupOnMessage,\n setupOnError,\n setupSendMethod\n ]\n const executor = Reflect.apply(chainFns, null, fns)\n // get the executor\n return executor(fn, ee, namespace, resolverName, params, log)\n}\n\nexport { \n createResolver, \n setupResolver \n}","// put all the resolver related methods here to make it more clear\n\n// this will be a mini client server architect\n// The reason is when the enableAuth setup - the private route\n// might not be validated, but we need the callable point is ready\n// therefore this part will always take the contract and generate\n// callable api for the developer to setup their front end\n// the only thing is - when they call they might get an error or\n// NOT_LOGIN_IN and they can react to this error accordingly\n\nimport { \n createResolver, \n setupResolver \n} from './setup-resolver'\nimport {\n injectToFn\n} from '../utils'\n\n\n/**\n * step one get the clientmap with the namespace\n * @param {object} opts configuration\n * @param {object} ee EventEmitter\n * @param {object} nspGroup resolvers index by their namespace\n * @return {promise} resolve the clientmapped, and start the chain\n */\nexport function generateResolvers(opts, ee, nspGroup) {\n const { log } = opts\n let client= {}\n \n for (let namespace in nspGroup) {\n let list = nspGroup[namespace]\n for (let resolverName in list) {\n // resolverNames.push(resolverName)\n let params = list[resolverName]\n let fn = createResolver(ee, namespace, resolverName, params, log)\n // this should set as a getter therefore can not be overwrite by accident\n client = injectToFn(\n client,\n resolverName,\n setupResolver(namespace, resolverName, params, fn, ee, log)\n )\n }\n }\n \n // resolve the clientto start the chain\n // chain the result to allow the chain processing\n return [ client, opts, ee, nspGroup ]\n}\n\n","// move from generator-methods \n// they are global event listeners \nimport {\n createEvt,\n objDefineProps,\n isFunc\n} from '../utils'\nimport {\n ON_ERROR_FN_NAME,\n ON_READY_FN_NAME\n} from 'jsonql-constants'\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * @param {object} client client itself\n * @param {object} opts configuration\n * @param {object} ee Event Emitter\n * @return {array} [ obj, opts, ee ]\n */\nexport function setupOnReadyListener(client, opts, ee) {\n return [\n objDefineProps(\n client,\n ON_READY_FN_NAME,\n function onReadyCallbackHandler(onReadyCallback) {\n if (isFunc(onReadyCallback)) {\n // reduce it down to just one flat level\n // @2020-03-19 only allow ONE onReady callback otherwise\n // it will get fire multiple times which is not what we want\n ee.$only(ON_READY_FN_NAME, onReadyCallback)\n }\n }\n ),\n opts,\n ee\n ]\n}\n\n/**\n * The problem is the namespace can have more than one\n * and we only have on onError message\n * @param {object} clientthe client itself\n * @param {object} opts configuration\n * @param {object} ee Event Emitter\n * @param {object} nspGroup namespace keys\n * @return {array} [obj, opts, ee]\n */\nexport function setupNamespaceErrorListener(client, opts, ee, nspGroup) {\n return [\n objDefineProps(\n client,\n ON_ERROR_FN_NAME,\n function namespaceErrorCallbackHandler(namespaceErrorHandler) {\n if (isFunc(namespaceErrorHandler)) {\n // please note ON_ERROR_FN_NAME can add multiple listners\n for (let namespace in nspGroup) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ON_ERROR_FN_NAME), namespaceErrorHandler)\n }\n }\n }\n ),\n opts,\n ee\n ]\n}\n\n","// take out from the resolver-methods\nimport {\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n ON_LOGIN_FN_NAME\n} from 'jsonql-constants'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { injectToFn, chainFns, isString, objDefineProps, isFunc } from '../utils'\n\n\n/**\n * @UPDATE it might be better if we decoup the two http-client only emit a login event\n * Here should catch it and reload the ws client @TBC\n * break out from createAuthMethods to allow chaining call\n * @param {object} obj the main client object\n * @param {object} opts configuration\n * @param {object} ee event emitter\n * @return {array} [ obj, opts, ee ] what comes in what goes out\n */\nconst setupLoginHandler = (obj, opts, ee) => [\n injectToFn(obj, opts.loginHandlerName, function loginHandler(token) {\n if (token && isString(token)) {\n opts.log(`Received ${LOGIN_EVENT_NAME} with ${token}`)\n // @TODO add the interceptor hook\n return ee.$trigger(LOGIN_EVENT_NAME, [token])\n }\n // should trigger a global error instead @TODO\n throw new JsonqlValidationError(opts.loginHandlerName, `Unexpected token ${token}`)\n }),\n opts,\n ee\n]\n\n\n/**\n * break out from createAuthMethods to allow chaining call - final in chain\n * @param {object} obj the main client object\n * @param {object} opts configuration\n * @param {object} ee event emitter\n * @return {array} [ obj, opts, ee ] what comes in what goes out\n */\nconst setupLogoutHandler = (obj, opts, ee) => [\n injectToFn(obj, opts.logoutHandlerName, function logoutHandler(...args) {\n ee.$trigger(LOGOUT_EVENT_NAME, args)\n }),\n opts,\n ee\n]\n\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * Plus this will check if it's the private namespace that fired the event\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @return {array} [ obj, opts, ee] what comes in what goes out\n */\nconst setupOnLoginhandler = (obj, opts, ee) => [\n objDefineProps(obj, ON_LOGIN_FN_NAME, function onLoginCallbackHandler(onLoginCallback) {\n if (isFunc(onLoginCallback)) {\n // only one callback can registered with it, TBC\n // Should this be a $onlyOnce listener after the logout \n // we add it back? \n ee.$only(ON_LOGIN_FN_NAME, onLoginCallback)\n }\n }),\n opts,\n ee\n]\n\n// @TODO future feature setup switch user\n\n\n/**\n * Create auth related methods\n * @param {object} obj the client itself\n * @param {object} opts configuration\n * @param {object} ee Event Emitter\n * @return {array} [ obj, opts, ee ] what comes in what goes out\n */\nexport function setupAuthMethods(obj, opts, ee) {\n return chainFns(\n setupLoginHandler,\n setupLogoutHandler,\n setupOnLoginhandler\n )(obj, opts, ee)\n}\n","// this is a new method that will create several\n// intercom method also reverse listen to the server\n// such as disconnect (server issue disconnect)\nimport { injectToFn, chainFns } from '../utils'\nimport { \n CONNECT_EVENT_NAME,\n CONNECTED_EVENT_NAME,\n DISCONNECT_EVENT_NAME,\n CONNECTED_PROP_KEY\n} from 'jsonql-constants'\n\n/**\n * Set up the CONNECTED_PROP_KEY to the client\n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupConnectPropKey(client, opts, ee) {\n const { log } = opts \n log('[1] setupConnectPropKey')\n // we just inject a helloWorld method here\n // set up the init state of the connect\n client = injectToFn(client, CONNECTED_PROP_KEY , false, true)\n return [ client, opts, ee ]\n}\n\n\n/**\n * setup listener to the connect event \n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupConnectEvtListener(client, opts, ee) {\n // @TODO do what at this point?\n const { log } = opts \n\n log(`[2] setupConnectEvtListener`)\n\n ee.$on(CONNECT_EVENT_NAME, function(...args) {\n log(`setupConnectEvtListener pass and do nothing at the moment`, args)\n })\n \n return [client, opts, ee]\n}\n\n/**\n * setup listener to the connected event \n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupConnectedEvtListener(client, opts, ee) {\n const { log } = opts \n\n log(`[3] setupConnectedEvtListener`)\n\n ee.$on(CONNECTED_EVENT_NAME, function() {\n client[CONNECTED_PROP_KEY] = true\n // new action to take release the holded event queue \n const ctn = ee.$release()\n\n log(`CONNECTED_EVENT_NAME`, true, 'queue count', ctn)\n\n return {[CONNECTED_PROP_KEY]: true}\n })\n\n return [client, opts, ee]\n}\n\n/**\n * Listen to the disconnect event and set the property to the client \n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupDisconnectListener(client, opts, ee) {\n const { log } = opts \n\n log(`[4] setupDisconnectListener`)\n\n ee.$on(DISCONNECT_EVENT_NAME, function() {\n client[CONNECTED_PROP_KEY] = false\n log(`CONNECTED_EVENT_NAME`, false)\n\n return {[CONNECTED_PROP_KEY]: false}\n })\n\n return [client, opts, ee]\n}\n\n/**\n * disconnect action\n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n * @return {object} this is the final step to return the client\n */\nfunction setupDisconectAction(client, opts, ee) {\n const { disconnectHandlerName, log } = opts\n log(`[5] setupDisconectAction`)\n\n return injectToFn(\n client,\n disconnectHandlerName,\n function disconnectHandler(...args) {\n ee.$trigger(DISCONNECT_EVENT_NAME, args)\n }\n )\n}\n\n/**\n * this is the new method that setup the intercom handler\n * also this serve as the final call in the then chain to\n * output the client\n * @param {object} client the client\n * @param {object} opts configuration\n * @param {object} ee the event emitter\n * @return {object} client\n */\nexport function setupInterCom(client, opts, ee) {\n const fns = [\n setupConnectPropKey,\n setupConnectEvtListener,\n setupConnectedEvtListener,\n setupDisconnectListener,\n setupDisconectAction\n ]\n\n const executor = Reflect.apply(chainFns, null, fns)\n return executor(client, opts, ee)\n}\n","// The final step of the setup before it returns the client\nimport { setupInterCom } from './setup-intercom'\nimport { CONNECT_EVENT_NAME, SUSPEND_EVENT_PROP_KEY } from 'jsonql-constants'\n\n/**\n * The final step to return the client\n * @param {object} obj the client\n * @param {object} opts configuration\n * @param {object} ee the event emitter\n * @return {object} client\n */\nfunction setupFinalStep(obj, opts, ee) {\n \n let client = setupInterCom(obj, opts, ee)\n // opts.log(`---> The final step to return the ws-client <---`)\n // add some debug functions\n client.verifyEventEmitter = () => ee.is\n // we add back the two things into the client\n // then when we do integration, we run it in reverse,\n // create the ws client first then the host client\n client.eventEmitter = opts.eventEmitter\n client.log = opts.log\n\n // now at this point, we are going to call the connect event\n ee.$trigger(CONNECT_EVENT_NAME, [opts, ee]) // just passing back the entire opts object\n // also we can release the queue here \n if (opts[SUSPEND_EVENT_PROP_KEY] === true) {\n opts.$releaseNamespace()\n }\n\n return client\n}\n\n\nexport { setupFinalStep }\n","// resolvers generator\n// we change the interface to return promise from v1.0.3\n// this way we make sure the obj return is correct and timely\nimport { NSP_GROUP } from 'jsonql-constants'\nimport { chainFns } from '../utils'\n\nimport { generateResolvers } from './generator-methods'\nimport {\n setupOnReadyListener,\n setupNamespaceErrorListener\n} from './global-listener'\n\nimport { setupAuthMethods } from './setup-auth-methods'\n\nimport { setupFinalStep } from './setup-final-step'\n\n/**\n * prepare the methods\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {object} of resolvers\n * @public\n */\nexport function callersGenerator(opts, nspMap, ee) {\n let fns = [\n generateResolvers,\n setupOnReadyListener,\n setupNamespaceErrorListener\n ]\n if (opts.enableAuth) {\n // there is a problem here, when this is a public namespace\n // it should not have a login logout event attach to it\n fns.push(setupAuthMethods)\n }\n // we will always get back the [ obj, opts, ee ]\n // then we only return the obj (wsClient)\n // This has move outside of here, into the main method\n // the reason is we could switch around the sequence much easier\n fns.push(setupFinalStep)\n // stupid reaon!!!\n const executer = Reflect.apply(chainFns, null, fns)\n // run it\n return executer(opts, ee, nspMap[NSP_GROUP])\n}\n","// create options\nimport {\n checkConfigAsync,\n checkConfig\n} from 'jsonql-params-validator'\nimport {\n wsCoreCheckMap,\n wsCoreConstProps,\n socketCheckMap\n} from './defaults'\nimport {\n fixWss,\n getHostName,\n getEventEmitter,\n getNspInfoByConfig,\n getLogFn\n} from '../utils'\n\nimport {\n SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\n\n/**\n * We need this to find the socket server type\n * @param {*} config\n * @return {string} the name of the socket server if any\n */\nfunction checkSocketClientType(config) {\n return checkConfig(config, socketCheckMap)\n}\n\n/**\n * Create a combine checkConfig for the creating the combine client\n * @param {*} configCheckMap\n * @param {*} constProps\n * @return {function} takes the user input config then resolve the configuration\n */\nfunction createCombineConfigCheck(configCheckMap, constProps) {\n const combineCheckMap = Object.assign({}, configCheckMap, wsCoreCheckMap)\n const combineConstProps = Object.assign({}, constProps, wsCoreConstProps)\n return config => checkConfigAsync(config, combineCheckMap, combineConstProps)\n}\n\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config user supply config\n * @param {object} defaultOptions for checking\n * @param {object} constProps user supply const props\n * @return {promise} resolve to the checked opitons\n */\nfunction checkConfiguration(config, defaultOptions, constProps) {\n const defaultCheckMap= Object.assign(wsCoreCheckMap, defaultOptions)\n const wsConstProps = Object.assign(wsCoreConstProps, constProps)\n\n return checkConfigAsync(config, defaultCheckMap, wsConstProps)\n}\n\n/**\n * Taking the `then` part from the method below\n * @param {object} opts\n * @return {promise} opts all done\n */\nfunction postCheckInjectOpts(opts) {\n return Promise.resolve(opts)\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // get the log function here\n opts.log = getLogFn(opts)\n\n opts.eventEmitter = getEventEmitter(opts)\n \n return opts\n })\n}\n\n/**\n * Don't want to make things confusing\n * Breaking up the opts process in one place\n * then generate the necessary parameter in another step\n * @2020-3-20 here we suspend operation by it's namespace first\n * Then in the framework part, after the connection establish we release\n * the queue\n * @param {object} opts checked --> merge --> injected\n * @return {object} {opts, nspMap, ee}\n */\nfunction createRequiredParams(opts) {\n const nspMap = getNspInfoByConfig(opts)\n const ee = opts.eventEmitter\n // @TODO here we are going to add suspend event to the namespace related methods\n const { log } = opts \n const { namespaces } = nspMap\n\n log(`namespaces`, namespaces)\n\n // next we loop the namespace and suspend all the events prefix with namespace \n if (opts[SUSPEND_EVENT_PROP_KEY] === true) {\n // we create this as a function then we can call it again \n opts.$suspendNamepsace = () => namespaces.forEach(namespace => ee.$suspendEvent(namespace))\n // then we create a new method to releas the queue \n // we prefix it with the $ to notify this is not a jsonql part methods\n opts.$releaseNamespace = () => ee.$release()\n // now run it \n opts.$suspendNamepsace()\n }\n \n return { opts, nspMap, ee }\n}\n\nexport {\n // properties\n wsCoreCheckMap,\n wsCoreConstProps,\n // functions\n checkConfiguration,\n postCheckInjectOpts,\n createRequiredParams,\n // this will just get export for integration\n checkSocketClientType,\n createCombineConfigCheck\n}\n","// the top level API\n// The goal is to create a generic method that will able to handle\n// any kind of clients\n// import { injectToFn } from 'jsonql-utils'\nimport { callersGenerator } from './callers'\nimport {\n checkConfiguration,\n postCheckInjectOpts,\n createRequiredParams\n} from './options'\n\n\n/**\n * 0.5.0 we break up the wsClientCore in two parts one without the config check\n * @param {function} setupSocketClientListener just make sure what it said it does\n * @return {function} to actually generate the client\n */\nexport function wsClientCoreAction(setupSocketClientListener) {\n /**\n * This is a breaking change, to continue the onion skin design\n * @param {object} config the already checked config\n * @return {promise} resolve the client\n */\n return function createClientAction(config = {}) {\n\n return postCheckInjectOpts(config)\n .then(createRequiredParams)\n .then(\n ({opts, nspMap, ee}) => setupSocketClientListener(opts, nspMap, ee)\n )\n .then(\n ({opts, nspMap, ee}) => callersGenerator(opts, nspMap, ee)\n )\n .catch(err => {\n console.error(`[jsonql-ws-core-client init error]`, err)\n })\n }\n}\n\n/**\n * The main interface which will generate the socket clients and map all events\n * @param {object} socketClientListerner this is the one method export by various clients\n * @param {object} [configCheckMap={}] we should do all the checking in the core instead of the client\n * @param {object} [constProps={}] add this to supply the constProps from the downstream client\n * @return {function} accept a config then return the wsClient instance with all the available API\n */\nexport function wsClientCore(socketClientListener, configCheckMap = {}, constProps = {}) {\n // we need to inject property to this client later\n return (config = {}) => checkConfiguration(config, configCheckMap, constProps)\n .then(\n wsClientCoreAction(socketClientListener)\n )\n}\n","// this is getting too confusing \n// therefore we move it back to the framework specific \n\n/**\n * wrapper method to create a nsp without login\n * @param {string|boolean} namespace namespace url could be false\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspClient(namespace, opts) {\n const { hostname, wssPath, wsOptions, nspClient, log } = opts\n const url = namespace ? [hostname, namespace].join('/') : wssPath\n log(`createNspClient --> `, url)\n\n return nspClient(url, wsOptions)\n}\n\n/**\n * wrapper method to create a nsp with token auth\n * @param {string} namespace namespace url\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspAuthClient(namespace, opts) {\n const { hostname, wssPath, token, wsOptions, nspAuthClient, log } = opts\n const url = namespace ? [hostname, namespace].join('/') : wssPath\n \n log(`createNspAuthClient -->`, url)\n\n if (token && typeof token !== 'string') {\n throw new Error(`Expect token to be string, but got ${token}`)\n }\n \n return nspAuthClient(url, token, wsOptions)\n}\n\nexport {\n createNspClient,\n createNspAuthClient\n}\n","// this use by client-event-handler\nimport { ON_ERROR_FN_NAME } from 'jsonql-constants'\nimport { createEvt } from '../utils'\n\n/**\n * trigger errors on all the namespace onError handler\n * @param {object} ee Event Emitter\n * @param {array} namespaces nsps string\n * @param {string} message optional\n * @return {void}\n */\nexport function triggerNamespacesOnError(ee, namespaces, message) {\n namespaces.forEach( namespace => {\n ee.$trigger(\n createEvt(namespace, ON_ERROR_FN_NAME), \n [{ message, namespace }]\n )\n })\n}\n\n/**\n * Handle the onerror callback \n * @param {object} ee event emitter \n * @param {string} namespace which namespace has error \n * @param {*} err error object\n * @return {void} \n */\nexport const handleNamespaceOnError = (ee, namespace, err) => {\n ee.$trigger(createEvt(namespace, ON_ERROR_FN_NAME), [err])\n}","// NOT IN USE AT THE MOMENT JUST KEEP IT HERE FOR THE TIME BEING \nimport {\n LOGOUT_EVENT_NAME,\n NOT_LOGIN_ERR_MSG,\n ON_ERROR_FN_NAME,\n ON_RESULT_FN_NAME,\n DISCONNECT_EVENT_NAME,\n SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\nimport { EMIT_EVT, DISCONNECTED_ERROR_MSG } from '../options/constants'\nimport { createEvt, clearMainEmitEvt } from '../utils'\nimport { triggerNamespacesOnError } from './trigger-namespaces-on-error'\n\n/**\n * A Event Listerner placeholder when it's not connect to any nsp\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nexport const notConnectedListener = (namespace, ee, opts) => {\n const { log } = opts \n\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function disconnectedEvtCallback(resolverName, args) {\n log(`[disconnectedListerner] hijack the ws call`, namespace, resolverName, args)\n // Now we suspend all the calls but note the existing one won't be affected \n // we need to update the methods to move everything across \n \n\n const error = {\n message: DISCONNECTED_ERROR_MSG\n }\n ee.$call(createEvt(namespace, resolverName, ON_ERROR_FN_NAME), [ error ])\n // also trigger the result Listerner, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [{ error }])\n }\n )\n}\n\n\n/**\n * The disconnect event Listerner, now we log the client out from everything\n * @TODO now we are another problem they disconnect, how to reconnect\n * @param {object} nsps the available nsp(s)\n * @param {array} namespaces available namespace \n * @param {object} ee eventEmitter \n * @param {object} opts configuration\n * @return {void}\n */\nexport const disconnectListener = (nsps, namespaces, ee, opts) => {\n const { log } = opts \n ee.$on(\n DISCONNECT_EVENT_NAME, \n function disconnectEvtCallback() {\n triggerNamespacesOnError(ee, namespaces, DISCONNECT_EVENT_NAME)\n namespaces.forEach( namespace => { \n log(`disconnect from ${namespace}`)\n\n clearMainEmitEvt(ee, namespace)\n nsps[namespace] = null \n disconnectedListerner(namespace, ee, opts)\n })\n }\n )\n}\n\n/**\n * A Event Listerner placeholder when it's not connect to the private nsp\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nexport const notLoginListener = (namespace, ee, opts) => {\n const { log } = opts \n\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function notLoginListernerCallback(resolverName, args) {\n log('[notLoginListerner] hijack the ws call', namespace, resolverName, args)\n const error = { message: NOT_LOGIN_ERR_MSG }\n // It should just throw error here and should not call the result\n // because that's channel for handling normal event not the fake one\n ee.$call(createEvt(namespace, resolverName, ON_ERROR_FN_NAME), [ error ])\n // also trigger the result Listerner, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [{ error }])\n }\n )\n}\n\n/**\n * Only when there is a private namespace then we bind to this event\n * @param {object} nsps the available nsp(s)\n * @param {array} namespaces available namespace \n * @param {object} ee eventEmitter \n * @param {object} opts configuration\n * @return {void}\n */\nexport const logoutEvtListener = (nsps, namespaces, ee, opts) => {\n const { log } = opts \n // this will be available regardless enableAuth\n // because the server can log the client out\n ee.$on(\n LOGOUT_EVENT_NAME, \n function logoutEvtCallback() {\n const privateNamespace = getPrivateNamespace(namespaces)\n log(`${LOGOUT_EVENT_NAME} event triggered`)\n // disconnect(nsps, opts.serverType)\n // we need to issue error to all the namespace onError Listerner\n triggerNamespacesOnError(ee, [privateNamespace], LOGOUT_EVENT_NAME)\n // rebind all of the Listerner to the fake one\n log(`logout from ${privateNamespace}`)\n\n clearMainEmitEvt(ee, privateNamespace)\n // we need to issue one more call to the server before we disconnect\n // now this is a catch 22, here we are not suppose to do anything platform specific\n // so that should fire before trigger this event\n // clear out the nsp\n nsps[privateNamespace] = null \n // add a NOT LOGIN error if call\n notLoginWsListerner(privateNamespace, ee, opts)\n }\n )\n}\n\n","// This is share between different clients so we export it\n// @TODO port what is in the ws-main-handler\n// because all the client side call are via the ee\n// and that makes it re-usable between different client setup\n\n/*\nInside the map call but we take it out for now and until the WebSocket version is fully working\nimport { SOCKET_IO } from '../options/constants'\n // @TODO need to double check this\n if (opts.serverType === SOCKET_IO) {\n let { nspGroup } = nspMap\n args.push(nspGroup[namespace])\n }\n*/\nimport { getPrivateNamespace } from 'jsonql-utils/src/namespace'\nimport { logoutEvtListener, notLoginListener } from './event-listeners'\n\n/**\n * centralize all the comm in one place\n * @param {function} bindSocketEventHandler binding the ee to ws --> this is the core bit\n * @param {object} nsps namespaced nsp\n * @return {void} nothing\n */\nexport function namespaceEventListener(bindSocketEventListener, nsps) {\n /**\n * BREAKING CHANGE instead of one flat structure\n * we return a function to accept the two\n * @param {object} opts configuration\n * @param {object} nspMap this is not in the opts\n * @param {object} ee Event Emitter instance\n * @return {array} although we return something but this is the last step and nothing to do further\n */\n return (opts, nspMap, ee) => {\n // since all these params already in the opts\n const { log } = opts\n const { namespaces } = nspMap\n // @1.1.3 add isPrivate prop to id which namespace is the private nsp\n // then we can use this prop to determine if we need to fire the ON_LOGIN_PROP_NAME event\n const privateNamespace = getPrivateNamespace(namespaces)\n\n // @TODO hook up the connectedEvtHandler somewhere\n\n return namespaces.map(namespace => {\n let isPrivate = privateNamespace === namespace\n log(namespace, ` --> ${isPrivate ? 'private': 'public'} nsp --> `, nsps[namespace] !== false)\n if (nsps[namespace]) {\n log('[call bindWsHandler]', isPrivate, namespace)\n\n let args = [namespace, nsps[namespace], ee, isPrivate, opts]\n // Finally we binding everything together\n Reflect.apply(bindSocketEventListener, null, args)\n \n } else {\n log(`binding notLoginWsHandler to ${namespace}`)\n // a dummy placeholder\n // @TODO but it should be a not connect handler\n // when it's not login (or fail) this should be handle differently\n notLoginListener(namespace, ee, opts)\n }\n if (isPrivate) {\n log(`Has private and add logoutEvtHandler`)\n logoutEvtListener(nsps, namespaces, ee, opts)\n }\n // just return something its not going to get use anywhere\n return isPrivate\n })\n }\n}\n","// jsonql-ws-core takes over the check configuration\n// here we only have to supply the options that is unique to this client\n// create options\nimport { JS_WS_NAME } from 'jsonql-constants'\n// constant props\nconst wsClientConstProps = {\n version: '__PLACEHOLDER__', // will get replace\n serverType: JS_WS_NAME\n}\n\nexport { wsClientConstProps }\n","// pass the different type of ws to generate the client\n// this is where the framework specific code get injected\nimport { TOKEN_PARAM_NAME } from 'jsonql-constants'\nimport { fixWss } from '../modules'\nimport {\n createInitPing, \n extractPingResult\n} from '../modules'\n\n/**\n * Group the ping and get respond create new client in one\n * @param {object} ws \n * @param {object} WebSocket \n * @param {string} url\n * @param {function} resolver \n * @param {function} rejecter \n * @param {boolean} auth client or not\n * @return {promise} resolve the confirm client\n */\nfunction initPingAction(ws, WebSocket, url, resolver, rejecter, wsOptions) {\n // @TODO how to we id this client can issue a CSRF\n // by origin? \n ws.onopen = function onOpenCallback() {\n ws.send(createInitPing())\n }\n\n ws.onmessage = function onMessageCallback(payload) {\n try {\n const header = extractPingResult(payload.data)\n // @NOTE the break down test in ws-client-core show no problems\n // the problem was cause by malform nspInfo that time? \n setTimeout(() => { // delay or not show no different but just on the safe side\n ws.terminate()\n }, 50)\n const newWs = new WebSocket(url, Object.assign(wsOptions, header)) \n resolver(newWs) \n } catch(e) {\n rejecter(e)\n }\n }\n\n ws.onerror = function onErrorCallback(err) {\n rejecter(err)\n }\n\n return ws // just return it\n}\n\n/**\n * less duplicated code the better \n * @param {object} WebSocket \n * @param {string} url formatted url\n * @param {object} options or not\n * @return {promise} resolve the actual verified client\n */\nfunction asyncConnect(WebSocket, url, options) {\n \n return new Promise((resolver, rejecter) => { \n const unconfirmClient = new WebSocket(url, options)\n \n return initPingAction(unconfirmClient, WebSocket, url, resolver, rejecter, options)\n })\n}\n\n\n/**\n * The bug was in the wsOptions where ws don't need it but socket.io do\n * therefore the object was pass as second parameter!\n * @NOTE here we only return a method to create the client, it might not get call \n * @param {object} WebSocket the client or node version of ws\n * @param {object} opts this is a breaking change we will init the client twice\n * @param {boolean} [auth = false] if it's auth then 3 param or just one\n * @return {function} the client method to connect to the ws socket server\n */\nfunction initWebSocketClient(WebSocket, opts, auth = false) {\n const { log } = opts\n if (auth === false) {\n /**\n * Create a non-protected client\n * @param {string} url \n * @param {object} [wsOptions={}]\n * @return {promise} resolve to the confirmed client\n */\n return function createWsClient(url, wsOptions = {}) {\n const _url = fixWss(url)\n log(`nspClient: \\n${_url}\\n`, wsOptions)\n\n return asyncConnect(WebSocket, _url, wsOptions)\n }\n }\n\n /**\n * Create a client with auth token\n * @param {string} url start with ws:// @TODO check this?\n * @param {string} token the jwt token\n * @param {object} [wsOptions={}] extra options pass to the WebSocket object\n * @return {object} ws instance\n */\n return function createWsAuthClient(url, token, wsOptions = {}) {\n const ws_url = fixWss(url)\n // console.log('what happen here?', url, ws_url, token)\n const _url = token && typeof token === 'string' ? `${ws_url}?${TOKEN_PARAM_NAME}=${token}` : ws_url\n log(`nspAuthClient: \\n${_url}\\n`, wsOptions)\n\n return asyncConnect(WebSocket, _url, wsOptions)\n }\n}\n\nexport { initWebSocketClient }","// @BUG when call disconnected\n// this keep causing an \"Disconnect call failed TypeError: Cannot read property 'readyState' of null\"\n// I think that is because it's not login then it can not be disconnect\n// how do we track this state globally\nimport { \n LOGIN_EVENT_NAME, \n CONNECT_EVENT_NAME \n} from 'jsonql-constants'\nimport { clearMainEmitEvt } from '../modules'\n\n/**\n * when we received a login event \n * from the http-client or the standalone login call \n * we received a token here --> update the opts then trigger \n * the CONNECT_EVENT_NAME again\n * @param {object} opts configurations\n * @param {object} nspMap contain all the required info\n * @param {object} ee event emitter\n * @return {void}\n */\nexport function loginEventListener(opts, nspMap, ee) {\n const { log } = opts\n const { namespaces } = nspMap\n\n log(`[4] loginEventHandler`)\n\n ee.$only(LOGIN_EVENT_NAME, function loginEventHandlerCallback(tokenFromLoginAction) {\n\n log('createClient LOGIN_EVENT_NAME $only handler')\n // clear out all the event binding\n clearMainEmitEvt(ee, namespaces)\n // reload the nsp and rebind all the events\n opts.token = tokenFromLoginAction \n ee.$trigger(CONNECT_EVENT_NAME, [opts, ee]) // don't need to pass the nspMap \n })\n}\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","// break it out on its own because\n// it's building from the lodash-es from scratch\n// according to this discussion https://github.com/lodash/lodash/issues/3298\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport merge from 'lodash-es/merge'\n\n/**\n * previously we already make sure the order of the namespaces\n * and attach the auth client to it\n * @param {array} promises array of unresolved promises\n * @param {boolean} asObject if true then merge the result object\n * @return {object} promise resolved with the array of promises resolved results\n */\nexport function chainPromises(promises, asObject = false) {\n return promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResults => (\n currentTask.then(currentResult => (\n asObject === false ? [...chainResults, currentResult] : merge(chainResults, currentResult)\n ))\n ))\n ), Promise.resolve(\n asObject === false ? [] : (isPlainObject(asObject) ? asObject : {})\n ))\n}\n\n\n/**\n * This one return a different result from the chainPromises\n * it will be the same like chainFns that take one promise resolve as the next fn parameter\n * @param {function} initPromise a function that accept param and resolve result\n * @param {array} promises array of function pass that resolve promises\n * @return {promise} resolve the processed result\n */\nexport function chainProcessPromises(initPromise, ...promises) {\n return (...args) => (\n promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResult => (\n currentTask(chainResult)\n )\n )\n ), Reflect.apply(initPromise, null, args))\n )\n}\n","// actually binding the event client to the socket client\nimport {\n createNspClient,\n createNspAuthClient\n} from './modules'\nimport {\n chainPromises \n} from 'jsonql-utils/src/chain-promises'\n\n/**\n * Because the nsps can be throw away so it doesn't matter the scope\n * this will get reuse again\n * @NOTE when we enable the standalone method this sequence will not change \n * only call and reload\n * @param {object} opts configuration\n * @param {object} nspMap from contract\n * @param {string|null} token whether we have the token at run time\n * @return {promise} resolve the nsps namespace with namespace as key\n */\nconst createNsp = function(opts, nspMap, token = null) {\n // we leave the token param out because it could get call by another method\n token = token || opts.token \n let { publicNamespace, namespaces } = nspMap\n const { log } = opts \n log(`createNspAction`, 'publicNamespace', publicNamespace, 'namespaces', namespaces)\n \n // reverse the namespaces because it got stuck for some reason\n // const reverseNamespaces = namespaces.reverse()\n if (opts.enableAuth) {\n return chainPromises(\n namespaces.map((namespace, i) => {\n if (i === 0) {\n if (token) {\n opts.token = token\n log('create createNspAuthClient at run time')\n return createNspAuthClient(namespace, opts)\n }\n return Promise.resolve(false)\n }\n return createNspClient(namespace, opts)\n })\n )\n .then(results => \n results.map((result, i) => \n ({ [namespaces[i]]: result }))\n .reduce((a, b) => Object.assign(a, b), {})\n )\n }\n\n return createNspClient(false, opts)\n .then(nsp => ({[publicNamespace]: nsp}))\n}\n\nexport { createNsp }\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg]\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @param {boolean} [t=true] or throw\n * @return {*} json object on success\n */\nexport const parseJson = function(n, t=true) {\n try {\n return JSON.parse(n)\n } catch(e) {\n if (t) {\n return n\n }\n throw new Error(e)\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = n => {\n if (typeof n === 'string') {\n return parseJson(n)\n }\n return parseJson(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== ''\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n\n/**\n * Shorthand method for Object.assign \n * @param {array} args \n * @return {object} merge together object by key \n */\nexport const assign = (...args) => Reflect.apply(Object.assign, Object, args)\n \n/** \n * generic placeholder function\n * @return {boolean} false \n */\nexport const nil = () => false\n\n/**\n * generic turn config into immutatble \n */\nexport const freeze = config => Object.freeze(config)","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError'\n }\n}\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time\n}\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\n\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isString from 'lodash-es/isString'\nimport isPlainObject from 'lodash-es/isPlainObject'\n\nimport { timestamp } from './timestamp'\nimport { parseJson } from './generic'\n\n/**\n * check if the payload has a timestamp field, then append a new timestamp to it\n * @param {object} payload from the com\n * @return {array} timestamp field with an array value\n */\nexport const handleTimestamp = payload => {\n let ts = payload[TIMESTAMP_PARAM_NAME]\n if (!isArray(ts)) {\n ts = [ts]\n }\n ts.push( timestamp() )\n\n return ts\n}\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? parseJson(payload) : payload\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * extract the resolver name from the payload \n * @param {object} payload\n * @return {string} resolver name \n */\nexport function getResolverFromPayload(payload) {\n const keys = Object.keys(payload)\n return keys.filter(key => key !== TIMESTAMP_PARAM_NAME)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName name of the resolver\n * @param {*} payload what is sending \n * @param {object} extra additonal property we want to merge into the deliverable\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload, extra = {}) {\n return Object.assign({\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }, extra)\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError('utils:params-api:createQuery', { \n message: `expect resolverName to be string and args to be array!`,\n resolverName, \n args \n })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getResolverFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// There are the socket related methods ported back from \n// ws-server-core and ws-client-core \nimport {\n WS_REPLY_TYPE,\n WS_EVT_NAME,\n WS_DATA_NAME,\n TIMESTAMP_PARAM_NAME,\n ERROR_KEY,\n EMIT_REPLY_TYPE,\n EMIT_SEND_TYPE,\n ACKNOWLEDGE_REPLY_TYPE\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlValidationError } from 'jsonql-errors' \nimport isString from 'lodash-es/isString'\nimport isArray from 'lodash-es/isArray'\n\nimport { createDeliverable, formatPayload } from './params-api'\nimport { toJson, isObjectHasKey, nil } from './generic'\nimport { timestamp } from './timestamp'\n\nconst PAYLOAD_NOT_DECODED_ERR = 'payload can not decoded'\nconst WS_KEYS = [\n WS_REPLY_TYPE,\n WS_EVT_NAME,\n WS_DATA_NAME\n]\n\n/////////////////////////////////////\n// REPLY FROM SERVER //\n/////////////////////////////////////\n\n/**\n * This will be a event emit from the client using the send method \n * But we have to change the server to understand it\n * @param {string} resolverName name of resolver ot call \n * @param {array} args for the resolver\n * @param {boolean} str true then stringify it \n * @return {object} formatted payload\n */\nexport const createSendPayload = (resolverName, args, str = false) => {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n // the different is we add a additonal type in the payload \n const result = createDeliverable(resolverName, payload, {type: EMIT_SEND_TYPE})\n return str ? JSON.stringify(result) : result\n }\n throw new JsonqlValidationError(`utils:socket:createSendMsg`, { \n resolverName, \n args, \n message: 'expect resolverName to be string and args to be array!'\n })\n}\n\n/**\n * We need to find the TS field and take it out from the previous payload \n * otherwise it will keep on rolling into the structure which is not what we wanted\n * @param {object} data for inspection\n * @return {object} { data: for the data to use, TS if there is any }\n */\nconst getTsFieldFromData = (data) => {\n let obj = {[TIMESTAMP_PARAM_NAME]: [], data: {}}\n if (data[TIMESTAMP_PARAM_NAME]) {\n const ts = data[TIMESTAMP_PARAM_NAME]\n obj[TIMESTAMP_PARAM_NAME] = Array.isArray(ts) ? ts : [ts]\n delete data[TIMESTAMP_PARAM_NAME]\n } \n obj.data = data\n \n return obj\n}\n\n\n/**\n * The ws doesn't have a acknowledge callback like socket.io\n * so we have to DIY one for ws and other that doesn't have it\n * @param {string} type of reply\n * @param {string} resolverName which is replying\n * @param {*} data payload\n * @param {array} [ts= []] the last received ts, if any \n * @return {string} stringify json\n */\nexport const createWsReply = (type, resolverName, data, ts = []) => {\n const obj = getTsFieldFromData(toJson(data))\n ts = ts.concat(obj[TIMESTAMP_PARAM_NAME])\n if (!ts.length) {\n ts.push(timestamp())\n }\n return JSON.stringify({\n data: {\n [WS_REPLY_TYPE]: type,\n [WS_EVT_NAME]: resolverName,\n [WS_DATA_NAME]: obj.data \n },\n [TIMESTAMP_PARAM_NAME]: ts \n })\n}\n\n// extended function \nexport const createReplyMsg = (resolverName, data, ts = []) => (\n createWsReply(EMIT_REPLY_TYPE, resolverName, data, ts)\n)\n\nexport const createAcknowledgeMsg = (resolverName, data, ts = []) => (\n createWsReply(ACKNOWLEDGE_REPLY_TYPE, resolverName, data, ts)\n)\n\n/**\n * @param {string|object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nexport const isWsReply = payload => {\n const json = isString(payload) ? toJson(payload) : payload\n const { data } = json\n if (data) {\n let result = WS_KEYS.filter(key => isObjectHasKey(data, key))\n return (result.length === WS_KEYS.length) ? data : false\n }\n return false\n}\n\n/**\n * @param {string|object} data received data\n * @param {function} [cb=nil] this is for extracting the TS field or when it's error\n * @return {object} false on failed\n */\nexport const extractWsPayload = (payload, cb = nil) => {\n try {\n const json = toJson(payload)\n // now handle the data\n let _data\n if ((_data = isWsReply(json)) !== false) {\n // note the ts property is on its own \n cb('_data', _data)\n \n return {\n data: toJson(_data[WS_DATA_NAME]),\n resolverName: _data[WS_EVT_NAME],\n type: _data[WS_REPLY_TYPE]\n }\n }\n throw new JsonqlError(PAYLOAD_NOT_DECODED_ERR, payload)\n } catch(e) {\n return cb(ERROR_KEY, e)\n }\n}\n","// taken out from the bind-socket-event-handler \nimport { DISCONNECT_EVENT_NAME } from 'jsonql-constants'\nimport { createIntercomPayload } from '../modules'\n\n/**\n * This is the actual logout (terminate socket connection) handler \n * There is another one that is handle what should do when this happen \n * @param {object} ee eventEmitter\n * @param {object} ws the WebSocket instance\n * @return {void}\n */\nexport function disconnectEventListener(ee, ws) {\n // listen to the LOGOUT_EVENT_NAME when this is a private nsp\n ee.$on(DISCONNECT_EVENT_NAME, function closeEvtHandler() {\n try {\n // @TODO we need find a way to get the userdata\n ws.send(createIntercomPayload(LOGOUT_EVENT_NAME))\n log('terminate ws connection')\n ws.terminate()\n } catch(e) {\n console.error('ws.terminate error', e)\n }\n })\n}","// the WebSocket main handler\nimport {\n ACKNOWLEDGE_REPLY_TYPE,\n EMIT_REPLY_TYPE,\n ERROR_KEY,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME,\n ON_READY_FN_NAME,\n ON_LOGIN_FN_NAME,\n ON_ERROR_FN_NAME\n} from 'jsonql-constants'\nimport {\n createQueryStr,\n createEvt,\n extractWsPayload\n} from 'jsonql-utils/module'\nimport {\n handleNamespaceOnError\n} from '../modules'\nimport { \n disconnectEventListener\n} from './disconnect-event-listener'\n\n/**\n * in some edge case we might not even have a resolverName, then\n * we issue a global error for the developer to catch it\n * @param {object} ee event emitter\n * @param {string} namespace nsp\n * @param {string} resolverName resolver\n * @param {object} json decoded payload or error object\n * @return {undefined} nothing return\n */\nexport const errorTypeHandler = (ee, namespace, resolverName, json) => {\n let evt = [namespace]\n if (resolverName) {\n evt.push(resolverName)\n }\n evt.push(ON_ERROR_FN_NAME)\n let evtName = Reflect.apply(createEvt, null, evt)\n // test if there is a data field\n let payload = json.data || json\n ee.$trigger(evtName, [payload])\n}\n\n/**\n * Binding the event to socket normally\n * @param {string} namespace\n * @param {object} ws the nsp\n * @param {object} ee EventEmitter\n * @param {boolean} isPrivate to id if this namespace is private or not\n * @param {object} opts configuration\n * @return {object} promise resolve after the onopen event\n */\nexport function bindSocketEventHandler(namespace, ws, ee, isPrivate, opts) {\n const { log } = opts\n let onReadCalls = 2\n // setup the logut event listener \n // this will hear the event and actually call the ws.terminate\n if (isPrivate) {\n log('Private namespace', namespace, ' binding to the DISCONNECT ws.terminate')\n disconnectEventListener(ee, ws)\n }\n // log(`log test, isPrivate:`, isPrivate)\n // connection open\n ws.onopen = function onOpenCallback() {\n\n log('=== ws.onopen listened -->', namespace)\n // we just call the onReady\n ee.$trigger(ON_READY_FN_NAME, [namespace])\n // we only want to allow it get call twice (number of namespaces)\n --onReadCalls\n if (onReadCalls === 0) {\n ee.$off(ON_READY_FN_NAME)\n }\n\n // need an extra parameter here to id the private nsp\n if (isPrivate) {\n log(`isPrivate and fire the ${ON_LOGIN_FN_NAME}`)\n ee.$call(ON_LOGIN_FN_NAME)(namespace)\n }\n // add listener only after the open is called\n ee.$only(\n createEvt(namespace, EMIT_REPLY_TYPE),\n /**\n * actually send the payload to server\n * @param {string} resolverName\n * @param {array} args NEED TO CHECK HOW WE PASS THIS!\n */\n function wsMainOnEvtHandler(resolverName, args) {\n const payload = createQueryStr(resolverName, args)\n log('ws.onopen.send', resolverName, args, payload)\n\n ws.send(payload)\n }\n )\n }\n\n // reply\n // If we change it to the event callback style\n // then the payload will just be the payload and fucks up the extractWsPayload call @TODO\n ws.onmessage = function onMessageCallback(payload) {\n log(`ws.onmessage raw payload`, payload.data)\n \n // console.log(`on.message`, typeof payload, payload)\n try {\n // log(`ws.onmessage raw payload`, payload)\n // @TODO the payload actually contain quite a few things - is that changed?\n // type: message, data: data_send_from_server\n const json = extractWsPayload(payload.data)\n const { resolverName, type } = json\n\n log('Respond from server', type, json)\n\n switch (type) {\n case EMIT_REPLY_TYPE:\n let e1 = createEvt(namespace, resolverName, ON_MESSAGE_FN_NAME)\n let r = ee.$call(e1)(json)\n \n log(`EMIT_REPLY_TYPE`, e1, r)\n break\n case ACKNOWLEDGE_REPLY_TYPE:\n let e2 = createEvt(namespace, resolverName, ON_RESULT_FN_NAME)\n let x2 = ee.$call(e2)(json)\n\n log(`ACKNOWLEDGE_REPLY_TYPE`, e2, x2)\n break\n case ERROR_KEY:\n // this is handled error and we won't throw it\n // we need to extract the error from json\n log(`ERROR_KEY`)\n errorTypeHandler(ee, namespace, resolverName, json)\n break\n // @TODO there should be an error type instead of roll into the other two types? TBC\n default:\n // if this happen then we should throw it and halt the operation all together\n log('Unhandled event!', json)\n errorTypeHandler(ee, namespace, resolverName, json)\n // let error = {error: {'message': 'Unhandled event!', type}};\n // ee.$trigger(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [error])\n }\n } catch(e) {\n log(`ws.onmessage error`, e)\n errorTypeHandler(ee, namespace, false, e)\n }\n }\n // when the server close the connection\n ws.onclose = function onCloseCallback() {\n log('ws.onclose callback')\n // @TODO what to do with this\n // ee.$trigger(LOGOUT_EVENT_NAME, [namespace])\n }\n // add a onerror event handler here\n ws.onerror = function onErrorCallback(err) {\n // trigger a global error event\n log(`ws.onerror`, err)\n handleNamespaceOnError(ee, namespace, err)\n }\n \n // we don't bind the logut here and just return the ws \n return ws \n}\n","// take out from the bind-framework-to-jsonql \nimport { CONNECT_EVENT_NAME } from 'jsonql-constants'\nimport { namespaceEventListener } from '../modules'\nimport { createNsp } from '../create-nsp'\nimport { bindSocketEventHandler } from './bind-socket-event-handler'\n\n/**\n * This is the hard of establishing the connection and binding to the jsonql events \n * @param {*} nspMap \n * @param {*} ee event emitter\n * @param {function} log function to show internal \n * @return {void}\n */\nexport function connectEventListener(nspMap, ee, log) {\n log(`[2] setup the CONNECT_EVENT_NAME`)\n // this is a automatic trigger from within the framework\n ee.$only(CONNECT_EVENT_NAME, function connectEventNameHandler($config, $ee) {\n log(`[3] CONNECT_EVENT_NAME`, $ee)\n\n return createNsp($config, nspMap)\n .then(nsps => namespaceEventListener(bindSocketEventHandler, nsps))\n .then(listenerFn => listenerFn($config, nspMap, $ee))\n })\n\n // log(`[3] after setup the CONNECT_EVENT_NAME`)\n}","// share method to create the wsClientResolver\nimport { NSP_CLIENT, NSP_AUTH_CLIENT } from 'jsonql-constants'\nimport { initWebSocketClient } from './init-websocket-client'\nimport { \n loginEventListener, \n connectEventListener \n} from '../listeners'\n\n/**\n * Create the framework <---> jsonql client binding\n * @param {object} frameworkModule the different WebSocket module\n * @return {function} the wsClientResolver\n */\nfunction bindWebsocketToJsonql(frameworkModule) {\n /**\n * wsClientResolver\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\n return function createClientBindingAction(opts, nspMap, ee) {\n const { log } = opts\n\n log(`There is problem here with passing the opts`, opts)\n\n opts[NSP_CLIENT] = initWebSocketClient(frameworkModule, opts)\n opts[NSP_AUTH_CLIENT] = initWebSocketClient(frameworkModule, opts, true) \n // debug \n log(`[1] bindWebsocketToJsonql`, ee.$name, nspMap)\n // @2020-03-20 @NOTE \n \n connectEventListener(nspMap, ee, log)\n \n // next we need to setup the login event handler\n // But the same design (see above) when we received a login event \n // from the http-client or the standalone login call \n // we received a token here --> update the opts then trigger \n // the CONNECT_EVENT_NAME again\n loginEventListener(opts, nspMap, ee)\n\n log(`just before returing the values for the next operation from createClientBindingAction`)\n\n // we just return what comes in\n return { opts, nspMap, ee }\n }\n}\n\nexport { bindWebsocketToJsonql }","// this will be the news style interface that will pass to the jsonql-ws-client\n// then return a function for accepting an opts to generate the final\n// client api\nimport WebSocket from 'ws'\nimport createWebSocketBinding from '../core/create-websocket-binding'\n\n/**\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\nexport default createWebSocketBinding(WebSocket)\n","// this is the module entry point for node client\nimport {\n wsClientCore\n} from './core/modules'\nimport { wsClientConstProps } from './options'\n\nimport setupSocketClientListener from './node/setup-socket-client-listener'\n\n// export back the function and that's it\nexport default function wsNodeClient(config = {}, constProps = {}) {\n \n return wsClientCore(\n setupSocketClientListener, \n {}, \n Object.assign({}, wsClientConstProps, constProps)\n )(config)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;ACAA;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/packages/@jsonql/ws/module.js b/packages/@jsonql/ws/module.js index 6db4d66709bef4ae5fd75c18926b0bff0a2a2cb4..8be95e40b919033332d43ed34f5a51408fa84ae4 100644 --- a/packages/@jsonql/ws/module.js +++ b/packages/@jsonql/ws/module.js @@ -8,14 +8,15 @@ import { getEventEmitter, EventEmitterClass } from './src/create-combine-client' -import setupSocketClientListener from './src/core/setup-socket-client-listener' +import { setupSocketClientListener } from './src/core/setup-socket-client-listener' const createCombineWsClient = createCombineWsClientConstructor(setupSocketClientListener) export { - createCombineWsClient, checkSocketClientType, getEventEmitter, - EventEmitterClass + EventEmitterClass, + + createCombineWsClient } diff --git a/packages/@jsonql/ws/node-module.js b/packages/@jsonql/ws/node-module.js new file mode 100644 index 0000000000000000000000000000000000000000..1a67dfa329241897c46fc68dc0c2fea4e92b4b2b --- /dev/null +++ b/packages/@jsonql/ws/node-module.js @@ -0,0 +1,2 @@ +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=(t=require("ws"))&&"object"==typeof t&&"default"in t?t.default:t,r="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof r&&r&&r.Object===Object&&r,o="object"==typeof self&&self&&self.Object===Object&&self,i=n||o||Function("return this")(),a=i.Symbol;var u=Array.isArray,c=Object.prototype,s=c.hasOwnProperty,f=c.toString,l=a?a.toStringTag:void 0;var p=Object.prototype.toString;var h=a?a.toStringTag:void 0;function v(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":h&&h in Object(t)?function(t){var e=s.call(t,l),r=t[l];try{t[l]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(e?t[l]=r:delete t[l]),o}(t):function(t){return p.call(t)}(t)}function g(t){return null!=t&&"object"==typeof t}var d=a?a.prototype:void 0,y=d?d.toString:void 0;function _(t){if("string"==typeof t)return t;if(u(t))return function(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(o,i),function(t,e){for(var r=t.length;r--&&j(e,t[r],0)>-1;);return r}(o,i)+1).join("")}function q(t){return function(t){return"number"==typeof t||g(t)&&"[object Number]"==v(t)}(t)&&t!=+t}function M(t){return"string"==typeof t||!u(t)&&g(t)&&"[object String]"==v(t)}var L=function(t){return!M(t)&&!q(parseFloat(t))},F=function(t){return""!==R(t)&&M(t)},D=function(t){return null!=t&&"boolean"==typeof t},U=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==R(t)&&(!1===e||!0===e&&null!==t)},I=function(t,e){return void 0===e&&(e=""),!!u(t)&&(""===e||""===R(e)||!(t.filter((function(t){return!function(t){switch(t){case"number":return L;case"string":return F;case"boolean":return D;default:return U}}(e)(t)})).length>0))};var J,W,B=(J=Object.getPrototypeOf,W=Object,function(t){return J(W(t))}),H=Function.prototype,V=Object.prototype,G=H.toString,K=V.hasOwnProperty,Y=G.call(Object);function Q(t){if(!g(t)||"[object Object]"!=v(t))return!1;var e=B(t);if(null===e)return!0;var r=K.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&G.call(r)==Y}var X=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Z=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error);function tt(t,e){return t===e||t!=t&&e!=e}function et(t,e){for(var r=t.length;r--;)if(tt(t[r][0],e))return r;return-1}var rt=Array.prototype.splice;function nt(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},nt.prototype.set=function(t,e){var r=this.__data__,n=et(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function it(t){if(!ot(t))return!1;var e=v(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var at,ut=i["__core-js_shared__"],ct=(at=/[^.]+$/.exec(ut&&ut.keys&&ut.keys.IE_PROTO||""))?"Symbol(src)_1."+at:"";var st=Function.prototype.toString;var ft=/^\[object .+?Constructor\]$/,lt=Function.prototype,pt=Object.prototype,ht=lt.toString,vt=pt.hasOwnProperty,gt=RegExp("^"+ht.call(vt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function dt(t){return!(!ot(t)||function(t){return!!ct&&ct in t}(t))&&(it(t)?gt:ft).test(function(t){if(null!=t){try{return st.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function yt(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return dt(r)?r:void 0}var _t=yt(i,"Map"),bt=yt(Object,"create");var mt=Object.prototype.hasOwnProperty;var jt=Object.prototype.hasOwnProperty;function wt(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Vt(t){return null!=t&&Ht(t.length)&&!it(t)}var Gt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Kt=Gt&&"object"==typeof module&&module&&!module.nodeType&&module,Yt=Kt&&Kt.exports===Gt?i.Buffer:void 0,Qt=(Yt?Yt.isBuffer:void 0)||function(){return!1},Xt={};Xt["[object Float32Array]"]=Xt["[object Float64Array]"]=Xt["[object Int8Array]"]=Xt["[object Int16Array]"]=Xt["[object Int32Array]"]=Xt["[object Uint8Array]"]=Xt["[object Uint8ClampedArray]"]=Xt["[object Uint16Array]"]=Xt["[object Uint32Array]"]=!0,Xt["[object Arguments]"]=Xt["[object Array]"]=Xt["[object ArrayBuffer]"]=Xt["[object Boolean]"]=Xt["[object DataView]"]=Xt["[object Date]"]=Xt["[object Error]"]=Xt["[object Function]"]=Xt["[object Map]"]=Xt["[object Number]"]=Xt["[object Object]"]=Xt["[object RegExp]"]=Xt["[object Set]"]=Xt["[object String]"]=Xt["[object WeakMap]"]=!1;var Zt="object"==typeof exports&&exports&&!exports.nodeType&&exports,te=Zt&&"object"==typeof module&&module&&!module.nodeType&&module,ee=te&&te.exports===Zt&&n.process,re=function(){try{var t=te&&te.require&&te.require("util").types;return t||ee&&ee.binding&&ee.binding("util")}catch(t){}}(),ne=re&&re.isTypedArray,oe=ne?function(t){return function(e){return t(e)}}(ne):function(t){return g(t)&&Ht(t.length)&&!!Xt[v(t)]};function ie(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ae=Object.prototype.hasOwnProperty;function ue(t,e,r){var n=t[e];ae.call(t,e)&&tt(n,r)&&(void 0!==r||e in t)||At(t,e,r)}var ce=/^(?:0|[1-9]\d*)$/;function se(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&ce.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(je);function Ee(t,e){return Oe(function(t,e,r){return e=me(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=me(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Se.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!ot(r))return!1;var n=typeof e;return!!("number"==n?Vt(r)&&se(e,r.length):"string"==n&&e in r)&&tt(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&ur(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var Or=function(t){return Ce(t)?t:[t]},Er=function(t,e){void 0===e&&(e=!0);try{return JSON.parse(t)}catch(r){if(e)return t;throw new Error(r)}},Sr=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},$r=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},Ar=function(t){return Er("string"==typeof t?t:JSON.stringify(t))},kr=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},xr=function(){return!1},Nr=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,Or(t))}),Reflect.apply(t,null,r))}};function Tr(t,e){return t===e||t!=t&&e!=e}function Pr(t,e){for(var r=t.length;r--;)if(Tr(t[r][0],e))return r;return-1}var Cr=Array.prototype.splice;function zr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},zr.prototype.set=function(t,e){var r=this.__data__,n=Pr(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function qr(t){if(!Rr(t))return!1;var e=We(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var Mr=qe["__core-js_shared__"],Lr=function(){var t=/[^.]+$/.exec(Mr&&Mr.keys&&Mr.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();var Fr=Function.prototype.toString;function Dr(t){if(null!=t){try{return Fr.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Ur=/^\[object .+?Constructor\]$/,Ir=Function.prototype,Jr=Object.prototype,Wr=Ir.toString,Br=Jr.hasOwnProperty,Hr=RegExp("^"+Wr.call(Br).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Vr(t){return!(!Rr(t)||function(t){return!!Lr&&Lr in t}(t))&&(qr(t)?Hr:Ur).test(Dr(t))}function Gr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return Vr(r)?r:void 0}var Kr=Gr(qe,"Map"),Yr=Gr(Object,"create");var Qr=Object.prototype.hasOwnProperty;var Xr=Object.prototype.hasOwnProperty;function Zr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function En(t){return null!=t&&On(t.length)&&!qr(t)}var Sn="object"==typeof exports&&exports&&!exports.nodeType&&exports,$n=Sn&&"object"==typeof module&&module&&!module.nodeType&&module,An=$n&&$n.exports===Sn?qe.Buffer:void 0,kn=(An?An.isBuffer:void 0)||function(){return!1},xn={};xn["[object Float32Array]"]=xn["[object Float64Array]"]=xn["[object Int8Array]"]=xn["[object Int16Array]"]=xn["[object Int32Array]"]=xn["[object Uint8Array]"]=xn["[object Uint8ClampedArray]"]=xn["[object Uint16Array]"]=xn["[object Uint32Array]"]=!0,xn["[object Arguments]"]=xn["[object Array]"]=xn["[object ArrayBuffer]"]=xn["[object Boolean]"]=xn["[object DataView]"]=xn["[object Date]"]=xn["[object Error]"]=xn["[object Function]"]=xn["[object Map]"]=xn["[object Number]"]=xn["[object Object]"]=xn["[object RegExp]"]=xn["[object Set]"]=xn["[object String]"]=xn["[object WeakMap]"]=!1;var Nn="object"==typeof exports&&exports&&!exports.nodeType&&exports,Tn=Nn&&"object"==typeof module&&module&&!module.nodeType&&module,Pn=Tn&&Tn.exports===Nn&&ze.process,Cn=function(){try{var t=Tn&&Tn.require&&Tn.require("util").types;return t||Pn&&Pn.binding&&Pn.binding("util")}catch(t){}}(),zn=Cn&&Cn.isTypedArray,Rn=zn?function(t){return function(e){return t(e)}}(zn):function(t){return Ve(t)&&On(t.length)&&!!xn[We(t)]};function qn(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var Mn=Object.prototype.hasOwnProperty;function Ln(t,e,r){var n=t[e];Mn.call(t,e)&&Tr(n,r)&&(void 0!==r||e in t)||on(t,e,r)}var Fn=/^(?:0|[1-9]\d*)$/;function Dn(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&Fn.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Xn);function eo(t,e){return to(function(t,e,r){return e=Qn(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Qn(n.length-e,0),a=Array(i);++o1?r[o-1]:void 0,a=o>2?r[2]:void 0;for(i=t.length>3&&"function"==typeof i?(o--,i):void 0,a&&function(t,e,r){if(!Rr(r))return!1;var n=typeof e;return!!("number"==n?En(r)&&Dn(e,r.length):"string"==n&&e in r)&&Tr(r[e],t)}(r[0],r[1],a)&&(i=o<3?void 0:i,o=1),e=Object(e);++n0))},qo=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},Mo=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!zo(e)(t)})).length)})).length:e.length>e.filter((function(t){return!Ro(r,t)})).length},Lo=function(t,e){if(void 0===e&&(e=null),Ze(t)){if(!e)return!0;if(Ro(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return void 0===r||(!1!==(e=qo(t))?!Mo({arg:r},e):!zo(t)(r))})).length)})).length}return!1},Fo=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Lo,null,a);case"array"===t:return!Ro(e.arg);case!1!==(r=qo(t)):return!Mo(e,r);default:return!zo(t)(e.arg)}},Do=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Uo=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!Ro(e))throw new go("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!Ro(t))throw console.info(t),new go("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Do(t,a):t,index:r,param:a,optional:i}}));default:throw new yo("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!ko(e)&&!(r.type.length>r.type.filter((function(e){return Fo(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Fo(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Io=Be(Object.keys,Object),Jo=Object.prototype.hasOwnProperty;function Wo(t){return En(t)?In(t):function(t){if(!yn(t))return Io(t);var e=[];for(var r in Object(t))Jo.call(t,r)&&"constructor"!=r&&e.push(r);return e}(t)}function Bo(t,e){return t&&un(t,e,Wo)}function Ho(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new en;++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=2&r?new Ho:void 0;for(i.set(t,e),i.set(e,t);++f0){if(!1!==this.$get(t,!0)){var n=this.searchMapEvt(t);if(n.length){var o=n[0][3],i=(this.checkMaxStore(t,e),this);return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var a=i.getMaxStore(t),u=-1;if(a>0){var c=i.$call(t,o,r);if(Reflect.apply(c,i,e),-1===(u=i.checkMaxStore(t)))return i.$off(t),-1}return u}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,n))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var a=Array.from(i.get(t)),u=a.length,c=!1,s=0;s0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,r=t[3];return e=r,!!ua.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var n=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',n),r.delete(t),n}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];var o=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||o.add(r)}else this.checkContentExist(r,o)||(this.logger("(addToStore) insert new",r),o.add(r));else o.add(r);return t.set(e,o),[t,o.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,this.logger("(addToLazyStore) size: "+u),u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){la.set(this,t)},r.normalStore.get=function(){return la.get(this)},r.lazyStore.set=function(t){pa.set(this,t)},r.lazyStore.get=function(){return pa.get(this)},Object.defineProperties(e.prototype,r),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=null,this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(t){var e=function(t){switch(!0){case!0===ca(t):return t;case!0===sa(t):return new RegExp(t);default:return!1}}(t);if(ca(e))return this.__pattern__=e,this.$suspend();throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof e+'" instead')},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];if(this.logger("($queue) get called"),!0===this.__suspend_state__){if(ca(this.__pattern__)){var n=this.__pattern__.test(t);if(!n)return!1}this.logger("($queue) added to $queue",e),this.queueStore.add([t].concat(e))}return!!this.__suspend_state__},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=null,this.logger("(release) was called with "+e+(r?' for "'+r+'"':"")+" item"+(e>1?"s":"")),e>0){var n=Array.from(this.queueStore);this.queueStore.clear(),this.logger("(release queue)",n),n.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(ha))),da=function(t){function e(e){if("function"!=typeof e)throw new Error("Just die here the logger is not a function!");e("---\x3e Create a new EventEmitter <---"),t.call(this,{logger:e})}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"jsonql-ws-client-core"},Object.defineProperties(e.prototype,r),e}(ga),ya=function(t){var e=t.log,r=t.eventEmitter;return r?(e("eventEmitter is:",r.name),r):new da(t.log)},_a=function(t){var e=t.toLowerCase();return e.indexOf("http")>-1?e.indexOf("https")>-1?e.replace("https","wss"):e.replace("http","ws"):e},ba=function(t,e){Or(e).forEach((function(e){t.$off($r(e,"emit_reply"))}))};function ma(t,e,r){Sr(t,"error")?r(t.error):Sr(t,"data")?Reflect.apply(e,null,[].concat(t.data)):r({message:"UKNNOWN RESULT!",error:t})}function ja(t,e,r,n,o){void 0===n&&(n=[]);var i=$r(e,"emit_reply");return o("actionCall: "+i+" --\x3e "+r,n),t.$trigger(i,[r,Or(n)]),new Promise((function(n,i){var a=$r(e,r,"onResult");t.$on(a,(function(t){o("got the first result",t),ma(t,n,i)}))}))}var wa=function(t,e,r,n,o,i){return no(t,"send",xr,(function(){return i("running call getter method"),function(){for(var t=[],a=arguments.length;a--;)t[a]=arguments[a];return Zi(t,o.params,!0).then((function(t){return i("execute send",r,n,t),ja(e,r,n,t,i)})).catch((function(t){i("send error",t),e.$call($r(r,n,"onError"),[new go(n,t)])}))}}))};function Oa(t,e,r,n,o){return function(){for(var i=[],a=arguments.length;a--;)i[a]=arguments[a];return Zi(i,n.params,!0).then((function(n){return ja(t,e,r,n,o)})).catch(bo)}}var Ea=function(t,e,r,n,o,i){return[oo(t,"myNamespace",r),e,r,n,o,i]},Sa=function(t,e,r,n,o,i){return[no(t,"onResult",(function(t){kr(t)&&e.$on($r(r,n,"onResult"),(function(o){ma(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger($r(r,n,"onError"),t)}))}))})),e,r,n,o,i]},$a=function(t,e,r,n,o,i){return[no(t,"onMessage",(function(t){if(kr(t)){e.$only($r(r,n,"onMessage"),(function(o){i("onMessageCallback",o),ma(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger($r(r,n,"onError"),t)}))}))}})),e,r,n,o,i]},Aa=function(t,e,r,n,o,i){return[no(t,"onError",(function(t){kr(t)&&e.$only($r(r,n,"onError"),t)})),e,r,n,o,i]};function ka(t,e,r,n,o,i){var a=[Ea,Sa,$a,Aa,wa];return Reflect.apply(Nr,null,a)(n,o,t,e,r,i)}function xa(t,e,r){var n=t.log,o={};for(var i in r){var a=r[i];for(var u in a){var c=a[u];o=oo(o,u,ka(i,u,c,Oa(e,i,u,c,n),e,n))}}return[o,t,e,r]}function Na(t,e,r){return[no(t,"onReady",(function(t){kr(t)&&r.$only("onReady",t)})),e,r]}function Ta(t,e,r,n){return[no(t,"onError",(function(t){if(kr(t))for(var e in n)r.$on($r(e,"onError"),t)})),e,r]}var Pa,Ca,za=function(t,e,r){return[oo(t,e.loginHandlerName,(function(t){if(t&&Xi(t))return e.log("Received __login__ with "+t),r.$trigger("__login__",[t]);throw new go(e.loginHandlerName,"Unexpected token "+t)})),e,r]},Ra=function(t,e,r){return[oo(t,e.logoutHandlerName,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__logout__",t)})),e,r]},qa=function(t,e,r){return[no(t,"onLogin",(function(t){kr(t)&&r.$only("onLogin",t)})),e,r]};function Ma(t,e,r){return Nr(za,Ra,qa)(t,e,r)}function La(t,e,r){return(0,e.log)("[1] setupConnectPropKey"),[t=oo(t,"connected",!1,!0),e,r]}function Fa(t,e,r){var n=e.log;return n("[2] setupConnectEvtListener"),r.$on("__connect__",(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];n("setupConnectEvtListener pass and do nothing at the moment",t)})),[t,e,r]}function Da(t,e,r){var n=e.log;return n("[3] setupConnectedEvtListener"),r.$on("__connected__",(function(){var e;t.connected=!0;var o=r.$release();return n("CONNECTED_EVENT_NAME",!0,"queue count",o),(e={}).connected=!0,e})),[t,e,r]}function Ua(t,e,r){var n=e.log;return n("[4] setupDisconnectListener"),r.$on("__disconnect__",(function(){var e;return t.connected=!1,n("CONNECTED_EVENT_NAME",!1),(e={}).connected=!1,e})),[t,e,r]}function Ia(t,e,r){var n=e.disconnectHandlerName;return(0,e.log)("[5] setupDisconectAction"),oo(t,n,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__disconnect__",t)}))}function Ja(t,e,r){var n=function(t,e,r){var n=[La,Fa,Da,Ua,Ia];return Reflect.apply(Nr,null,n)(t,e,r)}(t,e,r);return n.verifyEventEmitter=function(){return r.is},n.eventEmitter=e.eventEmitter,n.log=e.log,r.$trigger("__connect__",[e,r]),!0===e.suspendOnStart&&e.$releaseNamespace(),n}var Wa={};Wa.standalone=ta(!1,["boolean"]),Wa.debugOn=ta(!1,["boolean"]),Wa.loginHandlerName=ta("login",["string"]),Wa.logoutHandlerName=ta("logout",["string"]),Wa.disconnectHandlerName=ta("disconnect",["string"]),Wa.switchUserHandlerName=ta("switch-user",["string"]),Wa.hostname=ta(!1,["string"]),Wa.namespace=ta("jsonql",["string"]),Wa.wsOptions=ta({},["object"]),Wa.contract=ta({},["object"],((Pa={}).checker=function(t){return!!function(t){return Ze(t)&&(Sr(t,"query")||Sr(t,"mutation")||Sr(t,"socket"))}(t)&&t},Pa)),Wa.enableAuth=ta(!1,["boolean"]),Wa.token=ta(!1,["string"]),Wa.csrf=ta("X-CSRF-Token",["string"]),Wa.useJwt=ta(!0,["boolean","string"]),Wa.suspendOnStart=ta(!1,["boolean"]);var Ba={};Ba.serverType=ta(null,["string"],((Ca={}).alias="socketClientType",Ca));var Ha=Object.assign(Wa,Ba),Va={log:null,eventEmitter:null,nspClient:null,nspAuthClient:null,wssPath:"",publicNamespace:"public",privateNamespace:"private"};function Ga(t){return Promise.resolve(t).then((function(t){return t.hostname||(t.hostname=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new go(t)}}()),t.wssPath=_a([t.hostname,t.namespace].join("/"),t.serverType),t.log=oa(t),t.eventEmitter=ya(t),t}))}function Ka(t){var e=function(t){var e=t.contract,r=t.enableAuth,n=function(t){var e="jsonql";return t.enableAuth?[[e,t.privateNamespace].join("/"),[e,t.publicNamespace].join("/")]:[e]}(t),o=r?Eo(e):function(t,e){var r,n={};for(var o in t){var i=t[o];n[o]=i}return{size:1,nspGroup:(r={},r[e]=n,r),publicNamespace:e}}(e.socket,n[0]);return Object.assign(o,{namespaces:n})}(t),r=t.eventEmitter,n=t.log,o=e.namespaces;return n("namespaces",o),!0===t.suspendOnStart&&(t.$suspendNamepsace=function(){return o.forEach((function(t){return r.$suspendEvent(t)}))},t.$releaseNamespace=function(){return r.$release()},t.$suspendNamepsace()),{opts:t,nspMap:e,ee:r}}function Ya(t){return function(e){return void 0===e&&(e={}),Ga(e).then(Ka).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return function(t,e,r){var n=[xa,Na,Ta];return t.enableAuth&&n.push(Ma),n.push(Ja),Reflect.apply(Nr,null,n)(t,r,e.nspGroup)}(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("[jsonql-ws-core-client init error]",t)}))}}var Qa=function(t,e,r,n){var o=n.log;r.$on("__logout__",(function(){var i=getPrivateNamespace(e);o("__logout__ event triggered"),function(t,e,r){e.forEach((function(e){t.$trigger($r(e,"onError"),[{message:r,namespace:e}])}))}(r,[i],"__logout__"),o("logout from "+i),ba(r,i),t[i]=null,notLoginWsListerner(i,r,n)}))};function Xa(t,e){return function(r,n,o){var i=r.log,a=n.namespaces,u=function(t){return t.length>1&&t[0]}(a);return a.map((function(n){var c=u===n;if(i(n," --\x3e "+(c?"private":"public")+" nsp --\x3e ",!1!==e[n]),e[n]){i("[call bindWsHandler]",c,n);var s=[n,e[n],o,c,r];Reflect.apply(t,null,s)}else i("binding notLoginWsHandler to "+n),function(t,e,r){var n=r.log;e.$only($r(t,"emit_reply"),(function(r,o){n("[notLoginListerner] hijack the ws call",t,r,o);var i={message:"NOT LOGIN"};e.$call($r(t,r,"onError"),[i]),e.$call($r(t,r,"onResult"),[{error:i}])}))}(n,o,r);return c&&(i("Has private and add logoutEvtHandler"),Qa(e,a,o,r)),c}))}}function Za(t,e,r,n){var o=function(t,e){var r=Object.assign({},t,Ha),n=Object.assign({},e,Va);return function(t){return ea(t,r,n)}}(r,n);return function(r){return void 0===r&&(r={}),o(r).then((function(e){return t(e)})).then((function(t){var r=Ya(e)(opts);return t.socket=r,t}))}}function tu(t,e){var r=e.hostname,n=e.wssPath,o=e.nspClient,i=e.log,a=t?[r,t].join("/"):n;return i("createNspClient --\x3e ",a),o(a,e)}var eu,ru,nu,ou,iu,au,uu,cu,su;Error;try{"undefined"!=typeof window&&window.atob&&window.atob.bind(window)}catch(t){}ta("HS256",["string"]),ta(!1,["boolean","number","string"],((eu={}).alias="exp",eu.optional=!0,eu)),ta(!1,["boolean","number","string"],((ru={}).alias="nbf",ru.optional=!0,ru)),ta(!1,["boolean","string"],((nu={}).alias="iss",nu.optional=!0,nu)),ta(!1,["boolean","string"],((ou={}).alias="sub",ou.optional=!0,ou)),ta(!1,["boolean","string"],((iu={}).alias="iss",iu.optional=!0,iu)),ta(!1,["boolean"],((au={}).optional=!0,au)),ta(!1,["boolean","string"],((uu={}).optional=!0,uu)),ta(!1,["boolean","string"],((cu={}).optional=!0,cu)),ta(!1,["boolean"],((su={}).optional=!0,su));var fu=require("jsonql-constants"),lu=fu.TOKEN_PARAM_NAME,pu=fu.AUTH_HEADER,hu=fu.TOKEN_DELIVER_LOCATION_PROP_KEY,vu=fu.TOKEN_IN_URL,gu=fu.TOKEN_IN_HEADER,du=fu.WS_OPT_PROP_KEY;function yu(t,e,r){var n;if(void 0===r&&(r=!1),!1===r)return{url:t,opts:e[du]||{}};switch(function(t){return t[hu]||vu}(e)){case vu:return{url:t+"?"+lu+"="+r,opts:e[du]||{}};case gu:return{url:t,opts:Object.assign({},e[du]||{},{headers:(n={},n[pu]=r,n)})}}}function _u(t,e,r,n,o,i){t.onopen=function(){t.send(Oo("__intercom__",["__ping__",mo()]))},t.onmessage=function(a){try{var u=Ao(a.data);setTimeout((function(){t.terminate()}),50);var c=new e(r,Object.assign(n,u));o(c)}catch(t){i(t)}},t.onerror=function(t){i(t)}}function bu(t,e,r){return new Promise((function(n,o){return _u(new t(e,r),t,e,r,n,o)}))}function mu(t,e){return void 0===e&&(e=!1),!1===e?function(e,r){var n=r.log,o=yu(e,r,!1),i=o.url,a=o.opts;return n("createWsClient url: "+i+" with opts:",a),bu(t,_a(i),a)}:function(e,r,n){var o=r.log,i=yu(e,r,n),a=i.url,u=i.opts;return o("createWsAuthClient url: "+a+" with opts:",u),bu(t,_a(a),u)}}var ju=function(t,e,r){void 0===r&&(r=null),r=r||t.token;var n,o,i=e.publicNamespace,a=e.namespaces,u=t.log;return u("createNspAction","publicNamespace",i,"namespaces",a),t.enableAuth?(n=a.map((function(e,n){return 0===n?r?(t.token=r,u("create createNspAuthClient at run time"),function(t,e){var r=e.hostname,n=e.wssPath,o=e.token,i=e.nspAuthClient,a=e.log,u=t?[r,t].join("/"):n;if(a("createNspAuthClient --\x3e",u),o&&"string"!=typeof o)throw new Error("Expect token to be string, but got "+o);return i(u,e,o)}(e,t)):Promise.resolve(!1):tu(e,t)})),void 0===o&&(o=!1),n.reduce((function(t,e){return t.then((function(t){return e.then((function(e){return!1===o?t.concat([e]):$e(t,e)}))}))}),Promise.resolve(!1===o?[]:Q(o)?o:{}))).then((function(t){return t.map((function(t,e){var r;return(r={})[a[e]]=t,r})).reduce((function(t,e){return Object.assign(t,e)}),{})})):tu(!1,t).then((function(t){var e;return(e={})[i]=t,e}))},wu=function(t,e){void 0===e&&(e=!0);try{return JSON.parse(t)}catch(r){if(e)return t;throw new Error(r)}},Ou=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},Eu=function(t){return wu("string"==typeof t?t:JSON.stringify(t))},Su=function(){return!1},$u=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Au(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),M(t)&&u(e)){var n=function(t){var e;return(e={}).args=t,e}(e);return!0===r?n:function(t,e,r){var n;return void 0===r&&(r={}),Object.assign(((n={})[t]=e,n.TS=[$u()],n),r)}(t,n)}throw new X("utils:params-api:createQuery",{message:"expect resolverName to be string and args to be array!",resolverName:t,args:e})}var ku=["__reply__","__event__","__data__"],xu=function(t){var e=(M(t)?Eu(t):t).data;return!!e&&(ku.filter((function(t){return function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n}(e,t)})).length===ku.length&&e)};function Nu(t,e){t.$on("__disconnect__",(function(){try{e.send(function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];var n=mo(),o=[t].concat(e);return o.push(n),Oo("__intercom__",o)}(LOGOUT_EVENT_NAME)),log("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var Tu=function(t,e,r,n){var o=[e];r&&o.push(r),o.push("onError");var i=Reflect.apply(Ou,null,o),a=n.data||n;t.$trigger(i,[a])};function Pu(t,e,r,n,o){var i=o.log,a=2;return n&&(i("Private namespace",t," binding to the DISCONNECT ws.terminate"),Nu(r,e)),e.onopen=function(){i("=== ws.onopen listened --\x3e",t),r.$trigger("onReady",[t]),0===--a&&r.$off("onReady"),n&&(i("isPrivate and fire the onLogin"),r.$call("onLogin")(t)),r.$only(Ou(t,"emit_reply"),(function(t,r){var n=function(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(Au(t,e,r))}(t,r);i("ws.onopen.send",t,r,n),e.send(n)}))},e.onmessage=function(e){i("ws.onmessage raw payload",e.data);try{var n=function(t,e){void 0===e&&(e=Su);try{var r,n=Eu(t);if(!1!==(r=xu(n)))return e("_data",r),{data:Eu(r.__data__),resolverName:r.__event__,type:r.__reply__};throw new Z("payload can not decoded",t)}catch(t){return e("error",t)}}(e.data),o=n.resolverName,a=n.type;switch(i("Respond from server",a,n),a){case"emit_reply":var u=Ou(t,o,"onMessage"),c=r.$call(u)(n);i("EMIT_REPLY_TYPE",u,c);break;case"emit_acknowledge":var s=Ou(t,o,"onResult"),f=r.$call(s)(n);i("ACKNOWLEDGE_REPLY_TYPE",s,f);break;case"error":i("ERROR_KEY"),Tu(r,t,o,n);break;default:i("Unhandled event!",n),Tu(r,t,o,n)}}catch(e){i("ws.onmessage error",e),Tu(r,t,!1,e)}},e.onclose=function(){i("ws.onclose callback")},e.onerror=function(e){i("ws.onerror",e),function(t,e,r){t.$trigger($r(e,"onError"),[r])}(r,t,e)},e}var Cu,zu=function(t){return function(e,r,n){var o=Object.assign({},n,Te),i=Object.assign({},r,Pe);return Za(e,t,i,o)}}((Cu=e,function(t,e,r){var n=t.log;return n("There is problem here with passing the opts",t),t.nspClient=mu(Cu),!0===t.enableAuth&&(t.nspAuthClient=mu(Cu,!0)),n("[1] bindWebsocketToJsonql",r.$name,e),function(t,e,r){r("[2] setup the CONNECT_EVENT_NAME"),e.$only("__connect__",(function(e,n){return r("[3] CONNECT_EVENT_NAME",n),ju(e,t).then((function(t){return Xa(Pu,t)})).then((function(r){return r(e,t,n)}))}))}(e,r,n),function(t,e,r){var n=t.log,o=e.namespaces;n("[4] loginEventHandler"),r.$only("__login__",(function(e){n("createClient LOGIN_EVENT_NAME $only handler"),ba(r,o),t.token=e,r.$trigger("__connect__",[t,r])}))}(t,e,r),n("just before returing the values for the next operation from createClientBindingAction"),{opts:t,nspMap:e,ee:r}}));exports.EventEmitterClass=ga,exports.checkSocketClientType=function(t){return ra(t,Ba)},exports.createCombineWsClient=zu,exports.getEventEmitter=ya; +//# sourceMappingURL=node-module.js.map diff --git a/packages/@jsonql/ws/node-module.js.map b/packages/@jsonql/ws/node-module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b9d5278e1e41a9046fa2df29cb0c418bd7528378 --- /dev/null +++ b/packages/@jsonql/ws/node-module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"node-module.js","sources":["../../ws-client-core/node_modules/lodash-es/_strictIndexOf.js","../../ws-client-core/node_modules/lodash-es/_unicodeToArray.js","../../ws-client-core/node_modules/lodash-es/_hasUnicode.js","../../ws-client-core/node_modules/lodash-es/_toSource.js","../../ws-client-core/node_modules/lodash-es/_stackHas.js","../../ws-client-core/node_modules/lodash-es/isObject.js","../../ws-client-core/node_modules/lodash-es/_apply.js","../../ws-client-core/node_modules/jsonql-params-validator/src/string.js","../../ws-client-core/node_modules/lodash-es/_setCacheAdd.js","../../ws-client-core/src/listener/event-listeners.js"],"sourcesContent":["/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false\n}\n\nexport default checkIsString\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","// NOT IN USE AT THE MOMENT JUST KEEP IT HERE FOR THE TIME BEING \nimport {\n LOGOUT_EVENT_NAME,\n NOT_LOGIN_ERR_MSG,\n ON_ERROR_FN_NAME,\n ON_RESULT_FN_NAME,\n DISCONNECT_EVENT_NAME,\n SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\nimport { EMIT_EVT, DISCONNECTED_ERROR_MSG } from '../options/constants'\nimport { createEvt, clearMainEmitEvt } from '../utils'\nimport { triggerNamespacesOnError } from './trigger-namespaces-on-error'\n\n/**\n * A Event Listerner placeholder when it's not connect to any nsp\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nexport const notConnectedListener = (namespace, ee, opts) => {\n const { log } = opts \n\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function disconnectedEvtCallback(resolverName, args) {\n log(`[disconnectedListerner] hijack the ws call`, namespace, resolverName, args)\n // Now we suspend all the calls but note the existing one won't be affected \n // we need to update the methods to move everything across \n \n\n const error = {\n message: DISCONNECTED_ERROR_MSG\n }\n ee.$call(createEvt(namespace, resolverName, ON_ERROR_FN_NAME), [ error ])\n // also trigger the result Listerner, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [{ error }])\n }\n )\n}\n\n\n/**\n * The disconnect event Listerner, now we log the client out from everything\n * @TODO now we are another problem they disconnect, how to reconnect\n * @param {object} nsps the available nsp(s)\n * @param {array} namespaces available namespace \n * @param {object} ee eventEmitter \n * @param {object} opts configuration\n * @return {void}\n */\nexport const disconnectListener = (nsps, namespaces, ee, opts) => {\n const { log } = opts \n ee.$on(\n DISCONNECT_EVENT_NAME, \n function disconnectEvtCallback() {\n triggerNamespacesOnError(ee, namespaces, DISCONNECT_EVENT_NAME)\n namespaces.forEach( namespace => { \n log(`disconnect from ${namespace}`)\n\n clearMainEmitEvt(ee, namespace)\n nsps[namespace] = null \n disconnectedListerner(namespace, ee, opts)\n })\n }\n )\n}\n\n/**\n * A Event Listerner placeholder when it's not connect to the private nsp\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nexport const notLoginListener = (namespace, ee, opts) => {\n const { log } = opts \n\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function notLoginListernerCallback(resolverName, args) {\n log('[notLoginListerner] hijack the ws call', namespace, resolverName, args)\n const error = { message: NOT_LOGIN_ERR_MSG }\n // It should just throw error here and should not call the result\n // because that's channel for handling normal event not the fake one\n ee.$call(createEvt(namespace, resolverName, ON_ERROR_FN_NAME), [ error ])\n // also trigger the result Listerner, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [{ error }])\n }\n )\n}\n\n/**\n * Only when there is a private namespace then we bind to this event\n * @param {object} nsps the available nsp(s)\n * @param {array} namespaces available namespace \n * @param {object} ee eventEmitter \n * @param {object} opts configuration\n * @return {void}\n */\nexport const logoutEvtListener = (nsps, namespaces, ee, opts) => {\n const { log } = opts \n // this will be available regardless enableAuth\n // because the server can log the client out\n ee.$on(\n LOGOUT_EVENT_NAME, \n function logoutEvtCallback() {\n const privateNamespace = getPrivateNamespace(namespaces)\n log(`${LOGOUT_EVENT_NAME} event triggered`)\n // disconnect(nsps, opts.serverType)\n // we need to issue error to all the namespace onError Listerner\n triggerNamespacesOnError(ee, [privateNamespace], LOGOUT_EVENT_NAME)\n // rebind all of the Listerner to the fake one\n log(`logout from ${privateNamespace}`)\n\n clearMainEmitEvt(ee, privateNamespace)\n // we need to issue one more call to the server before we disconnect\n // now this is a catch 22, here we are not suppose to do anything platform specific\n // so that should fire before trigger this event\n // clear out the nsp\n nsps[privateNamespace] = null \n // add a NOT LOGIN error if call\n notLoginWsListerner(privateNamespace, ee, opts)\n }\n )\n}\n\n"],"names":[],"mappings":"0xfAAA,qxBCAA,yECAA,snFCAA,0zDCAA,0DCAA,o3JCAA,2uTCAA,i+FCAA,iv4BCAA"} \ No newline at end of file diff --git a/packages/@jsonql/ws/main.js b/packages/@jsonql/ws/node-ws-client.js similarity index 92% rename from packages/@jsonql/ws/main.js rename to packages/@jsonql/ws/node-ws-client.js index 9b4087dc104a45ffce6f8576545e4989d765f5bc..7e2477e94d655f95c641a273560d006f805b19ed 100644 --- a/packages/@jsonql/ws/main.js +++ b/packages/@jsonql/ws/node-ws-client.js @@ -8,7 +8,6 @@ var WebSocket = _interopDefault(require('ws')); // the core stuff to id if it's calling with jsonql var DATA_KEY = 'data'; var ERROR_KEY = 'error'; -var HEADERS_KEY = 'headers'; var JSONQL_PATH = 'jsonql'; @@ -48,6 +47,7 @@ var ARGS_KEY = 'args'; var CHECKER_KEY = 'checker'; var ALIAS_KEY = 'alias'; var ENABLE_AUTH_PROP_KEY = 'enableAuth'; +var USE_JWT_PROP_KEY = 'useJwt'; var LOGIN_FN_NAME_PROP_KEY = 'loginHandlerName'; var LOGOUT_FN_NAME_PROP_KEY = 'logoutHandlerName'; var DISCONNECT_FN_NAME_PROP_KEY = 'disconnectHandlerName'; @@ -56,6 +56,8 @@ var SWITCH_USER_FN_NAME_PROP_KEY = 'switchUserHandlerName'; var SOCKET_TYPE_PROP_KEY = 'serverType'; //1.9.1 var SOCKET_TYPE_CLIENT_ALIAS = 'socketClientType'; // 1.9.0 +var CSRF_PROP_KEY = 'csrf'; + var STANDALONE_PROP_KEY = 'standalone'; var DEBUG_ON_PROP_KEY = 'debugOn'; @@ -69,13 +71,7 @@ var TOKEN_PROP_KEY = 'token'; var CONNECTED_PROP_KEY = 'connected'; // track this key if we want to suspend event on start -var SUSPEND_EVENT_PROP_KEY = 'suspendOnStart'; /* socket.js */ - -// the constants file is gettig too large -// we need to split up and group the related constant in one file -// also it makes the other module easiler to id what they are importing -// use throughout the clients -var SOCKET_PING_EVENT_NAME = '__ping__'; // when init connection do a ping +var SUSPEND_EVENT_PROP_KEY = 'suspendOnStart'; var LOGIN_EVENT_NAME = '__login__'; var LOGOUT_EVENT_NAME$1 = '__logout__'; // at the moment we only have __logout__ regardless enableAuth is enable @@ -95,10 +91,6 @@ var DISCONNECT_EVENT_NAME = '__disconnect__'; // instead of using an event name in place of resolverName in the param // we use this internal resolverName instead, and in type using the event names var INTERCOM_RESOLVER_NAME = '__intercom__'; -// for ws servers -var WS_REPLY_TYPE = '__reply__'; -var WS_EVT_NAME = '__event__'; -var WS_DATA_NAME = '__data__'; // for ws client, 1.9.3 breaking change to name them as FN instead of PROP var ON_MESSAGE_FN_NAME = 'onMessage'; @@ -115,8 +107,8 @@ var EMIT_REPLY_TYPE = 'emit_reply'; var NSP_GROUP = 'nspGroup'; var PUBLIC_NAMESPACE = 'publicNamespace'; var NOT_LOGIN_ERR_MSG = 'NOT LOGIN'; -var IO_ROUNDTRIP_LOGIN = 'roundtip'; -var IO_HANDSHAKE_LOGIN = 'handshake'; +var HSA_ALGO = 'HS256'; + /* validation.js */ // validation related constants @@ -754,25 +746,6 @@ var inArray = function (arr, value) { return !!arr.filter(function (a) { return // quick and dirty to turn non array to array var toArray = function (arg) { return isArray(arg) ? arg : [arg]; }; -/** - * parse string to json or just return the original value if error happened - * @param {*} n input - * @param {boolean} [t=true] or throw - * @return {*} json object on success - */ -var parseJson = function(n, t) { - if ( t === void 0 ) t=true; - - try { - return JSON.parse(n) - } catch(e) { - if (t) { - return n - } - throw new Error(e) - } -}; - /** * @param {object} obj for search * @param {string} key target @@ -800,18 +773,6 @@ var createEvt = function () { return args.join('_'); }; -/** - * small util to make sure the return value is valid JSON object - * @param {*} n input - * @return {object} correct JSON object - */ -var toJson = function (n) { - if (typeof n === 'string') { - return parseJson(n) - } - return parseJson(JSON.stringify(n)) -}; - /** * Simple check if the prop is function * @param {*} prop input @@ -3590,102 +3551,7 @@ function getNspInfoByConfig(config) { return Object.assign(nspInfo, { namespaces: namespaces }) } -// There are the socket related methods ported back from - -var PAYLOAD_NOT_DECODED_ERR = 'payload can not decoded'; -var WS_KEYS = [ - WS_REPLY_TYPE, - WS_EVT_NAME, - WS_DATA_NAME -]; - -/** - * @param {string|object} payload should be string when reply but could be transformed - * @return {boolean} true is OK - */ -var isWsReply = function (payload) { - var json = isString(payload) ? toJson(payload) : payload; - var data = json.data; - if (data) { - var result = WS_KEYS.filter(function (key) { return isObjectHasKey(data, key); }); - return (result.length === WS_KEYS.length) ? data : false - } - return false -}; - -/** - * @param {string|object} data received data - * @param {function} [cb=nil] this is for extracting the TS field or when it's error - * @return {object} false on failed - */ -var extractWsPayload = function (payload, cb) { - if ( cb === void 0 ) cb = nil; - - try { - var json = toJson(payload); - // now handle the data - var _data; - if ((_data = isWsReply(json)) !== false) { - // note the ts property is on its own - cb('_data', _data); - - return { - data: toJson(_data[WS_DATA_NAME]), - resolverName: _data[WS_EVT_NAME], - type: _data[WS_REPLY_TYPE] - } - } - throw new JsonqlError$1(PAYLOAD_NOT_DECODED_ERR, payload) - } catch(e) { - return cb(ERROR_KEY, e) - } -}; - // this will be part of the init client sequence -var CSRF_HEADER_NOT_EXIST_ERR = 'CSRF header is not in the received payload'; - -/** - * Util method - * @param {string} payload return from server - * @return {object} the useful bit - */ -function extractSrvPayload(payload) { - var json = toJson(payload); - - if (json && typeof json === 'object') { - // note this method expect the json.data inside - return extractWsPayload(json) - } - - throw new JsonqlError$1('extractSrvPayload', json) -} - -/** - * call the server to get a csrf token - * @return {string} formatted payload to send to the server - */ -function createInitPing() { - var ts = timestamp(); - - return createQueryStr(INTERCOM_RESOLVER_NAME, [SOCKET_PING_EVENT_NAME, ts]) -} - -/** - * Take the raw on.message result back then decoded it - * @param {*} payload the raw result from server - * @return {object} the csrf payload - */ -function extractPingResult(payload) { - var obj; - - var result = extractSrvPayload(payload); - - if (result && result[DATA_KEY] && result[DATA_KEY][CSRF_HEADER_KEY]) { - return ( obj = {}, obj[HEADERS_KEY] = result[DATA_KEY], obj ) - } - - throw new JsonqlError$1('extractPingResult', CSRF_HEADER_NOT_EXIST_ERR) -} /** @@ -7368,9 +7234,11 @@ var getEventEmitter = function (opts) { /** * WebSocket is strict about the path, therefore we need to make sure before it goes in * @param {string} url input url + * @param {string} serverType this is not in use at the moment * @return {string} url with correct path name */ -var fixWss = function (url) { +var fixWss = function (url, serverType) { + var uri = url.toLowerCase(); if (uri.indexOf('http') > -1) { if (uri.indexOf('https') > -1) { @@ -8053,12 +7921,9 @@ function callersGenerator(opts, nspMap, ee) { return executer(opts, ee, nspMap[NSP_GROUP]) } -var obj, obj$1, obj$2; -// import { AVAILABLE_SERVERS } from './constants' -var AVAILABLE_METHODS = [ - IO_ROUNDTRIP_LOGIN, - IO_HANDSHAKE_LOGIN -]; +var obj, obj$1; + + var configCheckMap = {}; configCheckMap[STANDALONE_PROP_KEY] = createConfig$1(false, [BOOLEAN_TYPE]); @@ -8073,32 +7938,25 @@ configCheckMap[WS_OPT_PROP_KEY] = createConfig$1({}, [OBJECT_TYPE]); configCheckMap[CONTRACT_PROP_KEY] = createConfig$1({}, [OBJECT_TYPE], ( obj = {}, obj[CHECKER_KEY] = isContract, obj )); configCheckMap[ENABLE_AUTH_PROP_KEY] = createConfig$1(false, [BOOLEAN_TYPE]); configCheckMap[TOKEN_PROP_KEY] = createConfig$1(false, [STRING_TYPE]); -configCheckMap.loginMethod = createConfig$1(IO_HANDSHAKE_LOGIN, [STRING_TYPE], ( obj$1 = {}, obj$1[ENUM_KEY] = AVAILABLE_METHODS, obj$1 )); -configCheckMap.useJwt = createConfig$1(true, [BOOLEAN_TYPE, STRING_TYPE]); -configCheckMap.authStrKey = createConfig$1(null, [STRING_TYPE]); +configCheckMap[CSRF_PROP_KEY] = createConfig$1(CSRF_HEADER_KEY, [STRING_TYPE]); configCheckMap[SUSPEND_EVENT_PROP_KEY] = createConfig$1(false, [BOOLEAN_TYPE]); // socket client var socketCheckMap = {}; -socketCheckMap[SOCKET_TYPE_PROP_KEY] = createConfig$1(null, [STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = SOCKET_TYPE_CLIENT_ALIAS, obj$2 )); +socketCheckMap[SOCKET_TYPE_PROP_KEY] = createConfig$1(null, [STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = SOCKET_TYPE_CLIENT_ALIAS, obj$1 )); var wsCoreCheckMap = Object.assign(configCheckMap, socketCheckMap); // constant props -var wsCoreConstProps = { - log: null, - // contract: null, - eventEmitter: null, - // we unify the two different client into one now - // only expect different parameter - nspClient: null, - nspAuthClient: null, - // contructed path - wssPath: '', - // for generate the namespaces - publicNamespace: PUBLIC_KEY, - privateNamespace: PRIVATE_KEY -}; +var wsCoreConstProps = {}; +wsCoreConstProps[USE_JWT_PROP_KEY] = true; +wsCoreConstProps.log = null; +wsCoreConstProps.eventEmitter = null; +wsCoreConstProps.nspClient = null; +wsCoreConstProps.nspAuthClient = null; +wsCoreConstProps.wssPath = ''; +wsCoreConstProps.publicNamespace = PUBLIC_KEY; +wsCoreConstProps.privateNamespace = PRIVATE_KEY; // create options @@ -8123,6 +7981,7 @@ function checkConfiguration(config, defaultOptions, constProps) { * @return {promise} opts all done */ function postCheckInjectOpts(opts) { + return Promise.resolve(opts) .then(function (opts) { if (!opts.hostname) { @@ -8130,12 +7989,13 @@ function postCheckInjectOpts(opts) { } // @TODO the contract now will supply the namespace information // and we need to use that to group the namespace call + opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType); // get the log function here opts.log = getLogFn(opts); opts.eventEmitter = getEventEmitter(opts); - + return opts }) } @@ -8156,9 +8016,7 @@ function createRequiredParams(opts) { // @TODO here we are going to add suspend event to the namespace related methods var log = opts.log; var namespaces = nspMap.namespaces; - log("namespaces", namespaces); - // next we loop the namespace and suspend all the events prefix with namespace if (opts[SUSPEND_EVENT_PROP_KEY] === true) { // we create this as a function then we can call it again @@ -8239,51 +8097,6 @@ function wsClientCore(socketClientListener, configCheckMap, constProps) { } } -// this is getting too confusing -// therefore we move it back to the framework specific - -/** - * wrapper method to create a nsp without login - * @param {string|boolean} namespace namespace url could be false - * @param {object} opts configuration - * @return {object} ws client instance - */ -function createNspClient(namespace, opts) { - var hostname = opts.hostname; - var wssPath = opts.wssPath; - var wsOptions = opts.wsOptions; - var nspClient = opts.nspClient; - var log = opts.log; - var url = namespace ? [hostname, namespace].join('/') : wssPath; - log("createNspClient --> ", url); - - return nspClient(url, wsOptions) -} - -/** - * wrapper method to create a nsp with token auth - * @param {string} namespace namespace url - * @param {object} opts configuration - * @return {object} ws client instance - */ -function createNspAuthClient(namespace, opts) { - var hostname = opts.hostname; - var wssPath = opts.wssPath; - var token = opts.token; - var wsOptions = opts.wsOptions; - var nspAuthClient = opts.nspAuthClient; - var log = opts.log; - var url = namespace ? [hostname, namespace].join('/') : wssPath; - - log("createNspAuthClient -->", url); - - if (token && typeof token !== 'string') { - throw new Error(("Expect token to be string, but got " + token)) - } - - return nspAuthClient(url, token, wsOptions) -} - // this use by client-event-handler /** @@ -8428,10 +8241,214 @@ function namespaceEventListener(bindSocketEventListener, nsps) { } } +/* +This two client is the final one that gets call +all it does is to create the url that connect to +and actually trigger the connection and return the socket +therefore they are as generic as it can be +*/ + +/** + * wrapper method to create a nsp without login + * @param {string|boolean} namespace namespace url could be false + * @param {object} opts configuration + * @return {object} ws client instance + */ +function createNspClient(namespace, opts) { + var hostname = opts.hostname; + var wssPath = opts.wssPath; + var nspClient = opts.nspClient; + var log = opts.log; + var url = namespace ? [hostname, namespace].join('/') : wssPath; + log("createNspClient --> ", url); + + return nspClient(url, opts) +} + +/** + * wrapper method to create a nsp with token auth + * @param {string} namespace namespace url + * @param {object} opts configuration + * @return {object} ws client instance + */ +function createNspAuthClient(namespace, opts) { + var hostname = opts.hostname; + var wssPath = opts.wssPath; + var token = opts.token; + var nspAuthClient = opts.nspAuthClient; + var log = opts.log; + var url = namespace ? [hostname, namespace].join('/') : wssPath; + + log("createNspAuthClient -->", url); + + if (token && typeof token !== 'string') { + throw new Error(("Expect token to be string, but got " + token)) + } + // now we need to get an extra options for framework specific method, which is not great + // instead we just pass the entrie opts to the authClient + + return nspAuthClient(url, opts, token) +} + +// same with the invalid-token-error + +/* +function InvalidCharacterError(message) { + this.message = message; +} + +InvalidCharacterError.prototype = new Error(); +InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + +*/ + +var InvalidCharacterError = /*@__PURE__*/(function (Error) { + function InvalidCharacterError(message) { + this.message = message; + } + + if ( Error ) InvalidCharacterError.__proto__ = Error; + InvalidCharacterError.prototype = Object.create( Error && Error.prototype ); + InvalidCharacterError.prototype.constructor = InvalidCharacterError; + + var prototypeAccessors = { name: { configurable: true } }; + + prototypeAccessors.name.get = function () { + return 'InvalidCharacterError' + }; + + Object.defineProperties( InvalidCharacterError.prototype, prototypeAccessors ); + + return InvalidCharacterError; +}(Error)); + +/** + * The code was extracted from: + * https://github.com/davidchambers/Base64.js + */ +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +/** + * Polyfill the non ASCII code + * @param {*} input + * @return {*} usable output + */ +function atob(input) { + var str = String(input).replace(/=+$/, ''); + if (str.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.") + } + for ( + // initialize result and counters + var bc = 0, bs = (void 0), buffer = (void 0), idx = 0, output$1 = ''; + // get next character + buffer = str.charAt(idx++); + // character found in table? initialize bit storage and add its ascii value; + ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, + // and if not first of each 4 characters, + // convert the first 8 bits to one ascii character + bc++ % 4) ? output$1 += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 + ) { + // try to find character in table (0-63, not found => -1) + buffer = chars.indexOf(buffer); + } + return output +} + +// polyfill the window object +try { + typeof window !== 'undefined' && window.atob && window.atob.bind(window) || atob; +} catch(e) {} + +var obj$2, obj$1$1, obj$2$1, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; + +var appProps = { + algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), + expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'exp', obj$2[OPTIONAL_KEY] = true, obj$2 )), + notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1$1 = {}, obj$1$1[ALIAS_KEY] = 'nbf', obj$1$1[OPTIONAL_KEY] = true, obj$1$1 )), + audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2$1 = {}, obj$2$1[ALIAS_KEY] = 'iss', obj$2$1[OPTIONAL_KEY] = true, obj$2$1 )), + subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), + issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), + noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), + header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), + keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), + mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) +}; + +// this method is re-use in several clients +// therefore it's better to share here +var ref = require('jsonql-constants'); +var TOKEN_PARAM_NAME = ref.TOKEN_PARAM_NAME; +var AUTH_HEADER = ref.AUTH_HEADER; +var TOKEN_DELIVER_LOCATION_PROP_KEY = ref.TOKEN_DELIVER_LOCATION_PROP_KEY; +var TOKEN_IN_URL = ref.TOKEN_IN_URL; +var TOKEN_IN_HEADER = ref.TOKEN_IN_HEADER; +var WS_OPT_PROP_KEY$1 = ref.WS_OPT_PROP_KEY; +/** + * extract the new options for authorization + * @param {*} opts configuration + * @return {string} the header option + */ +function extractConfig(opts) { + // we don't really need to do any validation here + // because the opts should be clean before calling here + return opts[TOKEN_DELIVER_LOCATION_PROP_KEY] || TOKEN_IN_URL +} + +/** + * prepare the url and options to the WebSocket + * @param {*} url + * @param {*} config + * @param {*} [token = false] + * @return {object} with url and opts key + */ +function prepareConnectConfig(url, config, token) { + var obj; + + if ( token === void 0 ) token = false; + if (token === false) { + return { + url: url, + opts: config[WS_OPT_PROP_KEY$1] || {} + } + } + + var tokenOpt = extractConfig(config); + switch (tokenOpt) { + case TOKEN_IN_URL: + return { + url: (url + "?" + TOKEN_PARAM_NAME + "=" + token), + opts: config[WS_OPT_PROP_KEY$1] || {} + } + case TOKEN_IN_HEADER: + return { + url: url, + opts: Object.assign({}, config[WS_OPT_PROP_KEY$1] || {}, { + headers: ( obj = {}, obj[AUTH_HEADER] = token, obj ) + }) + } + } +} + /* base.js */ var ERROR_KEY$1 = 'error'; var QUERY_ARG_NAME$1 = 'args'; var TIMESTAMP_PARAM_NAME$1 = 'TS'; + + /* prop.js */ + +// this is all the key name for the config check map +// all subfix with prop_key + +var TYPE_KEY$1 = 'type'; +var OPTIONAL_KEY$1 = 'optional'; +var ENUM_KEY$1 = 'enumv'; // need to change this because enum is a reserved word +var ARGS_KEY$1 = 'args'; +var CHECKER_KEY$1 = 'checker'; +var ALIAS_KEY$1 = 'alias'; +var ENABLE_AUTH_PROP_KEY$1 = 'enableAuth'; +// we could pass the token in the header instead when init the WebSocket +var TOKEN_DELIVER_LOCATION_PROP_KEY$1 = 'tokenDeliverLocation'; /* socket.js */ var LOGIN_EVENT_NAME$1 = '__login__'; // at the moment we only have __logout__ regardless enableAuth is enable // this is incorrect, because logout suppose to come after login @@ -8442,9 +8459,9 @@ var LOGIN_EVENT_NAME$1 = '__login__'; var CONNECT_EVENT_NAME$1 = '__connect__'; var DISCONNECT_EVENT_NAME$1 = '__disconnect__'; // for ws servers -var WS_REPLY_TYPE$1 = '__reply__'; -var WS_EVT_NAME$1 = '__event__'; -var WS_DATA_NAME$1 = '__data__'; +var WS_REPLY_TYPE = '__reply__'; +var WS_EVT_NAME = '__event__'; +var WS_DATA_NAME = '__data__'; // for ws client, 1.9.3 breaking change to name them as FN instead of PROP var ON_MESSAGE_FN_NAME$1 = 'onMessage'; @@ -8457,165 +8474,74 @@ var ON_LOGIN_FN_NAME$1 = 'onLogin'; // new @1.8.6 var EMIT_REPLY_TYPE$1 = 'emit_reply'; var ACKNOWLEDGE_REPLY_TYPE = 'emit_acknowledge'; var JS_WS_NAME = 'ws'; -var TOKEN_PARAM_NAME = 'token'; var NSP_AUTH_CLIENT = 'nspAuthClient'; var NSP_CLIENT = 'nspClient'; -// jsonql-ws-core takes over the check configuration -// constant props -var wsClientConstProps = { - version: 'version: 1.2.0 module: cjs', // will get replace - serverType: JS_WS_NAME -}; +// this is the value for TOKEN_DELIVER_LOCATION_PROP_KEY +var TOKEN_IN_HEADER$1 = 'header'; +var TOKEN_IN_URL$1 = 'url'; +var STRING_TYPE$1 = 'string'; +var BOOLEAN_TYPE$1 = 'boolean'; -// pass the different type of ws to generate the client +var NUMBER_TYPE$1 = 'number'; -/** - * Group the ping and get respond create new client in one - * @param {object} ws - * @param {object} WebSocket - * @param {string} url - * @param {function} resolver - * @param {function} rejecter - * @param {boolean} auth client or not - * @return {promise} resolve the confirm client - */ -function initPingAction(ws, WebSocket, url, resolver, rejecter, wsOptions) { - // @TODO how to we id this client can issue a CSRF - // by origin? - ws.onopen = function onOpenCallback() { - ws.send(createInitPing()); - }; - - ws.onmessage = function onMessageCallback(payload) { - try { - var header = extractPingResult(payload.data); - // @NOTE the break down test in ws-client-core show no problems - // the problem was cause by malform nspInfo that time? - setTimeout(function () { // delay or not show no different but just on the safe side - ws.terminate(); - }, 50); - var newWs = new WebSocket(url, Object.assign(wsOptions, header)); - resolver(newWs); - } catch(e) { - rejecter(e); - } - }; - - ws.onerror = function onErrorCallback(err) { - rejecter(err); - }; +/** Detect free variable `global` from Node.js. */ +var freeGlobal$1 = typeof global$1 == 'object' && global$1 && global$1.Object === Object && global$1; - return ws // just return it -} +/** Detect free variable `self`. */ +var freeSelf$1 = typeof self == 'object' && self && self.Object === Object && self; -/** - * less duplicated code the better - * @param {object} WebSocket - * @param {string} url formatted url - * @param {object} options or not - * @return {promise} resolve the actual verified client - */ -function asyncConnect(WebSocket, url, options) { - - return new Promise(function (resolver, rejecter) { - var unconfirmClient = new WebSocket(url, options); - - return initPingAction(unconfirmClient, WebSocket, url, resolver, rejecter, options) - }) -} +/** Used as a reference to the global object. */ +var root$1 = freeGlobal$1 || freeSelf$1 || Function('return this')(); +/** Built-in value references. */ +var Symbol$1 = root$1.Symbol; /** - * The bug was in the wsOptions where ws don't need it but socket.io do - * therefore the object was pass as second parameter! - * @NOTE here we only return a method to create the client, it might not get call - * @param {object} WebSocket the client or node version of ws - * @param {object} opts this is a breaking change we will init the client twice - * @param {boolean} [auth = false] if it's auth then 3 param or just one - * @return {function} the client method to connect to the ws socket server + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. */ -function initWebSocketClient(WebSocket, opts, auth) { - if ( auth === void 0 ) auth = false; - - var log = opts.log; - if (auth === false) { - /** - * Create a non-protected client - * @param {string} url - * @param {object} [wsOptions={}] - * @return {promise} resolve to the confirmed client - */ - return function createWsClient(url, wsOptions) { - if ( wsOptions === void 0 ) wsOptions = {}; - - var _url = fixWss(url); - log(("nspClient: \n" + _url + "\n"), wsOptions); - - return asyncConnect(WebSocket, _url, wsOptions) - } - } - - /** - * Create a client with auth token - * @param {string} url start with ws:// @TODO check this? - * @param {string} token the jwt token - * @param {object} [wsOptions={}] extra options pass to the WebSocket object - * @return {object} ws instance - */ - return function createWsAuthClient(url, token, wsOptions) { - if ( wsOptions === void 0 ) wsOptions = {}; - - var ws_url = fixWss(url); - // console.log('what happen here?', url, ws_url, token) - var _url = token && typeof token === 'string' ? (ws_url + "?" + TOKEN_PARAM_NAME + "=" + token) : ws_url; - log(("nspAuthClient: \n" + _url + "\n"), wsOptions); +function arrayMap$1(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); - return asyncConnect(WebSocket, _url, wsOptions) + while (++index < length) { + result[index] = iteratee(array[index], index, array); } + return result; } -// @BUG when call disconnected - /** - * when we received a login event - * from the http-client or the standalone login call - * we received a token here --> update the opts then trigger - * the CONNECT_EVENT_NAME again - * @param {object} opts configurations - * @param {object} nspMap contain all the required info - * @param {object} ee event emitter - * @return {void} + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false */ -function loginEventListener(opts, nspMap, ee) { - var log = opts.log; - var namespaces = nspMap.namespaces; - - log("[4] loginEventHandler"); - - ee.$only(LOGIN_EVENT_NAME$1, function loginEventHandlerCallback(tokenFromLoginAction) { - - log('createClient LOGIN_EVENT_NAME $only handler'); - // clear out all the event binding - clearMainEmitEvt(ee, namespaces); - // reload the nsp and rebind all the events - opts.token = tokenFromLoginAction; - ee.$trigger(CONNECT_EVENT_NAME$1, [opts, ee]); // don't need to pass the nspMap - }); -} - -/** Detect free variable `global` from Node.js. */ -var freeGlobal$1 = typeof global$1 == 'object' && global$1 && global$1.Object === Object && global$1; - -/** Detect free variable `self`. */ -var freeSelf$1 = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root$1 = freeGlobal$1 || freeSelf$1 || Function('return this')(); - -/** Built-in value references. */ -var Symbol$1 = root$1.Symbol; +var isArray$1 = Array.isArray; /** Used for built-in method references. */ var objectProto$f = Object.prototype; @@ -8704,23 +8630,6 @@ function baseGetTag$1(value) { : objectToString$1(value); } -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg$1(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} - -/** Built-in value references. */ -var getPrototype$1 = overArg$1(Object.getPrototypeOf, Object); - /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". @@ -8750,61 +8659,701 @@ function isObjectLike$1(value) { } /** `Object#toString` result references. */ -var objectTag$4 = '[object Object]'; +var symbolTag$2 = '[object Symbol]'; -/** Used for built-in method references. */ -var funcProto$3 = Function.prototype, - objectProto$h = Object.prototype; +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol$1(value) { + return typeof value == 'symbol' || + (isObjectLike$1(value) && baseGetTag$1(value) == symbolTag$2); +} + +/** Used as references for various `Number` constants. */ +var INFINITY$2 = 1 / 0; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto$2 = Symbol$1 ? Symbol$1.prototype : undefined, + symbolToString$1 = symbolProto$2 ? symbolProto$2.toString : undefined; + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString$1(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray$1(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap$1(value, baseToString$1) + ''; + } + if (isSymbol$1(value)) { + return symbolToString$1 ? symbolToString$1.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$2) ? '-0' : result; +} + +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice$1(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; +} + +/** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ +function castSlice$1(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice$1(array, start, end); +} + +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex$1(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN$1(value) { + return value !== value; +} + +/** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictIndexOf$1(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf$1(array, value, fromIndex) { + return value === value + ? strictIndexOf$1(array, value, fromIndex) + : baseFindIndex$1(array, baseIsNaN$1, fromIndex); +} + +/** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ +function charsEndIndex$1(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf$1(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +/** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ +function charsStartIndex$1(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf$1(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +/** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function asciiToArray$1(string) { + return string.split(''); +} + +/** Used to compose unicode character classes. */ +var rsAstralRange$2 = '\\ud800-\\udfff', + rsComboMarksRange$2 = '\\u0300-\\u036f', + reComboHalfMarksRange$2 = '\\ufe20-\\ufe2f', + rsComboSymbolsRange$2 = '\\u20d0-\\u20ff', + rsComboRange$2 = rsComboMarksRange$2 + reComboHalfMarksRange$2 + rsComboSymbolsRange$2, + rsVarRange$2 = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsZWJ$2 = '\\u200d'; + +/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ +var reHasUnicode$1 = RegExp('[' + rsZWJ$2 + rsAstralRange$2 + rsComboRange$2 + rsVarRange$2 + ']'); + +/** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ +function hasUnicode$1(string) { + return reHasUnicode$1.test(string); +} + +/** Used to compose unicode character classes. */ +var rsAstralRange$3 = '\\ud800-\\udfff', + rsComboMarksRange$3 = '\\u0300-\\u036f', + reComboHalfMarksRange$3 = '\\ufe20-\\ufe2f', + rsComboSymbolsRange$3 = '\\u20d0-\\u20ff', + rsComboRange$3 = rsComboMarksRange$3 + reComboHalfMarksRange$3 + rsComboSymbolsRange$3, + rsVarRange$3 = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsAstral$1 = '[' + rsAstralRange$3 + ']', + rsCombo$1 = '[' + rsComboRange$3 + ']', + rsFitz$1 = '\\ud83c[\\udffb-\\udfff]', + rsModifier$1 = '(?:' + rsCombo$1 + '|' + rsFitz$1 + ')', + rsNonAstral$1 = '[^' + rsAstralRange$3 + ']', + rsRegional$1 = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair$1 = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsZWJ$3 = '\\u200d'; + +/** Used to compose unicode regexes. */ +var reOptMod$1 = rsModifier$1 + '?', + rsOptVar$1 = '[' + rsVarRange$3 + ']?', + rsOptJoin$1 = '(?:' + rsZWJ$3 + '(?:' + [rsNonAstral$1, rsRegional$1, rsSurrPair$1].join('|') + ')' + rsOptVar$1 + reOptMod$1 + ')*', + rsSeq$1 = rsOptVar$1 + reOptMod$1 + rsOptJoin$1, + rsSymbol$1 = '(?:' + [rsNonAstral$1 + rsCombo$1 + '?', rsCombo$1, rsRegional$1, rsSurrPair$1, rsAstral$1].join('|') + ')'; + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode$1 = RegExp(rsFitz$1 + '(?=' + rsFitz$1 + ')|' + rsSymbol$1 + rsSeq$1, 'g'); + +/** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function unicodeToArray$1(string) { + return string.match(reUnicode$1) || []; +} + +/** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function stringToArray$1(string) { + return hasUnicode$1(string) + ? unicodeToArray$1(string) + : asciiToArray$1(string); +} + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString$1(value) { + return value == null ? '' : baseToString$1(value); +} + +/** Used to match leading and trailing whitespace. */ +var reTrim$1 = /^\s+|\s+$/g; + +/** + * Removes leading and trailing whitespace or specified characters from `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to trim. + * @param {string} [chars=whitespace] The characters to trim. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the trimmed string. + * @example + * + * _.trim(' abc '); + * // => 'abc' + * + * _.trim('-_-abc-_-', '_-'); + * // => 'abc' + * + * _.map([' foo ', ' bar '], _.trim); + * // => ['foo', 'bar'] + */ +function trim$1(string, chars, guard) { + string = toString$1(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrim$1, ''); + } + if (!string || !(chars = baseToString$1(chars))) { + return string; + } + var strSymbols = stringToArray$1(string), + chrSymbols = stringToArray$1(chars), + start = charsStartIndex$1(strSymbols, chrSymbols), + end = charsEndIndex$1(strSymbols, chrSymbols) + 1; + + return castSlice$1(strSymbols, start, end).join(''); +} + +/** `Object#toString` result references. */ +var numberTag$3 = '[object Number]'; + +/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber$1(value) { + return typeof value == 'number' || + (isObjectLike$1(value) && baseGetTag$1(value) == numberTag$3); +} + +/** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ +function isNaN$2(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber$1(value) && value != +value; +} + +/** `Object#toString` result references. */ +var stringTag$3 = '[object String]'; + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString$3(value) { + return typeof value == 'string' || + (!isArray$1(value) && isObjectLike$1(value) && baseGetTag$1(value) == stringTag$3); +} + +// validator numbers +/** + * @2015-05-04 found a problem if the value is a number like string + * it will pass, so add a chck if it's string before we pass to next + * @param {number} value expected value + * @return {boolean} true if OK + */ +var checkIsNumber$1 = function(value) { + return isString$3(value) ? false : !isNaN$2( parseFloat(value) ) +}; + +// validate string type +/** + * @param {string} value expected value + * @return {boolean} true if OK + */ +var checkIsString$1 = function(value) { + return (trim$1(value) !== '') ? isString$3(value) : false +}; + +// check for boolean + +/** + * @param {boolean} value expected + * @return {boolean} true if OK + */ +var checkIsBoolean$1 = function(value) { + return value !== null && value !== undefined && typeof value === 'boolean' +}; + +// validate any thing only check if there is something + +/** + * @param {*} value the value + * @param {boolean} [checkNull=true] strict check if there is null value + * @return {boolean} true is OK + */ +var checkIsAny$1 = function(value, checkNull) { + if ( checkNull === void 0 ) checkNull = true; + + if (value !== undefined && value !== '' && trim$1(value) !== '') { + if (checkNull === false || (checkNull === true && value !== null)) { + return true; + } + } + return false; +}; + +// primitive types + +/** + * this is a wrapper method to call different one based on their type + * @param {string} type to check + * @return {function} a function to handle the type + */ +var combineFn$1 = function(type) { + switch (type) { + case NUMBER_TYPE$1: + return checkIsNumber$1 + case STRING_TYPE$1: + return checkIsString$1 + case BOOLEAN_TYPE$1: + return checkIsBoolean$1 + default: + return checkIsAny$1 + } +}; + +// validate array type + +/** + * @param {array} value expected + * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well + * @return {boolean} true if OK + */ +var checkIsArray$1 = function(value, type) { + if ( type === void 0 ) type=''; + + if (isArray$1(value)) { + if (type === '' || trim$1(type)==='') { + return true; + } + // we test it in reverse + // @TODO if the type is an array (OR) then what? + // we need to take into account this could be an array + var c = value.filter(function (v) { return !combineFn$1(type)(v); }); + return !(c.length > 0) + } + return false +}; + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg$1(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** Built-in value references. */ +var getPrototype$1 = overArg$1(Object.getPrototypeOf, Object); + +/** `Object#toString` result references. */ +var objectTag$4 = '[object Object]'; + +/** Used for built-in method references. */ +var funcProto$3 = Function.prototype, + objectProto$h = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString$3 = funcProto$3.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty$d = objectProto$h.hasOwnProperty; + +/** Used to infer the `Object` constructor. */ +var objectCtorString$1 = funcToString$3.call(Object); + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject$1(value) { + if (!isObjectLike$1(value) || baseGetTag$1(value) != objectTag$4) { + return false; + } + var proto = getPrototype$1(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty$d.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString$3.call(Ctor) == objectCtorString$1; +} + +// custom validation error class +// when validaton failed +var JsonqlValidationError$1 = /*@__PURE__*/(function (Error) { + function JsonqlValidationError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlValidationError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlValidationError); + } + } + + if ( Error ) JsonqlValidationError.__proto__ = Error; + JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); + JsonqlValidationError.prototype.constructor = JsonqlValidationError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlValidationError' + }; + + Object.defineProperties( JsonqlValidationError, staticAccessors ); + + return JsonqlValidationError; +}(Error)); + +var NO_STATUS_CODE$1 = -1; + +/** + * This is a custom error to throw whenever a error happen inside the jsonql + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ +var JsonqlError$2 = /*@__PURE__*/(function (Error) { + function JsonqlError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlError); + // this.detail = this.stack; + } + } + + if ( Error ) JsonqlError.__proto__ = Error; + JsonqlError.prototype = Object.create( Error && Error.prototype ); + JsonqlError.prototype.constructor = JsonqlError; -/** Used to resolve the decompiled source of functions. */ -var funcToString$3 = funcProto$3.toString; + var staticAccessors = { name: { configurable: true },statusCode: { configurable: true } }; -/** Used to check objects for own properties. */ -var hasOwnProperty$d = objectProto$h.hasOwnProperty; + staticAccessors.name.get = function () { + return 'JsonqlError' + }; -/** Used to infer the `Object` constructor. */ -var objectCtorString$1 = funcToString$3.call(Object); + staticAccessors.statusCode.get = function () { + return NO_STATUS_CODE$1 + }; -/** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ -function isPlainObject$1(value) { - if (!isObjectLike$1(value) || baseGetTag$1(value) != objectTag$4) { - return false; - } - var proto = getPrototype$1(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty$d.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString$3.call(Ctor) == objectCtorString$1; -} + Object.defineProperties( JsonqlError, staticAccessors ); + + return JsonqlError; +}(Error)); /** * Removes all key-value entries from the list cache. @@ -9780,31 +10329,6 @@ var isArguments$1 = baseIsArguments$1(function() { return arguments; }()) ? base !propertyIsEnumerable$2.call(value, 'callee'); }; -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray$1 = Array.isArray; - /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$2 = 9007199254740991; @@ -9956,11 +10480,11 @@ var argsTag$4 = '[object Arguments]', errorTag$2 = '[object Error]', funcTag$3 = '[object Function]', mapTag$3 = '[object Map]', - numberTag$3 = '[object Number]', + numberTag$4 = '[object Number]', objectTag$5 = '[object Object]', regexpTag$2 = '[object RegExp]', setTag$3 = '[object Set]', - stringTag$3 = '[object String]', + stringTag$4 = '[object String]', weakMapTag$2 = '[object WeakMap]'; var arrayBufferTag$2 = '[object ArrayBuffer]', @@ -9986,9 +10510,9 @@ typedArrayTags$1[argsTag$4] = typedArrayTags$1[arrayTag$2] = typedArrayTags$1[arrayBufferTag$2] = typedArrayTags$1[boolTag$2] = typedArrayTags$1[dataViewTag$3] = typedArrayTags$1[dateTag$2] = typedArrayTags$1[errorTag$2] = typedArrayTags$1[funcTag$3] = -typedArrayTags$1[mapTag$3] = typedArrayTags$1[numberTag$3] = +typedArrayTags$1[mapTag$3] = typedArrayTags$1[numberTag$4] = typedArrayTags$1[objectTag$5] = typedArrayTags$1[regexpTag$2] = -typedArrayTags$1[setTag$3] = typedArrayTags$1[stringTag$3] = +typedArrayTags$1[setTag$3] = typedArrayTags$1[stringTag$4] = typedArrayTags$1[weakMapTag$2] = false; /** @@ -10615,97 +11139,291 @@ function baseRest$1(func, start) { } /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall$1(value, index, object) { + if (!isObject$1(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike$2(object) && isIndex$1(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq$1(object[index], value); + } + return false; +} + +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner$1(assigner) { + return baseRest$1(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall$1(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} + +/** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ +var merge$1 = createAssigner$1(function(object, source, srcIndex) { + baseMerge$1(object, source, srcIndex); +}); + +// create function to construct the config entry so we don't need to keep building object +// import checkIsBoolean from '../boolean' +// import debug from 'debug'; +// const debugFn = debug('jsonql-params-validator:construct-config'); +/** + * @param {*} args value + * @param {string} type for value + * @param {boolean} [optional=false] + * @param {boolean|array} [enumv=false] + * @param {boolean|function} [checker=false] + * @return {object} config entry + */ +function constructConfig$1(args, type, optional, enumv, checker, alias) { + if ( optional === void 0 ) optional=false; + if ( enumv === void 0 ) enumv=false; + if ( checker === void 0 ) checker=false; + if ( alias === void 0 ) alias=false; + + var base = {}; + base[ARGS_KEY$1] = args; + base[TYPE_KEY$1] = type; + if (optional === true) { + base[OPTIONAL_KEY$1] = true; + } + if (checkIsArray$1(enumv)) { + base[ENUM_KEY$1] = enumv; + } + if (isFunction$1(checker)) { + base[CHECKER_KEY$1] = checker; + } + if (isString$3(alias)) { + base[ALIAS_KEY$1] = alias; + } + return base +} + +// export also create wrapper methods + +/** + * This has a different interface + * @param {*} value to supply + * @param {string|array} type for checking + * @param {object} params to map against the config check + * @param {array} params.enumv NOT enum + * @param {boolean} params.optional false then nothing + * @param {function} params.checker need more work on this one later + * @param {string} params.alias mostly for cmd + */ +var createConfig$2 = function (value, type, params) { + if ( params === void 0 ) params = {}; + + // Note the enumv not ENUM + // const { enumv, optional, checker, alias } = params; + // let args = [value, type, optional, enumv, checker, alias]; + var o = params[OPTIONAL_KEY$1]; + var e = params[ENUM_KEY$1]; + var c = params[CHECKER_KEY$1]; + var a = params[ALIAS_KEY$1]; + return constructConfig$1.apply(null, [value, type, o, e, c, a]) +}; + +// export + +var createConfig$3 = createConfig$2; + +var obj$9; + +var AVAILABLE_PLACES = [ + TOKEN_IN_URL$1, + TOKEN_IN_HEADER$1 +]; + +// constant props +var wsClientConstProps = { + version: 'version: 1.2.0 module: cjs', // will get replace + serverType: JS_WS_NAME +}; + +var wsClientCheckMap = {}; +wsClientCheckMap[TOKEN_DELIVER_LOCATION_PROP_KEY$1] = createConfig$3(TOKEN_IN_URL$1, [STRING_TYPE$1], ( obj$9 = {}, obj$9[ENUM_KEY$1] = AVAILABLE_PLACES, obj$9 )); + +// pass the different type of ws to generate the client + +/** + * Group the ping and get respond create new client in one + * @param {object} ws + * @param {object} WebSocket + * @param {string} url + * @param {function} resolver + * @param {function} rejecter + * @param {boolean} auth client or not + * @return {promise} resolve the confirm client + */ +function initPingAction(ws, WebSocket, url, wsOptions, resolver, rejecter) { + + return resolver(ws) +} + +/** + * less duplicated code the better + * @param {object} WebSocket + * @param {string} url formatted url + * @param {object} options or not + * @return {promise} resolve the actual verified client + */ +function asyncConnect(WebSocket, url, options) { + + return new Promise(function (resolver, rejecter) { + var unconfirmClient = new WebSocket(url, options); + + return initPingAction(unconfirmClient, WebSocket, url, options, resolver) + }) +} + +/** + * The bug was in the wsOptions where ws don't need it but socket.io do + * therefore the object was pass as second parameter! + * @NOTE here we only return a method to create the client, it might not get call + * @param {object} WebSocket the client or node version of ws + * @param {object} opts this is a breaking change we will init the client twice + * @param {boolean} [auth = false] if it's auth then 3 param or just one + * @return {function} the client method to connect to the ws socket server */ -function isIterateeCall$1(value, index, object) { - if (!isObject$1(object)) { - return false; +function setupWebsocketClientFn(WebSocket, auth) { + if ( auth === void 0 ) auth = false; + + + if (auth === false) { + /** + * Create a non-protected client + * @param {string} uri already constructed url + * @param {object} config from the ws-client-core this will be wsOptions taken out from opts + * @return {promise} resolve to the confirmed client + */ + return function createWsClient(uri, config) { + // const { log } = config + var ref = prepareConnectConfig(uri, config, false); + var url = ref.url; + var opts = ref.opts; + + // log(`createWsClient url: ${url} with opts:`, opts) + + return asyncConnect(WebSocket, url, opts) + } } - var type = typeof index; - if (type == 'number' - ? (isArrayLike$2(object) && isIndex$1(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq$1(object[index], value); + + /** + * Create a client with auth token + * @param {string} uri start with ws:// @TODO check this? + * @param {object} config this is the full configuration because we need something from it + * @param {string} token the jwt token + * @return {object} ws instance + */ + return function createWsAuthClient(uri, config, token) { + // const { log } = config + var ref = prepareConnectConfig(uri, config, token); + var url = ref.url; + var opts = ref.opts; + + // log(`createWsAuthClient url: ${url} with opts:`, opts) + + return asyncConnect(WebSocket, url, opts) } - return false; } +// @BUG when call disconnected + /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. + * when we received a login event + * from the http-client or the standalone login call + * we received a token here --> update the opts then trigger + * the CONNECT_EVENT_NAME again + * @param {object} opts configurations + * @param {object} nspMap contain all the required info + * @param {object} ee event emitter + * @return {void} */ -function createAssigner$1(assigner) { - return baseRest$1(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; +function loginEventListener(opts, nspMap, ee) { + var log = opts.log; + var namespaces = nspMap.namespaces; - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; + log("[4] loginEventHandler"); - if (guard && isIterateeCall$1(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; + ee.$only(LOGIN_EVENT_NAME$1, function loginEventHandlerCallback(tokenFromLoginAction) { + + log('createClient LOGIN_EVENT_NAME $only handler'); + // clear out all the event binding + clearMainEmitEvt(ee, namespaces); + // reload the nsp and rebind all the events + opts.token = tokenFromLoginAction; + ee.$trigger(CONNECT_EVENT_NAME$1, [opts, ee]); // don't need to pass the nspMap }); } -/** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ -var merge$1 = createAssigner$1(function(object, source, srcIndex) { - baseMerge$1(object, source, srcIndex); -}); - // break it out on its own because /** @@ -10800,7 +11518,7 @@ var inArray$3 = function (arr, value) { return !!arr.filter(function (a) { retur * @param {boolean} [t=true] or throw * @return {*} json object on success */ -var parseJson$1 = function(n, t) { +var parseJson = function(n, t) { if ( t === void 0 ) t=true; try { @@ -10845,11 +11563,11 @@ var createEvt$1 = function () { * @param {*} n input * @return {object} correct JSON object */ -var toJson$1 = function (n) { +var toJson = function (n) { if (typeof n === 'string') { - return parseJson$1(n) + return parseJson(n) } - return parseJson$1(JSON.stringify(n)) + return parseJson(JSON.stringify(n)) }; /** @@ -10858,85 +11576,6 @@ var toJson$1 = function (n) { */ var nil$1 = function () { return false; }; -var NO_STATUS_CODE$1 = -1; - -// custom validation error class -// when validaton failed -var JsonqlValidationError$1 = /*@__PURE__*/(function (Error) { - function JsonqlValidationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlValidationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlValidationError); - } - } - - if ( Error ) JsonqlValidationError.__proto__ = Error; - JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); - JsonqlValidationError.prototype.constructor = JsonqlValidationError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlValidationError' - }; - - Object.defineProperties( JsonqlValidationError, staticAccessors ); - - return JsonqlValidationError; -}(Error)); - -/** - * This is a custom error to throw whenever a error happen inside the jsonql - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ -var JsonqlError$2 = /*@__PURE__*/(function (Error) { - function JsonqlError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlError); - // this.detail = this.stack; - } - } - - if ( Error ) JsonqlError.__proto__ = Error; - JsonqlError.prototype = Object.create( Error && Error.prototype ); - JsonqlError.prototype.constructor = JsonqlError; - - var staticAccessors = { name: { configurable: true },statusCode: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlError' - }; - - staticAccessors.statusCode.get = function () { - return NO_STATUS_CODE$1 - }; - - Object.defineProperties( JsonqlError, staticAccessors ); - - return JsonqlError; -}(Error)); - /** * @param {boolean} sec return in second or not * @return {number} timestamp @@ -10948,31 +11587,6 @@ var timestamp$1 = function (sec) { return sec ? Math.floor( time / 1000 ) : time }; -/** `Object#toString` result references. */ -var stringTag$4 = '[object String]'; - -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString$3(value) { - return typeof value == 'string' || - (!isArray$1(value) && isObjectLike$1(value) && baseGetTag$1(value) == stringTag$4); -} - // ported from jsonql-params-validator /** @@ -11038,23 +11652,23 @@ function createQueryStr$1(resolverName, args, jsonp) { // There are the socket related methods ported back from -var PAYLOAD_NOT_DECODED_ERR$1 = 'payload can not decoded'; -var WS_KEYS$1 = [ - WS_REPLY_TYPE$1, - WS_EVT_NAME$1, - WS_DATA_NAME$1 +var PAYLOAD_NOT_DECODED_ERR = 'payload can not decoded'; +var WS_KEYS = [ + WS_REPLY_TYPE, + WS_EVT_NAME, + WS_DATA_NAME ]; /** * @param {string|object} payload should be string when reply but could be transformed * @return {boolean} true is OK */ -var isWsReply$1 = function (payload) { - var json = isString$3(payload) ? toJson$1(payload) : payload; +var isWsReply = function (payload) { + var json = isString$3(payload) ? toJson(payload) : payload; var data = json.data; if (data) { - var result = WS_KEYS$1.filter(function (key) { return isObjectHasKey$2(data, key); }); - return (result.length === WS_KEYS$1.length) ? data : false + var result = WS_KEYS.filter(function (key) { return isObjectHasKey$2(data, key); }); + return (result.length === WS_KEYS.length) ? data : false } return false }; @@ -11064,24 +11678,24 @@ var isWsReply$1 = function (payload) { * @param {function} [cb=nil] this is for extracting the TS field or when it's error * @return {object} false on failed */ -var extractWsPayload$1 = function (payload, cb) { +var extractWsPayload = function (payload, cb) { if ( cb === void 0 ) cb = nil$1; try { - var json = toJson$1(payload); + var json = toJson(payload); // now handle the data var _data; - if ((_data = isWsReply$1(json)) !== false) { + if ((_data = isWsReply(json)) !== false) { // note the ts property is on its own cb('_data', _data); return { - data: toJson$1(_data[WS_DATA_NAME$1]), - resolverName: _data[WS_EVT_NAME$1], - type: _data[WS_REPLY_TYPE$1] + data: toJson(_data[WS_DATA_NAME]), + resolverName: _data[WS_EVT_NAME], + type: _data[WS_REPLY_TYPE] } } - throw new JsonqlError$2(PAYLOAD_NOT_DECODED_ERR$1, payload) + throw new JsonqlError$2(PAYLOAD_NOT_DECODED_ERR, payload) } catch(e) { return cb(ERROR_KEY$1, e) } @@ -11197,7 +11811,7 @@ function bindSocketEventHandler(namespace, ws, ee, isPrivate, opts) { // log(`ws.onmessage raw payload`, payload) // @TODO the payload actually contain quite a few things - is that changed? // type: message, data: data_send_from_server - var json = extractWsPayload$1(payload.data); + var json = extractWsPayload(payload.data); var resolverName = json.resolverName; var type = json.type; @@ -11279,10 +11893,10 @@ function connectEventListener(nspMap, ee, log) { /** * Create the framework <---> jsonql client binding - * @param {object} frameworkModule the different WebSocket module + * @param {object} websocket the different WebSocket module * @return {function} the wsClientResolver */ -function bindWebsocketToJsonql(frameworkModule) { +function setupConnectClient(websocket) { /** * wsClientResolver * @param {object} opts configuration @@ -11294,9 +11908,12 @@ function bindWebsocketToJsonql(frameworkModule) { var log = opts.log; log("There is problem here with passing the opts", opts); - - opts[NSP_CLIENT] = initWebSocketClient(frameworkModule, opts); - opts[NSP_AUTH_CLIENT] = initWebSocketClient(frameworkModule, opts, true); + // this will put two callable methods into the opts + opts[NSP_CLIENT] = setupWebsocketClientFn(websocket); + // we don't need this one unless enableAuth === true + if (opts[ENABLE_AUTH_PROP_KEY$1] === true) { + opts[NSP_AUTH_CLIENT] = setupWebsocketClientFn(websocket, true); + } // debug log("[1] bindWebsocketToJsonql", ee.$name, nspMap); // @2020-03-20 @NOTE @@ -11319,13 +11936,7 @@ function bindWebsocketToJsonql(frameworkModule) { // this will be the news style interface that will pass to the jsonql-ws-client -/** - * @param {object} opts configuration - * @param {object} nspMap from the contract - * @param {object} ee instance of the eventEmitter - * @return {object} passing the same 3 input out with additional in the opts - */ -var setupSocketClientListener = bindWebsocketToJsonql(WebSocket); +var setupSocketClientListener = setupConnectClient(WebSocket); // this is the module entry point for node client @@ -11337,10 +11948,10 @@ function wsNodeClient(config, constProps) { return wsClientCore( setupSocketClientListener, - {}, + wsClientCheckMap, Object.assign({}, wsClientConstProps, constProps) )(config) } module.exports = wsNodeClient; -//# sourceMappingURL=main.js.map +//# sourceMappingURL=node-ws-client.js.map diff --git a/packages/@jsonql/ws/node-ws-client.js.map b/packages/@jsonql/ws/node-ws-client.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2ca498993df6c4b9aef1cd2f4674b099b1c8ded7 --- /dev/null +++ b/packages/@jsonql/ws/node-ws-client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"node-ws-client.js","sources":["../../ws-client-core/node_modules/lodash-es/isArray.js","node_modules/rollup-plugin-node-globals/src/global.js","../../ws-client-core/node_modules/lodash-es/_objectToString.js","../../ws-client-core/node_modules/lodash-es/_overArg.js","../../ws-client-core/node_modules/lodash-es/isObjectLike.js","../../ws-client-core/node_modules/lodash-es/_arrayMap.js","../../ws-client-core/node_modules/lodash-es/_baseSlice.js","../../ws-client-core/node_modules/lodash-es/_baseFindIndex.js","../../ws-client-core/node_modules/lodash-es/_baseIsNaN.js","../../ws-client-core/node_modules/lodash-es/_strictIndexOf.js","../../ws-client-core/node_modules/lodash-es/_asciiToArray.js","../../ws-client-core/node_modules/lodash-es/_hasUnicode.js","../../ws-client-core/node_modules/lodash-es/_unicodeToArray.js","../../ws-client-core/node_modules/jsonql-utils/src/generic.js","../../ws-client-core/node_modules/lodash-es/_listCacheClear.js","../../ws-client-core/node_modules/lodash-es/eq.js","../../ws-client-core/node_modules/lodash-es/_stackDelete.js","../../ws-client-core/node_modules/lodash-es/_stackGet.js","../../ws-client-core/node_modules/lodash-es/_stackHas.js","../../ws-client-core/node_modules/lodash-es/isObject.js","../../ws-client-core/node_modules/lodash-es/_toSource.js","../../ws-client-core/node_modules/lodash-es/_getValue.js","../../ws-client-core/node_modules/lodash-es/_hashDelete.js","../../ws-client-core/node_modules/lodash-es/_isKeyable.js","../../ws-client-core/node_modules/lodash-es/_createBaseFor.js","../../ws-client-core/node_modules/lodash-es/_copyArray.js","../../ws-client-core/node_modules/lodash-es/_isPrototype.js","../../ws-client-core/node_modules/lodash-es/isLength.js","../../ws-client-core/node_modules/lodash-es/stubFalse.js","../../ws-client-core/node_modules/lodash-es/_baseUnary.js","../../ws-client-core/node_modules/lodash-es/_safeGet.js","../../ws-client-core/node_modules/lodash-es/_baseTimes.js","../../ws-client-core/node_modules/lodash-es/_isIndex.js","../../ws-client-core/node_modules/lodash-es/_nativeKeysIn.js","../../ws-client-core/node_modules/lodash-es/identity.js","../../ws-client-core/node_modules/lodash-es/_apply.js","../../ws-client-core/node_modules/lodash-es/constant.js","../../ws-client-core/node_modules/lodash-es/_shortOut.js","../../ws-client-core/node_modules/jsonql-errors/src/enum-error.js","../../ws-client-core/node_modules/jsonql-errors/src/type-error.js","../../ws-client-core/node_modules/jsonql-errors/src/checker-error.js","../../ws-client-core/node_modules/jsonql-errors/src/validation-error.js","../../ws-client-core/node_modules/jsonql-utils/src/contract.js","../../ws-client-core/node_modules/jsonql-utils/src/timestamp.js","../../ws-client-core/node_modules/jsonql-utils/src/params-api.js","../../ws-client-core/node_modules/jsonql-utils/src/namespace.js","../../ws-client-core/src/callers/intercom-methods.js","../../ws-client-core/node_modules/jsonql-params-validator/src/number.js","../../ws-client-core/node_modules/jsonql-params-validator/src/string.js","../../ws-client-core/node_modules/jsonql-params-validator/src/boolean.js","../../ws-client-core/node_modules/jsonql-params-validator/src/any.js","../../ws-client-core/node_modules/jsonql-params-validator/src/constants.js","../../ws-client-core/node_modules/jsonql-params-validator/src/combine.js","../../ws-client-core/node_modules/jsonql-params-validator/src/array.js","../../ws-client-core/node_modules/jsonql-params-validator/src/object.js","../../ws-client-core/node_modules/jsonql-params-validator/src/validator.js","../../ws-client-core/node_modules/lodash-es/_setCacheAdd.js","../../ws-client-core/node_modules/lodash-es/_setCacheHas.js","../../ws-client-core/node_modules/lodash-es/_arraySome.js","../../ws-client-core/node_modules/lodash-es/_cacheHas.js","../../ws-client-core/node_modules/lodash-es/_mapToArray.js","../../ws-client-core/node_modules/lodash-es/_setToArray.js","../../ws-client-core/node_modules/lodash-es/_arrayPush.js","../../ws-client-core/node_modules/lodash-es/_arrayFilter.js","../../ws-client-core/node_modules/lodash-es/stubArray.js","../../ws-client-core/node_modules/lodash-es/_matchesStrictComparable.js","../../ws-client-core/node_modules/lodash-es/_baseHasIn.js","../../ws-client-core/node_modules/lodash-es/_baseProperty.js","../../ws-client-core/node_modules/lodash-es/negate.js","../../ws-client-core/node_modules/lodash-es/_baseFindKey.js","../../ws-client-core/node_modules/jsonql-params-validator/src/is-in-array.js","../../ws-client-core/node_modules/jsonql-params-validator/src/options/run-validation.js","../../ws-client-core/node_modules/jsonql-params-validator/src/options/check-options-async.js","../../ws-client-core/node_modules/jsonql-params-validator/src/options/construct-config.js","../../ws-client-core/node_modules/jsonql-params-validator/src/options/index.js","../../ws-client-core/node_modules/jsonql-params-validator/index.js","../../ws-client-core/src/utils/get-log-fn.js","../../ws-client-core/node_modules/@to1source/event/src/constants.js","../../ws-client-core/node_modules/@to1source/event/src/utils.js","../../ws-client-core/node_modules/@to1source/event/src/store.js","../../ws-client-core/node_modules/@to1source/event/src/base.js","../../ws-client-core/node_modules/@to1source/event/src/suspend.js","../../ws-client-core/node_modules/@to1source/event/src/store-service.js","../../ws-client-core/node_modules/@to1source/event/src/event-service.js","../../ws-client-core/node_modules/@to1source/event/index.js","../../ws-client-core/src/utils/get-event-emitter.js","../../ws-client-core/src/utils/helpers.js","../../ws-client-core/src/options/constants.js","../../ws-client-core/src/callers/respond-handler.js","../../ws-client-core/src/callers/action-call.js","../../ws-client-core/src/callers/setup-send-method.js","../../ws-client-core/src/callers/setup-resolver.js","../../ws-client-core/src/callers/generator-methods.js","../../ws-client-core/src/callers/global-listener.js","../../ws-client-core/src/callers/setup-auth-methods.js","../../ws-client-core/src/callers/setup-intercom.js","../../ws-client-core/src/callers/setup-final-step.js","../../ws-client-core/src/callers/callers-generator.js","../../ws-client-core/src/options/index.js","../../ws-client-core/src/api.js","../../ws-client-core/src/listener/trigger-namespaces-on-error.js","../../ws-client-core/src/listener/event-listeners.js","../../ws-client-core/src/listener/namespace-event-listener.js","../../ws-client-core/src/create-nsp-client.js","../../ws-client-core/node_modules/@jsonql/security/src/client/jwt-decode/invalid-character-error.js","../../ws-client-core/node_modules/@jsonql/security/src/client/jwt-decode/atob.js","../../ws-client-core/node_modules/@jsonql/security/src/socket/token-header-opts.js","node_modules/lodash-es/_arrayMap.js","node_modules/lodash-es/isArray.js","node_modules/lodash-es/_objectToString.js","node_modules/lodash-es/isObjectLike.js","node_modules/lodash-es/_baseSlice.js","node_modules/lodash-es/_baseFindIndex.js","node_modules/lodash-es/_baseIsNaN.js","node_modules/lodash-es/_strictIndexOf.js","node_modules/lodash-es/_asciiToArray.js","node_modules/lodash-es/_hasUnicode.js","node_modules/lodash-es/_unicodeToArray.js","node_modules/jsonql-params-validator/src/number.js","node_modules/jsonql-params-validator/src/string.js","node_modules/jsonql-params-validator/src/boolean.js","node_modules/jsonql-params-validator/src/any.js","node_modules/jsonql-params-validator/src/combine.js","node_modules/jsonql-params-validator/src/array.js","node_modules/lodash-es/_overArg.js","node_modules/jsonql-errors/src/validation-error.js","node_modules/lodash-es/_listCacheClear.js","node_modules/lodash-es/eq.js","node_modules/lodash-es/_stackDelete.js","node_modules/lodash-es/_stackGet.js","node_modules/lodash-es/_stackHas.js","node_modules/lodash-es/isObject.js","node_modules/lodash-es/_toSource.js","node_modules/lodash-es/_getValue.js","node_modules/lodash-es/_hashDelete.js","node_modules/lodash-es/_isKeyable.js","node_modules/lodash-es/_createBaseFor.js","node_modules/lodash-es/_copyArray.js","node_modules/lodash-es/_isPrototype.js","node_modules/lodash-es/isLength.js","node_modules/lodash-es/stubFalse.js","node_modules/lodash-es/_baseUnary.js","node_modules/lodash-es/_safeGet.js","node_modules/lodash-es/_baseTimes.js","node_modules/lodash-es/_isIndex.js","node_modules/lodash-es/_nativeKeysIn.js","node_modules/lodash-es/identity.js","node_modules/lodash-es/_apply.js","node_modules/lodash-es/constant.js","node_modules/lodash-es/_shortOut.js","node_modules/jsonql-params-validator/src/options/construct-config.js","node_modules/jsonql-params-validator/src/options/index.js","node_modules/jsonql-params-validator/index.js","src/core/setup-connect-client/setup-websocket-client-fn.js","src/core/setup-socket-listeners/login-event-listener.js","node_modules/jsonql-utils/src/chain-promises.js","src/core/create-nsp.js","node_modules/jsonql-utils/src/generic.js","node_modules/jsonql-utils/src/timestamp.js","node_modules/jsonql-utils/src/params-api.js","node_modules/jsonql-utils/src/socket.js","src/core/setup-socket-listeners/disconnect-event-listener.js","src/core/setup-socket-listeners/bind-socket-event-handler.js","src/core/setup-socket-listeners/connect-event-listener.js","src/core/setup-connect-client/setup-connect-client.js","src/node/setup-socket-client-listener.js","src/node-ws-client.js"],"sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg]\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @param {boolean} [t=true] or throw\n * @return {*} json object on success\n */\nexport const parseJson = function(n, t=true) {\n try {\n return JSON.parse(n)\n } catch(e) {\n if (t) {\n return n\n }\n throw new Error(e)\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = n => {\n if (typeof n === 'string') {\n return parseJson(n)\n }\n return parseJson(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== ''\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n\n/**\n * Shorthand method for Object.assign \n * @param {array} args \n * @return {object} merge together object by key \n */\nexport const assign = (...args) => Reflect.apply(Object.assign, Object, args)\n \n/** \n * generic placeholder function\n * @return {boolean} false \n */\nexport const nil = () => false\n\n/**\n * generic turn config into immutatble \n */\nexport const freeze = config => Object.freeze(config)","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError)\n }\n }\n\n static get name() {\n return 'JsonqlEnumError'\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlTypeError.name\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError)\n }\n }\n\n static get name() {\n return 'JsonqlTypeError'\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args)\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError)\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError'\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError'\n }\n}\n","// split the contract into the node side and the generic side\nimport { isObjectHasKey } from './generic'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n SOCKET_NAME,\n QUERY_ARG_NAME,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlResolverNotFoundError } from 'jsonql-errors'\n/**\n * Check if the json is a contract file or not\n * @param {object} contract json object\n * @return {boolean} true\n */\nexport function checkIsContract(contract) {\n return isPlainObject(contract)\n && (\n isObjectHasKey(contract, QUERY_NAME)\n || isObjectHasKey(contract, MUTATION_NAME)\n || isObjectHasKey(contract, SOCKET_NAME)\n )\n}\n\n/**\n * Wrapper method that check if it's contract then return the contract or false\n * @param {object} contract the object to check\n * @return {boolean | object} false when it's not\n */\nexport function isContract(contract) {\n return checkIsContract(contract) ? contract : false\n}\n\n/**\n * Ported from jsonql-params-validator but different\n * if we don't find the socket part then return false\n * @param {object} contract the contract object\n * @return {object|boolean} false on failed\n */\nexport function extractSocketPart(contract) {\n if (isObjectHasKey(contract, SOCKET_NAME)) {\n return contract[SOCKET_NAME]\n }\n return false\n}\n\n/**\n * Extract the args from the payload\n * @param {object} payload to work with\n * @param {string} type of call\n * @return {array} args\n */\nexport function extractArgsFromPayload(payload, type) {\n switch (type) {\n case QUERY_NAME:\n return payload[QUERY_ARG_NAME]\n case MUTATION_NAME:\n return [\n payload[PAYLOAD_PARAM_NAME],\n payload[CONDITION_PARAM_NAME]\n ]\n default:\n throw new JsonqlError(`Unknown ${type} to extract argument from!`)\n }\n}\n\n/**\n * Like what the name said\n * @param {object} contract the contract json\n * @param {string} type query|mutation\n * @param {string} name of the function\n * @return {object} the params part of the contract\n */\nexport function extractParamsFromContract(contract, type, name) {\n try {\n const result = contract[type][name]\n // debug('extractParamsFromContract', result)\n if (!result) {\n // debug(name, type, contract)\n throw new JsonqlResolverNotFoundError(name, type)\n }\n return result\n } catch(e) {\n throw new JsonqlResolverNotFoundError(name, e)\n }\n}\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time\n}\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\n\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isString from 'lodash-es/isString'\nimport isPlainObject from 'lodash-es/isPlainObject'\n\nimport { timestamp } from './timestamp'\nimport { parseJson } from './generic'\n\n/**\n * check if the payload has a timestamp field, then append a new timestamp to it\n * @param {object} payload from the com\n * @return {array} timestamp field with an array value\n */\nexport const handleTimestamp = payload => {\n let ts = payload[TIMESTAMP_PARAM_NAME]\n if (!isArray(ts)) {\n ts = [ts]\n }\n ts.push( timestamp() )\n\n return ts\n}\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? parseJson(payload) : payload\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * extract the resolver name from the payload \n * @param {object} payload\n * @return {string} resolver name \n */\nexport function getResolverFromPayload(payload) {\n const keys = Object.keys(payload)\n return keys.filter(key => key !== TIMESTAMP_PARAM_NAME)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName name of the resolver\n * @param {*} payload what is sending \n * @param {object} extra additonal property we want to merge into the deliverable\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload, extra = {}) {\n return Object.assign({\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }, extra)\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError('utils:params-api:createQuery', { \n message: `expect resolverName to be string and args to be array!`,\n resolverName, \n args \n })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getResolverFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// take out all the namespace related methods in one place for easy to find\nimport {\n JSONQL_PATH,\n PUBLIC_KEY,\n NSP_GROUP,\n PUBLIC_NAMESPACE\n} from 'jsonql-constants'\nimport { extractSocketPart } from './contract'\nconst SOCKET_NOT_FOUND_ERR = `socket not found in contract!`\nconst SIZE = 'size'\n\n/**\n * create the group using publicNamespace when there is only public\n * @param {object} socket from contract\n * @param {string} publicNamespace\n */\nfunction groupPublicNamespace(socket, publicNamespace) {\n let g = {}\n for (let resolverName in socket) {\n let params = socket[resolverName]\n g[resolverName] = params\n }\n return { size: 1, nspGroup: {[publicNamespace]: g}, publicNamespace}\n}\n\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport function groupByNamespace(contract) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n throw new JsonqlError('groupByNamespace', SOCKET_NOT_FOUND_ERR)\n }\n let prop = {\n [NSP_GROUP]: {},\n [PUBLIC_NAMESPACE]: null,\n [SIZE]: 0 \n }\n\n for (let resolverName in socket) {\n let params = socket[resolverName]\n let { namespace } = params\n if (namespace) {\n if (!prop[NSP_GROUP][namespace]) {\n ++prop[SIZE]\n prop[NSP_GROUP][namespace] = {}\n }\n prop[NSP_GROUP][namespace][resolverName] = params\n // get the public namespace\n if (!prop[PUBLIC_NAMESPACE] && params[PUBLIC_KEY]) {\n prop[PUBLIC_NAMESPACE] = namespace\n }\n }\n }\n \n return prop \n}\n\n/**\n * @NOTE ported from jsonql-ws-client\n * Got to make sure the connection order otherwise\n * it will hang\n * @param {object} nspGroup contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspGroup, publicNamespace) {\n let names = [] // need to make sure the order!\n for (let namespace in nspGroup) {\n if (namespace === publicNamespace) {\n names[1] = namespace\n } else {\n names[0] = namespace\n }\n }\n return names\n}\n\n/**\n * @TODO this might change, what if we want to do room with ws\n * 1. there will only be max two namespace\n * 2. when it's normal we will have the stock path as namespace\n * 3. when enableAuth then we will have two, one is jsonql/public + private\n * @param {object} config options\n * @return {array} of namespace(s)\n */\nexport function getNamespace(config) {\n const base = JSONQL_PATH\n if (config.enableAuth) {\n // the public come first @1.0.1 we use the constants instead of the user supplied value\n // @1.0.4 we use the config value again, because we could control this via the post init\n return [\n [ base , config.privateNamespace ].join('/'),\n [ base , config.publicNamespace ].join('/')\n ]\n }\n return [ base ]\n}\n\n/**\n * get the private namespace\n * @param {array} namespaces array\n * @return {*} string on success\n */\nexport function getPrivateNamespace(namespaces) {\n return namespaces.length > 1 ? namespaces[0] : false\n}\n\n/**\n * Got a problem with a contract that is public only the groupByNamespace is wrong\n * which is actually not a problem when using a fallback, but to be sure things in order\n * we could combine with the config to group it\n * @param {object} config configuration\n * @return {object} nspInfo object\n */\nexport function getNspInfoByConfig(config) {\n const { contract, enableAuth } = config\n const namespaces = getNamespace(config)\n let nspInfo = enableAuth ? groupByNamespace(contract)\n : groupPublicNamespace(contract.socket, namespaces[0])\n // add the namespaces into it as well\n return Object.assign(nspInfo, { namespaces })\n}\n\n","// this will be part of the init client sequence\n// as soon as we create a ws client\n// we listen to the on.connect event \n// then we send a init-ping event back to the server\n// and server issue a csrf token back to use \n// we use this token to create a new client and destroy the old one\nimport {\n INTERCOM_RESOLVER_NAME, \n SOCKET_PING_EVENT_NAME,\n HEADERS_KEY,\n DATA_KEY,\n CSRF_HEADER_KEY\n} from 'jsonql-constants'\nimport { \n createQueryStr, \n extractWsPayload,\n timestamp,\n toJson \n} from 'jsonql-utils/module'\nimport {\n JsonqlError\n} from 'jsonql-errors'\nconst CSRF_HEADER_NOT_EXIST_ERR = 'CSRF header is not in the received payload'\n\n/**\n * Util method \n * @param {string} payload return from server\n * @return {object} the useful bit \n */\nfunction extractSrvPayload(payload) {\n let json = toJson(payload)\n \n if (json && typeof json === 'object') {\n // note this method expect the json.data inside\n return extractWsPayload(json)\n }\n \n throw new JsonqlError('extractSrvPayload', json)\n}\n\n/**\n * call the server to get a csrf token \n * @return {string} formatted payload to send to the server \n */\nfunction createInitPing() {\n const ts = timestamp()\n\n return createQueryStr(INTERCOM_RESOLVER_NAME, [SOCKET_PING_EVENT_NAME, ts])\n}\n\n/**\n * Take the raw on.message result back then decoded it \n * @param {*} payload the raw result from server\n * @return {object} the csrf payload\n */\nfunction extractPingResult(payload) {\n const result = extractSrvPayload(payload)\n \n if (result && result[DATA_KEY] && result[DATA_KEY][CSRF_HEADER_KEY]) {\n return {\n [HEADERS_KEY]: result[DATA_KEY]\n }\n }\n\n throw new JsonqlError('extractPingResult', CSRF_HEADER_NOT_EXIST_ERR)\n}\n\n\n/**\n * Create a generic intercom method\n * @param {string} type the event type \n * @param {array} args if any \n * @return {string} formatted payload to send\n */\nfunction createIntercomPayload(type, ...args) {\n const ts = timestamp()\n let payload = [type].concat(args)\n payload.push(ts)\n return createQueryStr(INTERCOM_RESOLVER_NAME, payload)\n}\n\n\nexport { \n extractSrvPayload,\n createInitPing, \n extractPingResult, \n createIntercomPayload \n}","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false\n}\n\nexport default checkIsString\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nconst ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`\nconst PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`\nconst EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'\nconst UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread'\n\nconst RETURNS_NAME = 'returns'\n\nimport {\n \n DEFAULT_TYPE, // this is a mistake should move back to the validation\n DATA_KEY, \n ERROR_KEY,\n\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n \n ARRAY_TYPE,\n OBJECT_TYPE,\n STRING_TYPE,\n BOOLEAN_TYPE,\n NUMBER_TYPE,\n KEY_WORD,\n OR_SEPERATOR\n} from 'jsonql-constants'\n\n// group all export in one \nexport {\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR,\n DEFAULT_TYPE,\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n ARRAY_TYPE,\n OBJECT_TYPE,\n STRING_TYPE,\n BOOLEAN_TYPE,\n NUMBER_TYPE,\n KEY_WORD,\n OR_SEPERATOR,\n\n RETURNS_NAME,\n\n DATA_KEY, \n ERROR_KEY \n}","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber\n case STRING_TYPE:\n return checkIsString\n case BOOLEAN_TYPE:\n return checkIsBoolean\n default:\n return checkIsAny\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length\n}\n","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\n// import filter from 'lodash-es/filter'\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (_value !== undefined) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true\n }).length)\n }).length;\n }\n }\n return false\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p\n let _args = [arg]\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return Reflect.apply(checkIsObject, null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\n\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n combineFn,\n notEmpty\n} from './index'\n\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n DATA_KEY, \n ERROR_KEY \n} from './constants'\n\n\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\nimport JsonqlError from 'jsonql-errors/src/error'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (arg !== undefined) {\n return arg\n }\n return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlValidationError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return []\n }\n if (!checkIsArray(args)) {\n console.info(args)\n throw new JsonqlValidationError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ))\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ))\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ))\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length:\n let ctn = params.length;\n // this happens when we have those array. type\n let _type = [ DEFAULT_TYPE ]\n // we only looking at the first one, this might be a @BUG\n /*\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n } */\n // if we use the params as guide then the rest will get throw out\n // which is not what we want, instead, anything without the param\n // will get a any type and optional flag\n return args.map((arg, i) => {\n let optional = i >= ctn ? true : !!params[i].optional\n let param = params[i] || { type: _type, name: `_${i}` }\n return {\n arg: optional ? getOptionalValue(arg, param) : arg,\n index: i,\n param,\n optional\n }\n })\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n // v1.4.4 this fixed the problem, the root level optional is from the last fn\n if (p.optional === true || p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport isFunction from 'lodash-es/isFunction'\nimport merge from 'lodash-es/merge'\nimport mapValues from 'lodash-es/mapValues'\n\nimport JsonqlEnumError from 'jsonql-errors/src/enum-error'\nimport JsonqlTypeError from 'jsonql-errors/src/type-error'\nimport JsonqlCheckerError from 'jsonql-errors/src/checker-error'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false\n } catch (e) {\n return false\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // log('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n // log(ENUM_KEY, value[ENUM_KEY])\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n // log(CHECKER_KEY, value[CHECKER_KEY])\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","/// this is port back from the client to share across all projects\n\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:check-options-async')\n\n/**\n * Quick transform\n * @param {object} config that one\n * @param {object} appProps mutation configuration options\n * @return {object} put that arg into the args\n */\nconst configToArgs = (config, appProps) => {\n return Promise.resolve(\n prepareArgsForValidation(config, appProps)\n )\n}\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return configToArgs(config, appProps)\n .then(args1 => runValidation(args1, cb))\n // next if every thing good then pass to final merging\n .then(args2 => merge({}, args2, constProps))\n}\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\n// import checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n }\n if (optional === true) {\n base[OPTIONAL_KEY] = true\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias\n }\n return base\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__'\n\n/**\n * construct the actual end user method, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfigAsync = function(validateSync) {\n /**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n/**\n * copy of above but it's sync, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n getCheckConfigAsync,\n getCheckConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\nimport * as validator from './src/validator'\n// configuration checking\nimport * as jsonqlOptions from './src/options'\n// the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nconst isObject = checkIsObject\nconst isAny = checkIsAny\nconst isString = checkIsString\nconst isBoolean = checkIsBoolean\nconst isNumber = checkIsNumber\nconst isArray = checkIsArray\nconst isNotEmpty = notEmpty\n\nconst normalizeArgs = validator.normalizeArgs\nconst validateSync = validator.validateSync\nconst validateAsync = validator.validateAsync\n\nconst JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO\n\nconst createConfig = jsonqlOptions.createConfig\nconst constructConfig = jsonqlOptions.constructConfigFn\n// construct the final output 1.5.2\nconst checkConfigAsync = jsonqlOptions.getCheckConfigAsync(validator.validateSync)\nconst checkConfig = jsonqlOptions.getCheckConfig(validator.validateSync)\n\nconst inArray = isInArray\nconst isObjectHasKey = isObjectHasKeyFn\n\n// check returns methods \nimport { \n checkReturns, \n checkReturnsAsync, \n checkResolverReturns, \n checkResolverReturnsAsync \n} from './src/returns'\n\n\n// group the in one \nexport {\n JSONQL_PARAMS_VALIDATOR_INFO,\n \n isObject,\n isAny,\n isString,\n isBoolean,\n isNumber,\n isArray,\n isNotEmpty,\n \n inArray,\n isObjectHasKey,\n\n normalizeArgs,\n validateSync,\n validateAsync,\n\n createConfig,\n constructConfig,\n checkConfig,\n checkConfigAsync,\n\n checkReturns, \n checkReturnsAsync, \n checkResolverReturns, \n checkResolverReturnsAsync\n}\n\n\n\n\n\n","// move the get logger stuff here\n\n// it does nothing\nconst dummyLogger = () => {}\n\n/**\n * re-use the debugOn prop to control this log method\n * @param {object} opts configuration\n * @return {function} the log function\n */\nconst getLogger = (opts) => {\n const { debugOn } = opts \n if (debugOn) {\n return (...args) => {\n Reflect.apply(console.info, console, ['[jsonql-ws-client-core]', ...args])\n }\n }\n return dummyLogger\n}\n\n/**\n * Make sure there is a log method\n * @param {object} opts configuration\n * @return {object} opts\n */\nconst getLogFn = opts => {\n const { log } = opts // 1.3.9 if we pass a log method here then we use this\n if (!log || typeof log !== 'function') {\n return getLogger(opts)\n }\n opts.log('---> getLogFn user supplied log function <---', opts)\n return log\n}\n\nexport { getLogFn }","// group all the repetitive message here\n\nexport const TAKEN_BY_OTHER_TYPE_ERR = 'You are trying to register an event already been taken by other type:'\n\n// use constants for type\nexport const ON_TYPE = 'on'\nexport const ONLY_TYPE = 'only'\nexport const ONCE_TYPE = 'once'\nexport const ONLY_ONCE_TYPE = 'onlyOnce'\nexport const MAX_CALL_TYPE = 'maxAllowCall'\nexport const NEG_RETURN = -1\n\nexport const AVAILABLE_TYPES = [\n ON_TYPE,\n ONLY_TYPE,\n ONCE_TYPE,\n ONLY_ONCE_TYPE\n]\n// the type which the callMax can execute on\nexport const ON_MAX_TYPES = [\n ON_TYPE,\n ONLY_TYPE\n]\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n\n/**\n * wrapper to make sure it string\n * @param {*} input whatever\n * @return {string} output\n */\nexport function hashCode2Str(s) {\n return hashCode(s) + ''\n}\n\n/**\n * Just check if a pattern is an RegExp object\n * @param {*} pat whatever\n * @return {boolean} false when its not\n */\nexport function isRegExp(pat) {\n return pat instanceof RegExp\n}\n\n/**\n * check if its string\n * @param {*} arg whatever\n * @return {boolean} false when it's not\n */\nexport function isString(arg) {\n return typeof arg === 'string'\n}\n\n/**\n * check if it's an integer\n * @param {*} num input number\n * @return {boolean}\n */\nexport function isInt(num) {\n if (isString(num)) {\n throw new Error(`Wrong type, we want number!`)\n }\n return !isNaN(parseInt(num))\n}\n\n/**\n * Find from the array by matching the pattern\n * @param {*} pattern a string or RegExp object\n * @return {object} regex object or false when we can not id the input\n */\nexport function getRegex(pattern) {\n switch (true) {\n case isRegExp(pattern) === true:\n return pattern\n case isString(pattern) === true:\n return new RegExp(pattern)\n default:\n return false\n }\n}\n\n\n/**\n * in array\n * @param {array} arr to search\n * @param {*} prop to search\n */\n export const inArray = (arr, prop) => !!arr.filter(v => prop === v).length\n","// Create two WeakMap store as a private keys\nexport const NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap()\nexport const NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap()\n","// setup a base class to put all the don't know where to put methods \nimport { hashCode2Str, isString } from './utils'\nimport { AVAILABLE_TYPES } from './constants'\n\nexport default class BaseClass {\n\n constructor() {}\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n // for id if the instance is this class\n get $name() {\n return 'to1source-event'\n }\n\n // take this down in the next release\n get is() {\n return this.$name\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (!isString(e)) {\n this.logger('(validateEvt)', e)\n\n throw new Error(`Event name must be string type! we got ${typeof e}`)\n }\n })\n\n return true\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n\n return true\n }\n }\n throw new Error(`callback required to be function type! we got ${typeof callback}`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n this.validateEvt(type)\n \n return !!AVAILABLE_TYPES.filter(t => type === t).length\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run) callback:', callback, 'payload:', payload, 'context:', ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n\n return this.$done // return it here first \n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n\n return hashCode2Str(fn.toString())\n }\n} ","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n/*\nwe use a different way to do the same watch thing now\nthis.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n})\n*/\nimport { getRegex, isRegExp } from './utils'\n\nimport BaseClass from './base'\n\nexport default class SuspendClass extends BaseClass {\n\n constructor() {\n super()\n\n // suspend, release and queue\n this.__suspend_state__ = null\n // to do this proper we don't use a new prop to hold the event name pattern\n this.__pattern__ = null\n\n\n this.queueStore = new Set()\n }\n\n /**\n * start suspend\n * @return {void}\n */\n $suspend() {\n this.logger(`---> SUSPEND ALL OPS <---`)\n this.__suspend__(true)\n }\n\n /**\n * release the queue\n * @return {void}\n */\n $release() {\n this.logger(`---> RELEASE SUSPENDED QUEUE <---`)\n this.__suspend__(false)\n }\n\n /**\n * suspend event by pattern\n * @param {string} pattern the pattern search matches the event name\n * @return {void}\n */\n $suspendEvent(pattern) {\n const regex = getRegex(pattern)\n if (isRegExp(regex)) {\n this.__pattern__ = regex\n return this.$suspend()\n }\n throw new Error(`We expect a pattern variable to be string or RegExp, but we got \"${typeof regex}\" instead`)\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {string} evt the event name\n * @param {*} args unknown number of arguments\n * @return {boolean} true when added or false when it's not\n */\n $queue(evt, ...args) {\n this.logger('($queue) get called')\n if (this.__suspend_state__ === true) {\n if (isRegExp(this.__pattern__)) { // it's better then check if its not null\n // check the pattern and decide if we want to suspend it or not\n let found = this.__pattern__.test(evt)\n if (!found) {\n return false\n }\n }\n this.logger('($queue) added to $queue', args)\n // @TODO there shouldn't be any duplicate, but how to make sure?\n this.queueStore.add([evt].concat(args))\n // return this.queueStore.size\n }\n return !!this.__suspend_state__\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n __suspend__(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend_state__\n this.__suspend_state__ = value\n this.logger(`($suspend) Change from \"${lastValue}\" --> \"${value}\"`)\n if (lastValue === true && value === false) {\n this.__release__()\n }\n } else {\n throw new Error(`$suspend only accept Boolean value! we got ${typeof value}`)\n }\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n __release__() {\n let size = this.queueStore.size\n let pattern = this.__pattern__\n this.__pattern__ = null\n this.logger(`(release) was called with ${size}${pattern ? ' for \"' + pattern + '\"': ''} item${size > 1 ? 's' : ''}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('(release queue)', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n\n return size\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport {\n NEG_RETURN,\n ON_MAX_TYPES\n} from './constants'\nimport { isInt, inArray } from './utils'\n\nimport SuspendClass from './suspend'\n\nexport default class StoreService extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger\n }\n this.keep = config.keep\n // for the $done setter\n this.result = config.keep ? [] : null\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n // this is the new throw away map\n this.maxCountStore = new Map()\n }\n\n /**\n * We need this to pre-check the store, otherwise\n * the execution will be unable to determine the number of calls\n * @param {string} evtName event name\n * @return {number} the count of this store\n */\n getMaxStore(evtName) {\n return this.maxCountStore.get(evtName) || NEG_RETURN\n }\n\n /**\n * This is one stop shop to check and munipulate the maxStore\n * @param {*} evtName\n * @param {*} [max=null]\n * @return {number} when return -1 means removed\n */\n checkMaxStore(evtName, max = null) {\n this.logger(`===========================================`)\n this.logger('checkMaxStore start', evtName, max)\n // init the store\n if (max !== null && isInt(max)) {\n // because this is the setup phrase we just return the max value\n this.maxCountStore.set(evtName, max)\n this.logger(`Setup max store for ${evtName} with ${max}`)\n return max\n }\n if (max === null) {\n // first check if this exist in the maxStore\n let value = this.getMaxStore(evtName)\n\n this.logger('getMaxStore value', value)\n\n if (value !== NEG_RETURN) {\n if (value > 0) {\n --value\n }\n if (value > 0) {\n this.maxCountStore.set(evtName, value) // just update the value\n } else {\n this.maxCountStore.delete(evtName) // just remove it\n this.logger(`remove ${evtName} from maxStore`)\n return NEG_RETURN\n }\n }\n return value\n }\n throw new Error(`Expect max to be an integer, but we got ${typeof max} ${max}`)\n }\n\n /**\n * Wrap several get filter ops together to return the callback we are looking for\n * @param {string} evtName to search for\n * @return {array} empty array when not found\n */\n searchMapEvt(evtName) {\n const evts = this.$get(evtName, true) // return in full\n const search = evts.filter(result => {\n const [ ,,,type ] = result\n\n return inArray(ON_MAX_TYPES, type)\n })\n\n return search.length ? search : []\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName] // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger(`(takeFromStore) has \"${evt}\"`, content)\n store.delete(evt)\n\n return content\n }\n\n return false\n }\n throw new Error(`\"${storeName}\" is not supported!`)\n }\n\n /**\n * This was part of the $get. We take it out\n * so we could use a regex to remove more than one event\n * @param {object} store the store to return from\n * @param {string} evt event name\n * @param {boolean} full return just the callback or everything\n * @return {array|boolean} false when not found\n */\n findFromStore(evt, store, full = false) {\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l\n }\n let [, callback,] = l\n\n return callback\n })\n }\n return false\n }\n\n /**\n * Similar to the findFromStore, but remove\n * @param {string} evt event name\n * @param {object} store the store to remove from\n * @return {boolean} false when not found\n */\n removeFromStore(evt, store) {\n if (store.has(evt)) {\n this.logger('($off)', evt)\n\n store.delete(evt)\n\n return true\n }\n return false\n }\n\n /**\n * Take out from addToStore for reuse\n * @param {object} store the store to use\n * @param {string} evt event name\n * @return {object} the set within the store\n */\n getStoreSet(store, evt) {\n let fnSet\n if (store.has(evt)) {\n this.logger(`(addToStore) \"${evt}\" existed`)\n fnSet = store.get(evt)\n } else {\n this.logger(`(addToStore) create new Set for \"${evt}\"`)\n // this is new\n fnSet = new Set()\n }\n return fnSet\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n const fnSet = this.getStoreSet(store, evt)\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger(`(addToStore) insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(li => {\n let [hash,] = li\n return hash === args[0]\n }).length\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list\n return type !== t\n }).length\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n\n this.logger('(checkTypeInLazyStore)', store)\n\n if (store) {\n\n return !!Array\n .from(store)\n .filter(li => {\n let [,,t] = li\n return t !== type\n }).length\n }\n\n return false\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger(`(addToNormalStore) try to add \"${type}\" --> \"${evt}\" to normal store`)\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n\n this.logger('(addToNormalStore)', `\"${type}\" --> \"${evt}\" can add to normal store`)\n\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store\n\n return size\n }\n\n return false\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store\n this.logger(`(addToLazyStore) size: ${size}`)\n\n return size\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg]\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n\n}\n","// The top level\nimport {\n ON_TYPE,\n ONLY_TYPE,\n ONCE_TYPE,\n ONLY_ONCE_TYPE,\n MAX_CALL_TYPE,\n ON_MAX_TYPES,\n TAKEN_BY_OTHER_TYPE_ERR,\n NEG_RETURN\n} from './constants'\nimport { isInt, inArray } from './utils'\nimport StoreService from './store-service'\n// export\nexport default class EventService extends StoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on'\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger(`($on) \"${evt}\" is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger(`($on) ${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content\n if (t && t !== type) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger(`($on)`, `call run \"${evt}\"`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n\n this.logger(`($on) return size ${size}`)\n return size\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n // let nStore = this.normalStore\n if (lazyStoreContent === false) {\n this.logger(`($once) \"${evt}\" is not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, ONCE_TYPE, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== ONCE_TYPE) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger('($once)', `call run \"${evt}\"`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n\n let added = false\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore\n\n if (!nStore.has(evt)) {\n this.logger(`($only) \"${evt}\" add to normalStore`)\n\n added = this.addToNormalStore(evt, ONLY_TYPE, callback, context)\n }\n\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger(`($only) \"${evt}\" found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( li => {\n const [ payload, ctx, t ] = li\n if (t && t !== ONLY_TYPE) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger(`($only) call run \"${evt}\"`)\n this.run(callback, payload, context || ctx)\n })\n }\n\n return added\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD added in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n\n let added = false\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce) \"${evt}\" add to normalStore`)\n\n added = this.addToNormalStore(evt, ONLY_ONCE_TYPE, callback, context)\n }\n\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== ONLY_ONCE_TYPE) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger(`($onlyOnce) call run \"${evt}\"`)\n\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added\n }\n\n /**\n * change the way how it suppose to work, instead of create another new store\n * We perform this check on the trigger end, so we set the number max\n * whenever we call the callback, we increment a value in the store\n * once it reaches that number we remove that event from the store,\n * also this will not get add to the lazy store,\n * which means the event must register before we can fire it\n * therefore we don't have to deal with the backward check\n * @param {string} evtName the event to get pre-registered\n * @param {number} max pass the max amount of callback can add to this event\n * @param {*} [ctx=null] the context the callback execute in\n * @return {function} the event handler\n */\n $max(evtName, max, ctx = null) {\n this.validateEvt(evtName)\n if (isInt(max) && max > 0) {\n // find this in the normalStore\n const fnSet = this.$get(evtName, true)\n if (fnSet !== false) {\n const evts = this.searchMapEvt(evtName)\n if (evts.length) {\n // should only have one anyway\n const [,,,type] = evts[0]\n // now init the max store\n const value = this.checkMaxStore(evtName, max)\n const _self = this\n /**\n * construct the callback\n * @param {array<*>} args\n * @return {number} \n */\n return function executeMaxCall(...args) {\n const ctn = _self.getMaxStore(evtName)\n let value = NEG_RETURN\n if (ctn > 0) {\n const fn = _self.$call(evtName, type, ctx)\n Reflect.apply(fn, _self, args)\n\n value = _self.checkMaxStore(evtName)\n if (value === NEG_RETURN) {\n _self.$off(evtName)\n return NEG_RETURN\n }\n }\n return value\n }\n }\n }\n // change in 1.1.1 because we might just call it without knowing if it's register or not\n this.logger(`The ${evtName} is not registered, can not execute non-existing event at the moment`)\n return NEG_RETURN\n }\n throw new Error(`Expect max to be an integer and greater than zero! But we got [${typeof max}]${max} instead`)\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {*}\n */\n $replace(evt, callback, context = null, type = ON_TYPE) {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n\n this.logger(`($replace)`, evt, callback)\n\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0\n // first check the normal store\n let nStore = this.normalStore\n this.logger('($trigger) normalStore', nStore)\n if (nStore.has(evt)) {\n this.logger(`($trigger) \"${evt}\" found`)\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n if (added) {\n this.logger(`($trigger) Currently suspended \"${evt}\" added to queue, nothing executed. Exit now.`)\n return false // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length\n let hasOnce = false\n // let hasOnly = false\n for (let i=0; i < ctn; ++i) {\n ++found\n // this.logger('found', found)\n let [ _, callback, ctx, _type ] = nSet[i]\n this.logger(`($trigger) call run for ${type}:${evt}`)\n\n this.run(callback, payload, context || ctx)\n\n if (_type === 'once' || _type === 'onlyOnce') {\n hasOnce = true\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter aroun\n * @NOTE breaking change: v1.9.1 it return an function to accept the params as spread\n * @param {string} evt event name\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, type = false, context = null) {\n const ctx = this\n\n return function executeCall(...args) {\n let _args = [evt, args, context, type]\n\n return Reflect.apply(ctx.$trigger, ctx, _args)\n }\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n // @TODO we will allow a regex pattern to mass remove event\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n\n return !!stores\n .filter(store => store.has(evt))\n .map(store => this.removeFromStore(evt, store))\n .length\n }\n\n /**\n * return all the listener bind to that event name\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n // @TODO should we allow the same Regex to search for all?\n this.validateEvt(evt)\n let store = this.normalStore\n return this.findFromStore(evt, store, full)\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done) set value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n this.logger('($done) get result:', this.result)\n if (this.keep) {\n return this.result[this.result.length - 1]\n }\n return this.result\n }\n\n /**\n * Take a look inside the stores\n * @param {number|null} idx of the store, null means all\n * @return {void}\n */\n $debug(idx = null) {\n let names = ['lazyStore', 'normalStore']\n let stores = [this.lazyStore, this.normalStore]\n if (stores[idx]) {\n this.logger(names[idx], stores[idx])\n } else {\n stores.map((store, i) => {\n this.logger(names[i], store)\n })\n }\n }\n}\n","// default\nimport To1sourceEvent from './src/event-service'\n\nexport default To1sourceEvent\n","// this will generate a event emitter and will be use everywhere\nimport EventEmitterClass from '@to1source/event'\n// create a clone version so we know which one we actually is using\nclass JsonqlWsEvt extends EventEmitterClass {\n\n constructor(logger) {\n if (typeof logger !== 'function') {\n throw new Error(`Just die here the logger is not a function!`)\n }\n logger(`---> Create a new EventEmitter <---`)\n // this ee will always come with the logger\n // because we should take the ee from the configuration\n super({ logger })\n }\n\n get name() {\n return'jsonql-ws-client-core'\n }\n}\n\n/**\n * getting the event emitter\n * @param {object} opts configuration\n * @return {object} the event emitter instance\n */\nconst getEventEmitter = opts => {\n const { log, eventEmitter } = opts\n \n if (eventEmitter) {\n log(`eventEmitter is:`, eventEmitter.name)\n return eventEmitter\n }\n \n return new JsonqlWsEvt( opts.log )\n}\n\nexport { \n getEventEmitter, \n EventEmitterClass // for other module to build from \n}\n","// group all the small functions here\nimport { EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/src/generic'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\n\n/**\n * WebSocket is strict about the path, therefore we need to make sure before it goes in\n * @param {string} url input url\n * @param {string} serverType this is not in use at the moment\n * @return {string} url with correct path name\n */\nexport const fixWss = (url, serverType=false) => {\n const uri = url.toLowerCase()\n if (uri.indexOf('http') > -1) {\n if (uri.indexOf('https') > -1) {\n return uri.replace('https', 'wss')\n }\n return uri.replace('http', 'ws')\n }\n return uri\n}\n\n\n/**\n * get a stock host name from browser\n */\nexport const getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n throw new JsonqlValidationError(e)\n }\n}\n\n/**\n * Unbind the event\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nexport const clearMainEmitEvt = (ee, namespace) => {\n let nsps = toArray(namespace)\n nsps.forEach(n => {\n ee.$off(createEvt(n, EMIT_REPLY_TYPE))\n })\n}\n\n\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME\nconst WS = JS_WS_NAME\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!'\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!'\n\nconst MISSING_PROP_ERR = 'Missing property in contract!'\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!'\n\nconst EMIT_EVT = EMIT_REPLY_TYPE\n\nconst NAMESPACE_KEY = 'namespaceMap'\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!'\n\nconst NOT_ALLOW_OP = 'This operation is not allow!'\n\nconst MY_NAMESPACE = 'myNamespace'\n\nconst CB_FN_NAME = 'on'\n// this is a socket only (for now) feature so we just put it here \nconst DISCONNECTED_ERROR_MSG = `You have disconnected from the socket server, please reconnect.`\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME,\n DISCONNECTED_ERROR_MSG\n}\n","// breaking it up further to share between methods\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { UNKNOWN_RESULT } from '../options/constants'\nimport { isObjectHasKey } from '../utils'\n\n/**\n * break out to use in different places to handle the return from server\n * @param {object} data from server\n * @param {function} resolver NOT from promise\n * @param {function} rejecter NOT from promise\n * @return {void} nothing\n */\nexport function respondHandler(data, resolver, rejecter) {\n if (isObjectHasKey(data, ERROR_KEY)) {\n // debugFn('-- rejecter called --', data[ERROR_KEY])\n rejecter(data[ERROR_KEY])\n } else if (isObjectHasKey(data, DATA_KEY)) {\n // debugFn('-- resolver called --', data[DATA_KEY])\n // @NOTE we change from calling it directly to use reflect \n // this could have another problem later when the return data is no in an array structure\n Reflect.apply(resolver, null, [...data[DATA_KEY]])\n } else {\n // debugFn('-- UNKNOWN_RESULT --', data)\n rejecter({message: UNKNOWN_RESULT, error: data})\n }\n}\n","// the actual trigger call method\nimport { ON_RESULT_FN_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { createEvt, toArray } from '../utils'\nimport { respondHandler } from './respond-handler'\n\n/**\n * just wrapper\n * @param {object} ee EventEmitter\n * @param {string} namespace where this belongs\n * @param {string} resolverName resolver\n * @param {array} args arguments\n * @param {function} log function \n * @return {void} nothing\n */\nexport function actionCall(ee, namespace, resolverName, args = [], log) {\n // reply event \n const outEventName = createEvt(namespace, EMIT_REPLY_TYPE)\n\n log(`actionCall: ${outEventName} --> ${resolverName}`, args)\n // This is the out going call \n ee.$trigger(outEventName, [resolverName, toArray(args)])\n \n // then we need to listen to the event callback here as well\n return new Promise((resolver, rejecter) => {\n const inEventName = createEvt(namespace, resolverName, ON_RESULT_FN_NAME)\n // this cause the onResult got the result back first \n // and it should be the promise resolve first\n // @TODO we need to rewrote the respondHandler to change the problem stated above \n ee.$on(\n inEventName,\n function actionCallResultHandler(result) {\n log(`got the first result`, result)\n respondHandler(result, resolver, rejecter)\n }\n )\n })\n}\n","// setting up the send method \nimport { JsonqlValidationError } from 'jsonql-errors'\nimport {\n ON_ERROR_FN_NAME,\n SEND_MSG_FN_NAME\n} from 'jsonql-constants'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { objDefineProps, createEvt, toArray, nil } from '../utils'\nimport { actionCall } from './action-call'\n\n/** \n * pairing with the server vesrion SEND_MSG_FN_NAME\n * last of the chain so only return the resolver (fn)\n * This is now change to a getter / setter method \n * and call like this: resolver.send(...args)\n * @param {function} fn the resolver function \n * @param {object} ee event emitter instance \n * @param {string} namespace the namespace it belongs to \n * @param {string} resolverName name of the resolver \n * @param {object} params from contract \n * @param {function} log a logger function\n * @return {function} return the resolver itself \n */ \nexport const setupSendMethod = (fn, ee, namespace, resolverName, params, log) => (\n objDefineProps(\n fn, \n SEND_MSG_FN_NAME, \n nil, \n function sendHandler() {\n log(`running call getter method`)\n // let _log = (...args) => Reflect.apply(console.info, console, ['[SEND]'].concat(args))\n /** \n * This will follow the same pattern like the resolver \n * @param {array} args list of unknown argument follow the resolver \n * @return {promise} resolve the result \n */\n return function sendCallback(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => {\n // @TODO check the result \n // because the validation could failed with the list of fail properties \n log('execute send', namespace, resolverName, _args)\n return actionCall(ee, namespace, resolverName, _args, log)\n })\n .catch(err => {\n // @TODO it shouldn't be just a validation error \n // it could be server return error, so we need to check \n // what error we got back here first \n log('send error', err)\n // @TODO it might not an validation error need the finalCatch here\n ee.$call(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n [new JsonqlValidationError(resolverName, err)]\n )\n })\n } \n })\n)\n","// break up the original setup resolver method here\n// import { JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport {\n ON_ERROR_FN_NAME,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME\n} from 'jsonql-constants'\nimport { finalCatch } from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { actionCall } from './action-call'\n// local\nimport { MY_NAMESPACE } from '../options/constants'\nimport { chainFns, objDefineProps, injectToFn, createEvt, isFunc } from '../utils'\nimport { respondHandler } from './respond-handler'\nimport { setupSendMethod } from './setup-send-method'\n\n\n/**\n * moved back from generator-methods \n * create the actual function to send message to server\n * @param {object} ee EventEmitter instance\n * @param {string} namespace this resolver end point\n * @param {string} resolverName name of resolver as event name\n * @param {object} params from contract\n * @param {function} log pass the log function\n * @return {function} resolver\n */\nfunction createResolver(ee, namespace, resolverName, params, log) {\n // note we pass the new withResult=true option\n return function resolver(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => actionCall(ee, namespace, resolverName, _args, log))\n .catch(finalCatch)\n }\n}\n\n/**\n * The first one in the chain, just setup a namespace prop\n * the rest are passing through\n * @param {function} fn the resolver function\n * @param {object} ee the event emitter\n * @param {string} resolverName what it said\n * @param {object} params for resolver from contract\n * @param {function} log the logger function\n * @return {array}\n */\nconst setupNamespace = (fn, ee, namespace, resolverName, params, log) => [\n injectToFn(fn, MY_NAMESPACE, namespace),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * onResult handler\n */\nconst setupOnResult = (fn, ee, namespace, resolverName, params, log) => [\n objDefineProps(fn, ON_RESULT_FN_NAME, function(resultCallback) {\n if (isFunc(resultCallback)) {\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_FN_NAME),\n function resultHandler(result) {\n respondHandler(result, resultCallback, (error) => {\n log(`Catch error: \"${resolverName}\"`, error)\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n error\n )\n })\n }\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * we do need to add the send prop back because it's the only way to deal with\n * bi-directional data stream\n */\nconst setupOnMessage = (fn, ee, namespace, resolverName, params, log) => [\n objDefineProps(fn, ON_MESSAGE_FN_NAME, function(messageCallback) {\n // we expect this to be a function\n if (isFunc(messageCallback)) {\n // did that add to the callback\n let onMessageCallback = (args) => {\n log(`onMessageCallback`, args)\n respondHandler(\n args, \n messageCallback, \n (error) => {\n log(`Catch error: \"${resolverName}\"`, error)\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n error\n )\n })\n }\n // register the handler for this message event\n ee.$only(\n createEvt(namespace, resolverName, ON_MESSAGE_FN_NAME),\n onMessageCallback\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * ON_ERROR_FN_NAME handler\n */\nconst setupOnError = (fn, ee, namespace, resolverName, params, log) => [\n objDefineProps(fn, ON_ERROR_FN_NAME, function(resolverErrorHandler) {\n if (isFunc(resolverErrorHandler)) {\n // please note ON_ERROR_FN_NAME can add multiple listners\n ee.$only(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n resolverErrorHandler\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * Add extra property / listeners to the resolver\n * @param {string} namespace where this belongs\n * @param {string} resolverName name as event name\n * @param {object} params from contract\n * @param {function} fn resolver function\n * @param {object} ee EventEmitter\n * @param {function} log function\n * @return {function} resolver\n */ \nfunction setupResolver(namespace, resolverName, params, fn, ee, log) {\n let fns = [\n setupNamespace,\n setupOnResult,\n setupOnMessage,\n setupOnError,\n setupSendMethod\n ]\n const executor = Reflect.apply(chainFns, null, fns)\n // get the executor\n return executor(fn, ee, namespace, resolverName, params, log)\n}\n\nexport { \n createResolver, \n setupResolver \n}","// put all the resolver related methods here to make it more clear\n\n// this will be a mini client server architect\n// The reason is when the enableAuth setup - the private route\n// might not be validated, but we need the callable point is ready\n// therefore this part will always take the contract and generate\n// callable api for the developer to setup their front end\n// the only thing is - when they call they might get an error or\n// NOT_LOGIN_IN and they can react to this error accordingly\n\nimport { \n createResolver, \n setupResolver \n} from './setup-resolver'\nimport {\n injectToFn\n} from '../utils'\n\n\n/**\n * step one get the clientmap with the namespace\n * @param {object} opts configuration\n * @param {object} ee EventEmitter\n * @param {object} nspGroup resolvers index by their namespace\n * @return {promise} resolve the clientmapped, and start the chain\n */\nexport function generateResolvers(opts, ee, nspGroup) {\n const { log } = opts\n let client= {}\n \n for (let namespace in nspGroup) {\n let list = nspGroup[namespace]\n for (let resolverName in list) {\n // resolverNames.push(resolverName)\n let params = list[resolverName]\n let fn = createResolver(ee, namespace, resolverName, params, log)\n // this should set as a getter therefore can not be overwrite by accident\n client = injectToFn(\n client,\n resolverName,\n setupResolver(namespace, resolverName, params, fn, ee, log)\n )\n }\n }\n \n // resolve the clientto start the chain\n // chain the result to allow the chain processing\n return [ client, opts, ee, nspGroup ]\n}\n\n","// move from generator-methods \n// they are global event listeners \nimport {\n createEvt,\n objDefineProps,\n isFunc\n} from '../utils'\nimport {\n ON_ERROR_FN_NAME,\n ON_READY_FN_NAME\n} from 'jsonql-constants'\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * @param {object} client client itself\n * @param {object} opts configuration\n * @param {object} ee Event Emitter\n * @return {array} [ obj, opts, ee ]\n */\nexport function setupOnReadyListener(client, opts, ee) {\n return [\n objDefineProps(\n client,\n ON_READY_FN_NAME,\n function onReadyCallbackHandler(onReadyCallback) {\n if (isFunc(onReadyCallback)) {\n // reduce it down to just one flat level\n // @2020-03-19 only allow ONE onReady callback otherwise\n // it will get fire multiple times which is not what we want\n ee.$only(ON_READY_FN_NAME, onReadyCallback)\n }\n }\n ),\n opts,\n ee\n ]\n}\n\n/**\n * The problem is the namespace can have more than one\n * and we only have on onError message\n * @param {object} clientthe client itself\n * @param {object} opts configuration\n * @param {object} ee Event Emitter\n * @param {object} nspGroup namespace keys\n * @return {array} [obj, opts, ee]\n */\nexport function setupNamespaceErrorListener(client, opts, ee, nspGroup) {\n return [\n objDefineProps(\n client,\n ON_ERROR_FN_NAME,\n function namespaceErrorCallbackHandler(namespaceErrorHandler) {\n if (isFunc(namespaceErrorHandler)) {\n // please note ON_ERROR_FN_NAME can add multiple listners\n for (let namespace in nspGroup) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ON_ERROR_FN_NAME), namespaceErrorHandler)\n }\n }\n }\n ),\n opts,\n ee\n ]\n}\n\n","// take out from the resolver-methods\nimport {\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n ON_LOGIN_FN_NAME\n} from 'jsonql-constants'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { injectToFn, chainFns, isString, objDefineProps, isFunc } from '../utils'\n\n\n/**\n * @UPDATE it might be better if we decoup the two http-client only emit a login event\n * Here should catch it and reload the ws client @TBC\n * break out from createAuthMethods to allow chaining call\n * @param {object} obj the main client object\n * @param {object} opts configuration\n * @param {object} ee event emitter\n * @return {array} [ obj, opts, ee ] what comes in what goes out\n */\nconst setupLoginHandler = (obj, opts, ee) => [\n injectToFn(obj, opts.loginHandlerName, function loginHandler(token) {\n if (token && isString(token)) {\n opts.log(`Received ${LOGIN_EVENT_NAME} with ${token}`)\n // @TODO add the interceptor hook\n return ee.$trigger(LOGIN_EVENT_NAME, [token])\n }\n // should trigger a global error instead @TODO\n throw new JsonqlValidationError(opts.loginHandlerName, `Unexpected token ${token}`)\n }),\n opts,\n ee\n]\n\n\n/**\n * break out from createAuthMethods to allow chaining call - final in chain\n * @param {object} obj the main client object\n * @param {object} opts configuration\n * @param {object} ee event emitter\n * @return {array} [ obj, opts, ee ] what comes in what goes out\n */\nconst setupLogoutHandler = (obj, opts, ee) => [\n injectToFn(obj, opts.logoutHandlerName, function logoutHandler(...args) {\n ee.$trigger(LOGOUT_EVENT_NAME, args)\n }),\n opts,\n ee\n]\n\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * Plus this will check if it's the private namespace that fired the event\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @return {array} [ obj, opts, ee] what comes in what goes out\n */\nconst setupOnLoginhandler = (obj, opts, ee) => [\n objDefineProps(obj, ON_LOGIN_FN_NAME, function onLoginCallbackHandler(onLoginCallback) {\n if (isFunc(onLoginCallback)) {\n // only one callback can registered with it, TBC\n // Should this be a $onlyOnce listener after the logout \n // we add it back? \n ee.$only(ON_LOGIN_FN_NAME, onLoginCallback)\n }\n }),\n opts,\n ee\n]\n\n// @TODO future feature setup switch user\n\n\n/**\n * Create auth related methods\n * @param {object} obj the client itself\n * @param {object} opts configuration\n * @param {object} ee Event Emitter\n * @return {array} [ obj, opts, ee ] what comes in what goes out\n */\nexport function setupAuthMethods(obj, opts, ee) {\n return chainFns(\n setupLoginHandler,\n setupLogoutHandler,\n setupOnLoginhandler\n )(obj, opts, ee)\n}\n","// this is a new method that will create several\n// intercom method also reverse listen to the server\n// such as disconnect (server issue disconnect)\nimport { injectToFn, chainFns } from '../utils'\nimport { \n CONNECT_EVENT_NAME,\n CONNECTED_EVENT_NAME,\n DISCONNECT_EVENT_NAME,\n CONNECTED_PROP_KEY\n} from 'jsonql-constants'\n\n/**\n * Set up the CONNECTED_PROP_KEY to the client\n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupConnectPropKey(client, opts, ee) {\n const { log } = opts \n log('[1] setupConnectPropKey')\n // we just inject a helloWorld method here\n // set up the init state of the connect\n client = injectToFn(client, CONNECTED_PROP_KEY , false, true)\n return [ client, opts, ee ]\n}\n\n\n/**\n * setup listener to the connect event \n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupConnectEvtListener(client, opts, ee) {\n // @TODO do what at this point?\n const { log } = opts \n\n log(`[2] setupConnectEvtListener`)\n\n ee.$on(CONNECT_EVENT_NAME, function(...args) {\n log(`setupConnectEvtListener pass and do nothing at the moment`, args)\n })\n \n return [client, opts, ee]\n}\n\n/**\n * setup listener to the connected event \n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupConnectedEvtListener(client, opts, ee) {\n const { log } = opts \n\n log(`[3] setupConnectedEvtListener`)\n\n ee.$on(CONNECTED_EVENT_NAME, function() {\n client[CONNECTED_PROP_KEY] = true\n // new action to take release the holded event queue \n const ctn = ee.$release()\n\n log(`CONNECTED_EVENT_NAME`, true, 'queue count', ctn)\n\n return {[CONNECTED_PROP_KEY]: true}\n })\n\n return [client, opts, ee]\n}\n\n/**\n * Listen to the disconnect event and set the property to the client \n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupDisconnectListener(client, opts, ee) {\n const { log } = opts \n\n log(`[4] setupDisconnectListener`)\n\n ee.$on(DISCONNECT_EVENT_NAME, function() {\n client[CONNECTED_PROP_KEY] = false\n log(`CONNECTED_EVENT_NAME`, false)\n\n return {[CONNECTED_PROP_KEY]: false}\n })\n\n return [client, opts, ee]\n}\n\n/**\n * disconnect action\n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n * @return {object} this is the final step to return the client\n */\nfunction setupDisconectAction(client, opts, ee) {\n const { disconnectHandlerName, log } = opts\n log(`[5] setupDisconectAction`)\n\n return injectToFn(\n client,\n disconnectHandlerName,\n function disconnectHandler(...args) {\n ee.$trigger(DISCONNECT_EVENT_NAME, args)\n }\n )\n}\n\n/**\n * this is the new method that setup the intercom handler\n * also this serve as the final call in the then chain to\n * output the client\n * @param {object} client the client\n * @param {object} opts configuration\n * @param {object} ee the event emitter\n * @return {object} client\n */\nexport function setupInterCom(client, opts, ee) {\n const fns = [\n setupConnectPropKey,\n setupConnectEvtListener,\n setupConnectedEvtListener,\n setupDisconnectListener,\n setupDisconectAction\n ]\n\n const executor = Reflect.apply(chainFns, null, fns)\n return executor(client, opts, ee)\n}\n","// The final step of the setup before it returns the client\nimport { setupInterCom } from './setup-intercom'\nimport { CONNECT_EVENT_NAME, SUSPEND_EVENT_PROP_KEY } from 'jsonql-constants'\n\n/**\n * The final step to return the client\n * @param {object} obj the client\n * @param {object} opts configuration\n * @param {object} ee the event emitter\n * @return {object} client\n */\nfunction setupFinalStep(obj, opts, ee) {\n \n let client = setupInterCom(obj, opts, ee)\n // opts.log(`---> The final step to return the ws-client <---`)\n // add some debug functions\n client.verifyEventEmitter = () => ee.is\n // we add back the two things into the client\n // then when we do integration, we run it in reverse,\n // create the ws client first then the host client\n client.eventEmitter = opts.eventEmitter\n client.log = opts.log\n\n // now at this point, we are going to call the connect event\n ee.$trigger(CONNECT_EVENT_NAME, [opts, ee]) // just passing back the entire opts object\n // also we can release the queue here \n if (opts[SUSPEND_EVENT_PROP_KEY] === true) {\n opts.$releaseNamespace()\n }\n\n return client\n}\n\n\nexport { setupFinalStep }\n","// resolvers generator\n// we change the interface to return promise from v1.0.3\n// this way we make sure the obj return is correct and timely\nimport { NSP_GROUP } from 'jsonql-constants'\nimport { chainFns } from '../utils'\n\nimport { generateResolvers } from './generator-methods'\nimport {\n setupOnReadyListener,\n setupNamespaceErrorListener\n} from './global-listener'\n\nimport { setupAuthMethods } from './setup-auth-methods'\n\nimport { setupFinalStep } from './setup-final-step'\n\n/**\n * prepare the methods\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {object} of resolvers\n * @public\n */\nexport function callersGenerator(opts, nspMap, ee) {\n let fns = [\n generateResolvers,\n setupOnReadyListener,\n setupNamespaceErrorListener\n ]\n if (opts.enableAuth) {\n // there is a problem here, when this is a public namespace\n // it should not have a login logout event attach to it\n fns.push(setupAuthMethods)\n }\n // we will always get back the [ obj, opts, ee ]\n // then we only return the obj (wsClient)\n // This has move outside of here, into the main method\n // the reason is we could switch around the sequence much easier\n fns.push(setupFinalStep)\n // stupid reaon!!!\n const executer = Reflect.apply(chainFns, null, fns)\n // run it\n return executer(opts, ee, nspMap[NSP_GROUP])\n}\n","// create options\nimport {\n checkConfigAsync,\n checkConfig\n} from 'jsonql-params-validator'\nimport {\n wsCoreCheckMap,\n wsCoreConstProps,\n socketCheckMap\n} from './defaults'\nimport {\n fixWss,\n getHostName,\n getEventEmitter,\n getNspInfoByConfig,\n getLogFn\n} from '../utils'\n\nimport {\n SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\n\n/**\n * We need this to find the socket server type\n * @param {*} config\n * @return {string} the name of the socket server if any\n */\nfunction checkSocketClientType(config) {\n return checkConfig(config, socketCheckMap)\n}\n\n/**\n * Create a combine checkConfig for the creating the combine client\n * @param {*} configCheckMap\n * @param {*} constProps\n * @param {boolean} [withInject=false] if we need to run the postCheckInjectOpts \n * @return {function} takes the user input config then resolve the configuration\n */\nfunction createCombineConfigCheck(configCheckMap, constProps, withInject = false) {\n const combineCheckMap = Object.assign({}, wsCoreCheckMap, configCheckMap)\n const combineConstProps = Object.assign({}, wsCoreConstProps, constProps)\n\n return function runCheckConfigAsync(config) { \n return checkConfigAsync(config, combineCheckMap, combineConstProps)\n .then(opts => withInject ? postCheckInjectOpts(opts) : opts)\n }\n}\n\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config user supply config\n * @param {object} defaultOptions for checking\n * @param {object} constProps user supply const props\n * @return {promise} resolve to the checked opitons\n */\nfunction checkConfiguration(config, defaultOptions, constProps) {\n const defaultCheckMap= Object.assign(wsCoreCheckMap, defaultOptions)\n const wsConstProps = Object.assign(wsCoreConstProps, constProps)\n\n return checkConfigAsync(config, defaultCheckMap, wsConstProps)\n}\n\n/**\n * Taking the `then` part from the method below\n * @param {object} opts\n * @return {promise} opts all done\n */\nfunction postCheckInjectOpts(opts) {\n \n return Promise.resolve(opts)\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n \n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // get the log function here\n opts.log = getLogFn(opts)\n\n opts.eventEmitter = getEventEmitter(opts)\n \n return opts\n })\n}\n\n/**\n * Don't want to make things confusing\n * Breaking up the opts process in one place\n * then generate the necessary parameter in another step\n * @2020-3-20 here we suspend operation by it's namespace first\n * Then in the framework part, after the connection establish we release\n * the queue\n * @param {object} opts checked --> merge --> injected\n * @return {object} {opts, nspMap, ee}\n */\nfunction createRequiredParams(opts) {\n const nspMap = getNspInfoByConfig(opts)\n const ee = opts.eventEmitter\n // @TODO here we are going to add suspend event to the namespace related methods\n const { log } = opts \n const { namespaces } = nspMap\n log(`namespaces`, namespaces)\n // next we loop the namespace and suspend all the events prefix with namespace \n if (opts[SUSPEND_EVENT_PROP_KEY] === true) {\n // we create this as a function then we can call it again \n opts.$suspendNamepsace = () => namespaces.forEach(namespace => ee.$suspendEvent(namespace))\n // then we create a new method to releas the queue \n // we prefix it with the $ to notify this is not a jsonql part methods\n opts.$releaseNamespace = () => ee.$release()\n // now run it \n opts.$suspendNamepsace()\n }\n \n return { opts, nspMap, ee }\n}\n\nexport {\n // properties\n wsCoreCheckMap,\n wsCoreConstProps,\n // functions\n checkConfiguration,\n postCheckInjectOpts,\n createRequiredParams,\n // this will just get export for integration\n checkSocketClientType,\n createCombineConfigCheck\n}\n","// the top level API\n// The goal is to create a generic method that will able to handle\n// any kind of clients\n// import { injectToFn } from 'jsonql-utils'\nimport { callersGenerator } from './callers'\nimport {\n checkConfiguration,\n postCheckInjectOpts,\n createRequiredParams\n} from './options'\n\n\n/**\n * 0.5.0 we break up the wsClientCore in two parts one without the config check\n * @param {function} setupSocketClientListener just make sure what it said it does\n * @return {function} to actually generate the client\n */\nexport function wsClientCoreAction(setupSocketClientListener) {\n /**\n * This is a breaking change, to continue the onion skin design\n * @param {object} config the already checked config\n * @return {promise} resolve the client\n */\n return function createClientAction(config = {}) {\n\n return postCheckInjectOpts(config)\n .then(createRequiredParams)\n .then(\n ({opts, nspMap, ee}) => setupSocketClientListener(opts, nspMap, ee)\n )\n .then(\n ({opts, nspMap, ee}) => callersGenerator(opts, nspMap, ee)\n )\n .catch(err => {\n console.error(`[jsonql-ws-core-client init error]`, err)\n })\n }\n}\n\n/**\n * The main interface which will generate the socket clients and map all events\n * @param {object} socketClientListerner this is the one method export by various clients\n * @param {object} [configCheckMap={}] we should do all the checking in the core instead of the client\n * @param {object} [constProps={}] add this to supply the constProps from the downstream client\n * @return {function} accept a config then return the wsClient instance with all the available API\n */\nexport function wsClientCore(socketClientListener, configCheckMap = {}, constProps = {}) {\n // we need to inject property to this client later\n return (config = {}) => checkConfiguration(config, configCheckMap, constProps)\n .then(\n wsClientCoreAction(socketClientListener)\n )\n}\n","// this use by client-event-handler\nimport { ON_ERROR_FN_NAME } from 'jsonql-constants'\nimport { createEvt } from '../utils'\n\n/**\n * trigger errors on all the namespace onError handler\n * @param {object} ee Event Emitter\n * @param {array} namespaces nsps string\n * @param {string} message optional\n * @return {void}\n */\nexport function triggerNamespacesOnError(ee, namespaces, message) {\n namespaces.forEach( namespace => {\n ee.$trigger(\n createEvt(namespace, ON_ERROR_FN_NAME), \n [{ message, namespace }]\n )\n })\n}\n\n/**\n * Handle the onerror callback \n * @param {object} ee event emitter \n * @param {string} namespace which namespace has error \n * @param {*} err error object\n * @return {void} \n */\nexport const handleNamespaceOnError = (ee, namespace, err) => {\n ee.$trigger(createEvt(namespace, ON_ERROR_FN_NAME), [err])\n}","// NOT IN USE AT THE MOMENT JUST KEEP IT HERE FOR THE TIME BEING \nimport {\n LOGOUT_EVENT_NAME,\n NOT_LOGIN_ERR_MSG,\n ON_ERROR_FN_NAME,\n ON_RESULT_FN_NAME,\n DISCONNECT_EVENT_NAME,\n SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\nimport { EMIT_EVT, DISCONNECTED_ERROR_MSG } from '../options/constants'\nimport { createEvt, clearMainEmitEvt } from '../utils'\nimport { triggerNamespacesOnError } from './trigger-namespaces-on-error'\n\n/**\n * A Event Listerner placeholder when it's not connect to any nsp\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nexport const notConnectedListener = (namespace, ee, opts) => {\n const { log } = opts \n\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function disconnectedEvtCallback(resolverName, args) {\n log(`[disconnectedListerner] hijack the ws call`, namespace, resolverName, args)\n // Now we suspend all the calls but note the existing one won't be affected \n // we need to update the methods to move everything across \n \n\n const error = {\n message: DISCONNECTED_ERROR_MSG\n }\n ee.$call(createEvt(namespace, resolverName, ON_ERROR_FN_NAME), [ error ])\n // also trigger the result Listerner, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [{ error }])\n }\n )\n}\n\n\n/**\n * The disconnect event Listerner, now we log the client out from everything\n * @TODO now we are another problem they disconnect, how to reconnect\n * @param {object} nsps the available nsp(s)\n * @param {array} namespaces available namespace \n * @param {object} ee eventEmitter \n * @param {object} opts configuration\n * @return {void}\n */\nexport const disconnectListener = (nsps, namespaces, ee, opts) => {\n const { log } = opts \n ee.$on(\n DISCONNECT_EVENT_NAME, \n function disconnectEvtCallback() {\n triggerNamespacesOnError(ee, namespaces, DISCONNECT_EVENT_NAME)\n namespaces.forEach( namespace => { \n log(`disconnect from ${namespace}`)\n\n clearMainEmitEvt(ee, namespace)\n nsps[namespace] = null \n disconnectedListerner(namespace, ee, opts)\n })\n }\n )\n}\n\n/**\n * A Event Listerner placeholder when it's not connect to the private nsp\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nexport const notLoginListener = (namespace, ee, opts) => {\n const { log } = opts \n\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function notLoginListernerCallback(resolverName, args) {\n log('[notLoginListerner] hijack the ws call', namespace, resolverName, args)\n const error = { message: NOT_LOGIN_ERR_MSG }\n // It should just throw error here and should not call the result\n // because that's channel for handling normal event not the fake one\n ee.$call(createEvt(namespace, resolverName, ON_ERROR_FN_NAME), [ error ])\n // also trigger the result Listerner, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [{ error }])\n }\n )\n}\n\n/**\n * Only when there is a private namespace then we bind to this event\n * @param {object} nsps the available nsp(s)\n * @param {array} namespaces available namespace \n * @param {object} ee eventEmitter \n * @param {object} opts configuration\n * @return {void}\n */\nexport const logoutEvtListener = (nsps, namespaces, ee, opts) => {\n const { log } = opts \n // this will be available regardless enableAuth\n // because the server can log the client out\n ee.$on(\n LOGOUT_EVENT_NAME, \n function logoutEvtCallback() {\n const privateNamespace = getPrivateNamespace(namespaces)\n log(`${LOGOUT_EVENT_NAME} event triggered`)\n // disconnect(nsps, opts.serverType)\n // we need to issue error to all the namespace onError Listerner\n triggerNamespacesOnError(ee, [privateNamespace], LOGOUT_EVENT_NAME)\n // rebind all of the Listerner to the fake one\n log(`logout from ${privateNamespace}`)\n\n clearMainEmitEvt(ee, privateNamespace)\n // we need to issue one more call to the server before we disconnect\n // now this is a catch 22, here we are not suppose to do anything platform specific\n // so that should fire before trigger this event\n // clear out the nsp\n nsps[privateNamespace] = null \n // add a NOT LOGIN error if call\n notLoginWsListerner(privateNamespace, ee, opts)\n }\n )\n}\n\n","// This is share between different clients so we export it\n// @TODO port what is in the ws-main-handler\n// because all the client side call are via the ee\n// and that makes it re-usable between different client setup\n\n/*\nInside the map call but we take it out for now and until the WebSocket version is fully working\nimport { SOCKET_IO } from '../options/constants'\n // @TODO need to double check this\n if (opts.serverType === SOCKET_IO) {\n let { nspGroup } = nspMap\n args.push(nspGroup[namespace])\n }\n*/\nimport { getPrivateNamespace } from 'jsonql-utils/src/namespace'\nimport { logoutEvtListener, notLoginListener } from './event-listeners'\n\n/**\n * centralize all the comm in one place\n * @param {function} bindSocketEventHandler binding the ee to ws --> this is the core bit\n * @param {object} nsps namespaced nsp\n * @return {void} nothing\n */\nexport function namespaceEventListener(bindSocketEventListener, nsps) {\n /**\n * BREAKING CHANGE instead of one flat structure\n * we return a function to accept the two\n * @param {object} opts configuration\n * @param {object} nspMap this is not in the opts\n * @param {object} ee Event Emitter instance\n * @return {array} although we return something but this is the last step and nothing to do further\n */\n return (opts, nspMap, ee) => {\n // since all these params already in the opts\n const { log } = opts\n const { namespaces } = nspMap\n // @1.1.3 add isPrivate prop to id which namespace is the private nsp\n // then we can use this prop to determine if we need to fire the ON_LOGIN_PROP_NAME event\n const privateNamespace = getPrivateNamespace(namespaces)\n\n // @TODO hook up the connectedEvtHandler somewhere\n\n return namespaces.map(namespace => {\n let isPrivate = privateNamespace === namespace\n log(namespace, ` --> ${isPrivate ? 'private': 'public'} nsp --> `, nsps[namespace] !== false)\n if (nsps[namespace]) {\n log('[call bindWsHandler]', isPrivate, namespace)\n\n let args = [namespace, nsps[namespace], ee, isPrivate, opts]\n // Finally we binding everything together\n Reflect.apply(bindSocketEventListener, null, args)\n \n } else {\n log(`binding notLoginWsHandler to ${namespace}`)\n // a dummy placeholder\n // @TODO but it should be a not connect handler\n // when it's not login (or fail) this should be handle differently\n notLoginListener(namespace, ee, opts)\n }\n if (isPrivate) {\n log(`Has private and add logoutEvtHandler`)\n logoutEvtListener(nsps, namespaces, ee, opts)\n }\n // just return something its not going to get use anywhere\n return isPrivate\n })\n }\n}\n","/*\nThis two client is the final one that gets call \nall it does is to create the url that connect to \nand actually trigger the connection and return the socket \ntherefore they are as generic as it can be\n*/\n\n/**\n * wrapper method to create a nsp without login\n * @param {string|boolean} namespace namespace url could be false\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspClient(namespace, opts) {\n const { hostname, wssPath, nspClient, log } = opts\n const url = namespace ? [hostname, namespace].join('/') : wssPath\n log(`createNspClient --> `, url)\n\n return nspClient(url, opts)\n}\n\n/**\n * wrapper method to create a nsp with token auth\n * @param {string} namespace namespace url\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspAuthClient(namespace, opts) {\n const { hostname, wssPath, token, nspAuthClient, log } = opts\n const url = namespace ? [hostname, namespace].join('/') : wssPath\n \n log(`createNspAuthClient -->`, url)\n\n if (token && typeof token !== 'string') {\n throw new Error(`Expect token to be string, but got ${token}`)\n }\n // now we need to get an extra options for framework specific method, which is not great\n // instead we just pass the entrie opts to the authClient \n\n return nspAuthClient(url, opts, token)\n}\n\nexport {\n createNspClient,\n createNspAuthClient\n}\n","// same with the invalid-token-error \n\n/*\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\n*/\n\nclass InvalidCharacterError extends Error {\n\n constructor(message) {\n this.message = message \n }\n\n get name() {\n return 'InvalidCharacterError'\n }\n}\n\nexport { InvalidCharacterError }","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\nimport { InvalidCharacterError } from './invalid-character-error'\n\n/**\n * Polyfill the non ASCII code \n * @param {*} input\n * @return {*} usable output \n */\nfunction atob(input) {\n var str = String(input).replace(/=+$/, '')\n if (str.length % 4 == 1) {\n throw new InvalidCharacterError(\"'atob' failed: The string to be decoded is not correctly encoded.\")\n }\n for (\n // initialize result and counters\n let bc = 0, bs, buffer, idx = 0, output = '';\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer)\n }\n return output\n}\n\n// polyfill the window object\ntry {\n typeof window !== 'undefined' && window.atob && window.atob.bind(window) || atob\n} catch(e) {}\n\nexport { atob }\n\n\n","// this method is re-use in several clients \n// therefore it's better to share here \nconst { \n TOKEN_PARAM_NAME, \n AUTH_HEADER,\n TOKEN_DELIVER_LOCATION_PROP_KEY, \n TOKEN_IN_URL,\n TOKEN_IN_HEADER,\n WS_OPT_PROP_KEY\n} = require('jsonql-constants')\n/**\n * extract the new options for authorization\n * @param {*} opts configuration\n * @return {string} the header option\n */\nexport function extractConfig(opts) {\n // we don't really need to do any validation here \n // because the opts should be clean before calling here\n return opts[TOKEN_DELIVER_LOCATION_PROP_KEY] || TOKEN_IN_URL\n}\n\n/**\n * prepare the url and options to the WebSocket\n * @param {*} url \n * @param {*} config \n * @param {*} [token = false] \n * @return {object} with url and opts key \n */\nexport function prepareConnectConfig(url, config, token = false) {\n if (token === false) {\n return {\n url, \n opts: config[WS_OPT_PROP_KEY] || {}\n }\n }\n\n const tokenOpt = extractConfig(config, token)\n switch (tokenOpt) {\n case TOKEN_IN_URL:\n return {\n url: `${url}?${TOKEN_PARAM_NAME}=${token}`,\n opts: config[WS_OPT_PROP_KEY] || {}\n }\n case TOKEN_IN_HEADER:\n return {\n url,\n opts: Object.assign({}, config[WS_OPT_PROP_KEY] || {}, {\n headers: {\n [AUTH_HEADER]: token\n }\n })\n }\n default: \n }\n}\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false\n}\n\nexport default checkIsString\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber\n case STRING_TYPE:\n return checkIsString\n case BOOLEAN_TYPE:\n return checkIsBoolean\n default:\n return checkIsAny\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length\n}\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError'\n }\n}\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\n// import checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n }\n if (optional === true) {\n base[OPTIONAL_KEY] = true\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias\n }\n return base\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__'\n\n/**\n * construct the actual end user method, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfigAsync = function(validateSync) {\n /**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n/**\n * copy of above but it's sync, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n getCheckConfigAsync,\n getCheckConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\nimport * as validator from './src/validator'\n// configuration checking\nimport * as jsonqlOptions from './src/options'\n// the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nconst isObject = checkIsObject\nconst isAny = checkIsAny\nconst isString = checkIsString\nconst isBoolean = checkIsBoolean\nconst isNumber = checkIsNumber\nconst isArray = checkIsArray\nconst isNotEmpty = notEmpty\n\nconst normalizeArgs = validator.normalizeArgs\nconst validateSync = validator.validateSync\nconst validateAsync = validator.validateAsync\n\nconst JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO\n\nconst createConfig = jsonqlOptions.createConfig\nconst constructConfig = jsonqlOptions.constructConfigFn\n// construct the final output 1.5.2\nconst checkConfigAsync = jsonqlOptions.getCheckConfigAsync(validator.validateSync)\nconst checkConfig = jsonqlOptions.getCheckConfig(validator.validateSync)\n\nconst inArray = isInArray\nconst isObjectHasKey = isObjectHasKeyFn\n\n// check returns methods \nimport { \n checkReturns, \n checkReturnsAsync, \n checkResolverReturns, \n checkResolverReturnsAsync \n} from './src/returns'\n\n\n// group the in one \nexport {\n JSONQL_PARAMS_VALIDATOR_INFO,\n \n isObject,\n isAny,\n isString,\n isBoolean,\n isNumber,\n isArray,\n isNotEmpty,\n \n inArray,\n isObjectHasKey,\n\n normalizeArgs,\n validateSync,\n validateAsync,\n\n createConfig,\n constructConfig,\n checkConfig,\n checkConfigAsync,\n\n checkReturns, \n checkReturnsAsync, \n checkResolverReturns, \n checkResolverReturnsAsync\n}\n\n\n\n\n\n","// pass the different type of ws to generate the client\n// this is where the framework specific code get injected\n\nimport {\n createInitPing, \n extractPingResult,\n prepareConnectConfig\n} from '../modules'\n\n/**\n * Group the ping and get respond create new client in one\n * @param {object} ws \n * @param {object} WebSocket \n * @param {string} url\n * @param {function} resolver \n * @param {function} rejecter \n * @param {boolean} auth client or not\n * @return {promise} resolve the confirm client\n */\nfunction initPingAction(ws, WebSocket, url, wsOptions, resolver, rejecter) {\n\n return resolver(ws)\n\n // @TODO how to we id this client can issue a CSRF\n // by origin? \n ws.onopen = function onOpenCallback() {\n ws.send(createInitPing())\n }\n\n ws.onmessage = function onMessageCallback(payload) {\n try {\n const header = extractPingResult(payload.data)\n // @NOTE the break down test in ws-client-core show no problems\n // the problem was cause by malform nspInfo that time? \n \n setTimeout(() => { // delay or not show no different but just on the safe side\n ws.terminate()\n }, 50)\n const newWs = new WebSocket(url, Object.assign(wsOptions, header)) \n \n resolver(newWs) \n \n } catch(e) {\n rejecter(e)\n }\n }\n\n ws.onerror = function onErrorCallback(err) {\n rejecter(err)\n }\n}\n\n/**\n * less duplicated code the better \n * @param {object} WebSocket \n * @param {string} url formatted url\n * @param {object} options or not\n * @return {promise} resolve the actual verified client\n */\nfunction asyncConnect(WebSocket, url, options) {\n \n return new Promise((resolver, rejecter) => { \n const unconfirmClient = new WebSocket(url, options)\n \n return initPingAction(unconfirmClient, WebSocket, url, options, resolver, rejecter)\n })\n}\n\n/**\n * The bug was in the wsOptions where ws don't need it but socket.io do\n * therefore the object was pass as second parameter!\n * @NOTE here we only return a method to create the client, it might not get call \n * @param {object} WebSocket the client or node version of ws\n * @param {object} opts this is a breaking change we will init the client twice\n * @param {boolean} [auth = false] if it's auth then 3 param or just one\n * @return {function} the client method to connect to the ws socket server\n */\nfunction setupWebsocketClientFn(WebSocket, auth = false) {\n \n if (auth === false) {\n /**\n * Create a non-protected client\n * @param {string} uri already constructed url \n * @param {object} config from the ws-client-core this will be wsOptions taken out from opts \n * @return {promise} resolve to the confirmed client\n */\n return function createWsClient(uri, config) {\n // const { log } = config\n const { url, opts } = prepareConnectConfig(uri, config, false)\n\n // log(`createWsClient url: ${url} with opts:`, opts)\n\n return asyncConnect(WebSocket, url, opts)\n }\n }\n\n /**\n * Create a client with auth token\n * @param {string} uri start with ws:// @TODO check this?\n * @param {object} config this is the full configuration because we need something from it\n * @param {string} token the jwt token\n * @return {object} ws instance\n */\n return function createWsAuthClient(uri, config, token) {\n // const { log } = config\n const { url, opts } = prepareConnectConfig(uri, config, token)\n\n // log(`createWsAuthClient url: ${url} with opts:`, opts)\n\n return asyncConnect(WebSocket, url, opts)\n }\n}\n\nexport { setupWebsocketClientFn }","// @BUG when call disconnected\n// this keep causing an \"Disconnect call failed TypeError: Cannot read property 'readyState' of null\"\n// I think that is because it's not login then it can not be disconnect\n// how do we track this state globally\nimport { \n LOGIN_EVENT_NAME, \n CONNECT_EVENT_NAME \n} from 'jsonql-constants'\nimport { clearMainEmitEvt } from '../modules'\n\n/**\n * when we received a login event \n * from the http-client or the standalone login call \n * we received a token here --> update the opts then trigger \n * the CONNECT_EVENT_NAME again\n * @param {object} opts configurations\n * @param {object} nspMap contain all the required info\n * @param {object} ee event emitter\n * @return {void}\n */\nexport function loginEventListener(opts, nspMap, ee) {\n const { log } = opts\n const { namespaces } = nspMap\n\n log(`[4] loginEventHandler`)\n\n ee.$only(LOGIN_EVENT_NAME, function loginEventHandlerCallback(tokenFromLoginAction) {\n\n log('createClient LOGIN_EVENT_NAME $only handler')\n // clear out all the event binding\n clearMainEmitEvt(ee, namespaces)\n // reload the nsp and rebind all the events\n opts.token = tokenFromLoginAction \n ee.$trigger(CONNECT_EVENT_NAME, [opts, ee]) // don't need to pass the nspMap \n })\n}\n","// break it out on its own because\n// it's building from the lodash-es from scratch\n// according to this discussion https://github.com/lodash/lodash/issues/3298\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport merge from 'lodash-es/merge'\n\n/**\n * previously we already make sure the order of the namespaces\n * and attach the auth client to it\n * @param {array} promises array of unresolved promises\n * @param {boolean} asObject if true then merge the result object\n * @return {object} promise resolved with the array of promises resolved results\n */\nexport function chainPromises(promises, asObject = false) {\n return promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResults => (\n currentTask.then(currentResult => (\n asObject === false ? [...chainResults, currentResult] : merge(chainResults, currentResult)\n ))\n ))\n ), Promise.resolve(\n asObject === false ? [] : (isPlainObject(asObject) ? asObject : {})\n ))\n}\n\n\n/**\n * This one return a different result from the chainPromises\n * it will be the same like chainFns that take one promise resolve as the next fn parameter\n * @param {function} initPromise a function that accept param and resolve result\n * @param {array} promises array of function pass that resolve promises\n * @return {promise} resolve the processed result\n */\nexport function chainProcessPromises(initPromise, ...promises) {\n return (...args) => (\n promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResult => (\n currentTask(chainResult)\n )\n )\n ), Reflect.apply(initPromise, null, args))\n )\n}\n","// actually binding the event client to the socket client\nimport {\n createNspClient,\n createNspAuthClient\n} from './modules'\nimport {\n chainPromises \n} from 'jsonql-utils/src/chain-promises'\n\n/**\n * Because the nsps can be throw away so it doesn't matter the scope\n * this will get reuse again\n * @NOTE when we enable the standalone method this sequence will not change \n * only call and reload\n * @param {object} opts configuration\n * @param {object} nspMap from contract\n * @param {string|null} token whether we have the token at run time\n * @return {promise} resolve the nsps namespace with namespace as key\n */\nconst createNsp = function(opts, nspMap, token = null) {\n // we leave the token param out because it could get call by another method\n token = token || opts.token \n let { publicNamespace, namespaces } = nspMap\n const { log } = opts \n log(`createNspAction`, 'publicNamespace', publicNamespace, 'namespaces', namespaces)\n \n // reverse the namespaces because it got stuck for some reason\n // const reverseNamespaces = namespaces.reverse()\n if (opts.enableAuth) {\n return chainPromises(\n namespaces.map((namespace, i) => {\n if (i === 0) {\n if (token) {\n opts.token = token\n log('create createNspAuthClient at run time')\n return createNspAuthClient(namespace, opts)\n }\n return Promise.resolve(false)\n }\n return createNspClient(namespace, opts)\n })\n )\n .then(results => \n results.map((result, i) => \n ({ [namespaces[i]]: result }))\n .reduce((a, b) => Object.assign(a, b), {})\n )\n }\n\n return createNspClient(false, opts)\n .then(nsp => ({[publicNamespace]: nsp}))\n}\n\nexport { createNsp }\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg]\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @param {boolean} [t=true] or throw\n * @return {*} json object on success\n */\nexport const parseJson = function(n, t=true) {\n try {\n return JSON.parse(n)\n } catch(e) {\n if (t) {\n return n\n }\n throw new Error(e)\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = n => {\n if (typeof n === 'string') {\n return parseJson(n)\n }\n return parseJson(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== ''\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n\n/**\n * Shorthand method for Object.assign \n * @param {array} args \n * @return {object} merge together object by key \n */\nexport const assign = (...args) => Reflect.apply(Object.assign, Object, args)\n \n/** \n * generic placeholder function\n * @return {boolean} false \n */\nexport const nil = () => false\n\n/**\n * generic turn config into immutatble \n */\nexport const freeze = config => Object.freeze(config)","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time\n}\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\n\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isString from 'lodash-es/isString'\nimport isPlainObject from 'lodash-es/isPlainObject'\n\nimport { timestamp } from './timestamp'\nimport { parseJson } from './generic'\n\n/**\n * check if the payload has a timestamp field, then append a new timestamp to it\n * @param {object} payload from the com\n * @return {array} timestamp field with an array value\n */\nexport const handleTimestamp = payload => {\n let ts = payload[TIMESTAMP_PARAM_NAME]\n if (!isArray(ts)) {\n ts = [ts]\n }\n ts.push( timestamp() )\n\n return ts\n}\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? parseJson(payload) : payload\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * extract the resolver name from the payload \n * @param {object} payload\n * @return {string} resolver name \n */\nexport function getResolverFromPayload(payload) {\n const keys = Object.keys(payload)\n return keys.filter(key => key !== TIMESTAMP_PARAM_NAME)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName name of the resolver\n * @param {*} payload what is sending \n * @param {object} extra additonal property we want to merge into the deliverable\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload, extra = {}) {\n return Object.assign({\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }, extra)\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError('utils:params-api:createQuery', { \n message: `expect resolverName to be string and args to be array!`,\n resolverName, \n args \n })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getResolverFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// There are the socket related methods ported back from \n// ws-server-core and ws-client-core \nimport {\n WS_REPLY_TYPE,\n WS_EVT_NAME,\n WS_DATA_NAME,\n TIMESTAMP_PARAM_NAME,\n ERROR_KEY,\n EMIT_REPLY_TYPE,\n EMIT_SEND_TYPE,\n ACKNOWLEDGE_REPLY_TYPE\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlValidationError } from 'jsonql-errors' \nimport isString from 'lodash-es/isString'\nimport isArray from 'lodash-es/isArray'\n\nimport { createDeliverable, formatPayload } from './params-api'\nimport { toJson, isObjectHasKey, nil } from './generic'\nimport { timestamp } from './timestamp'\n\nconst PAYLOAD_NOT_DECODED_ERR = 'payload can not decoded'\nconst WS_KEYS = [\n WS_REPLY_TYPE,\n WS_EVT_NAME,\n WS_DATA_NAME\n]\n\n/////////////////////////////////////\n// REPLY FROM SERVER //\n/////////////////////////////////////\n\n/**\n * This will be a event emit from the client using the send method \n * But we have to change the server to understand it\n * @param {string} resolverName name of resolver ot call \n * @param {array} args for the resolver\n * @param {boolean} str true then stringify it \n * @return {object} formatted payload\n */\nexport const createSendPayload = (resolverName, args, str = false) => {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n // the different is we add a additonal type in the payload \n const result = createDeliverable(resolverName, payload, {type: EMIT_SEND_TYPE})\n return str ? JSON.stringify(result) : result\n }\n throw new JsonqlValidationError(`utils:socket:createSendMsg`, { \n resolverName, \n args, \n message: 'expect resolverName to be string and args to be array!'\n })\n}\n\n/**\n * We need to find the TS field and take it out from the previous payload \n * otherwise it will keep on rolling into the structure which is not what we wanted\n * @param {object} data for inspection\n * @return {object} { data: for the data to use, TS if there is any }\n */\nconst getTsFieldFromData = (data) => {\n let obj = {[TIMESTAMP_PARAM_NAME]: [], data: {}}\n if (data[TIMESTAMP_PARAM_NAME]) {\n const ts = data[TIMESTAMP_PARAM_NAME]\n obj[TIMESTAMP_PARAM_NAME] = Array.isArray(ts) ? ts : [ts]\n delete data[TIMESTAMP_PARAM_NAME]\n } \n obj.data = data\n \n return obj\n}\n\n\n/**\n * The ws doesn't have a acknowledge callback like socket.io\n * so we have to DIY one for ws and other that doesn't have it\n * @param {string} type of reply\n * @param {string} resolverName which is replying\n * @param {*} data payload\n * @param {array} [ts= []] the last received ts, if any \n * @return {string} stringify json\n */\nexport const createWsReply = (type, resolverName, data, ts = []) => {\n const obj = getTsFieldFromData(toJson(data))\n ts = ts.concat(obj[TIMESTAMP_PARAM_NAME])\n if (!ts.length) {\n ts.push(timestamp())\n }\n return JSON.stringify({\n data: {\n [WS_REPLY_TYPE]: type,\n [WS_EVT_NAME]: resolverName,\n [WS_DATA_NAME]: obj.data \n },\n [TIMESTAMP_PARAM_NAME]: ts \n })\n}\n\n// extended function \nexport const createReplyMsg = (resolverName, data, ts = []) => (\n createWsReply(EMIT_REPLY_TYPE, resolverName, data, ts)\n)\n\nexport const createAcknowledgeMsg = (resolverName, data, ts = []) => (\n createWsReply(ACKNOWLEDGE_REPLY_TYPE, resolverName, data, ts)\n)\n\n/**\n * @param {string|object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nexport const isWsReply = payload => {\n const json = isString(payload) ? toJson(payload) : payload\n const { data } = json\n if (data) {\n let result = WS_KEYS.filter(key => isObjectHasKey(data, key))\n return (result.length === WS_KEYS.length) ? data : false\n }\n return false\n}\n\n/**\n * @param {string|object} data received data\n * @param {function} [cb=nil] this is for extracting the TS field or when it's error\n * @return {object} false on failed\n */\nexport const extractWsPayload = (payload, cb = nil) => {\n try {\n const json = toJson(payload)\n // now handle the data\n let _data\n if ((_data = isWsReply(json)) !== false) {\n // note the ts property is on its own \n cb('_data', _data)\n \n return {\n data: toJson(_data[WS_DATA_NAME]),\n resolverName: _data[WS_EVT_NAME],\n type: _data[WS_REPLY_TYPE]\n }\n }\n throw new JsonqlError(PAYLOAD_NOT_DECODED_ERR, payload)\n } catch(e) {\n return cb(ERROR_KEY, e)\n }\n}\n","// taken out from the bind-socket-event-handler \nimport { DISCONNECT_EVENT_NAME } from 'jsonql-constants'\nimport { createIntercomPayload } from '../modules'\n\n/**\n * This is the actual logout (terminate socket connection) handler \n * There is another one that is handle what should do when this happen \n * @param {object} ee eventEmitter\n * @param {object} ws the WebSocket instance\n * @return {void}\n */\nexport function disconnectEventListener(ee, ws) {\n // listen to the LOGOUT_EVENT_NAME when this is a private nsp\n ee.$on(DISCONNECT_EVENT_NAME, function closeEvtHandler() {\n try {\n // @TODO we need find a way to get the userdata\n ws.send(createIntercomPayload(LOGOUT_EVENT_NAME))\n log('terminate ws connection')\n ws.terminate()\n } catch(e) {\n console.error('ws.terminate error', e)\n }\n })\n}","// the WebSocket main handler\nimport {\n ACKNOWLEDGE_REPLY_TYPE,\n EMIT_REPLY_TYPE,\n ERROR_KEY,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME,\n ON_READY_FN_NAME,\n ON_LOGIN_FN_NAME,\n ON_ERROR_FN_NAME\n} from 'jsonql-constants'\nimport {\n createQueryStr,\n createEvt,\n extractWsPayload\n} from 'jsonql-utils/module'\nimport {\n handleNamespaceOnError\n} from '../modules'\nimport { \n disconnectEventListener\n} from './disconnect-event-listener'\n\n/**\n * in some edge case we might not even have a resolverName, then\n * we issue a global error for the developer to catch it\n * @param {object} ee event emitter\n * @param {string} namespace nsp\n * @param {string} resolverName resolver\n * @param {object} json decoded payload or error object\n * @return {undefined} nothing return\n */\nexport const errorTypeHandler = (ee, namespace, resolverName, json) => {\n let evt = [namespace]\n if (resolverName) {\n evt.push(resolverName)\n }\n evt.push(ON_ERROR_FN_NAME)\n let evtName = Reflect.apply(createEvt, null, evt)\n // test if there is a data field\n let payload = json.data || json\n ee.$trigger(evtName, [payload])\n}\n\n/**\n * Binding the event to socket normally\n * @param {string} namespace\n * @param {object} ws the nsp\n * @param {object} ee EventEmitter\n * @param {boolean} isPrivate to id if this namespace is private or not\n * @param {object} opts configuration\n * @return {object} promise resolve after the onopen event\n */\nexport function bindSocketEventHandler(namespace, ws, ee, isPrivate, opts) {\n const { log } = opts\n let onReadCalls = 2\n // setup the logut event listener \n // this will hear the event and actually call the ws.terminate\n if (isPrivate) {\n log('Private namespace', namespace, ' binding to the DISCONNECT ws.terminate')\n disconnectEventListener(ee, ws)\n }\n // log(`log test, isPrivate:`, isPrivate)\n // connection open\n ws.onopen = function onOpenCallback() {\n\n log('=== ws.onopen listened -->', namespace)\n // we just call the onReady\n ee.$trigger(ON_READY_FN_NAME, [namespace])\n // we only want to allow it get call twice (number of namespaces)\n --onReadCalls\n if (onReadCalls === 0) {\n ee.$off(ON_READY_FN_NAME)\n }\n\n // need an extra parameter here to id the private nsp\n if (isPrivate) {\n log(`isPrivate and fire the ${ON_LOGIN_FN_NAME}`)\n ee.$call(ON_LOGIN_FN_NAME)(namespace)\n }\n // add listener only after the open is called\n ee.$only(\n createEvt(namespace, EMIT_REPLY_TYPE),\n /**\n * actually send the payload to server\n * @param {string} resolverName\n * @param {array} args NEED TO CHECK HOW WE PASS THIS!\n */\n function wsMainOnEvtHandler(resolverName, args) {\n const payload = createQueryStr(resolverName, args)\n log('ws.onopen.send', resolverName, args, payload)\n\n ws.send(payload)\n }\n )\n }\n\n // reply\n // If we change it to the event callback style\n // then the payload will just be the payload and fucks up the extractWsPayload call @TODO\n ws.onmessage = function onMessageCallback(payload) {\n log(`ws.onmessage raw payload`, payload.data)\n \n // console.log(`on.message`, typeof payload, payload)\n try {\n // log(`ws.onmessage raw payload`, payload)\n // @TODO the payload actually contain quite a few things - is that changed?\n // type: message, data: data_send_from_server\n const json = extractWsPayload(payload.data)\n const { resolverName, type } = json\n\n log('Respond from server', type, json)\n\n switch (type) {\n case EMIT_REPLY_TYPE:\n let e1 = createEvt(namespace, resolverName, ON_MESSAGE_FN_NAME)\n let r = ee.$call(e1)(json)\n \n log(`EMIT_REPLY_TYPE`, e1, r)\n break\n case ACKNOWLEDGE_REPLY_TYPE:\n let e2 = createEvt(namespace, resolverName, ON_RESULT_FN_NAME)\n let x2 = ee.$call(e2)(json)\n\n log(`ACKNOWLEDGE_REPLY_TYPE`, e2, x2)\n break\n case ERROR_KEY:\n // this is handled error and we won't throw it\n // we need to extract the error from json\n log(`ERROR_KEY`)\n errorTypeHandler(ee, namespace, resolverName, json)\n break\n // @TODO there should be an error type instead of roll into the other two types? TBC\n default:\n // if this happen then we should throw it and halt the operation all together\n log('Unhandled event!', json)\n errorTypeHandler(ee, namespace, resolverName, json)\n // let error = {error: {'message': 'Unhandled event!', type}};\n // ee.$trigger(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [error])\n }\n } catch(e) {\n log(`ws.onmessage error`, e)\n errorTypeHandler(ee, namespace, false, e)\n }\n }\n // when the server close the connection\n ws.onclose = function onCloseCallback() {\n log('ws.onclose callback')\n // @TODO what to do with this\n // ee.$trigger(LOGOUT_EVENT_NAME, [namespace])\n }\n // add a onerror event handler here\n ws.onerror = function onErrorCallback(err) {\n // trigger a global error event\n log(`ws.onerror`, err)\n handleNamespaceOnError(ee, namespace, err)\n }\n \n // we don't bind the logut here and just return the ws \n return ws \n}\n","// take out from the bind-framework-to-jsonql \nimport { CONNECT_EVENT_NAME } from 'jsonql-constants'\nimport { createNsp } from '../create-nsp'\nimport { namespaceEventListener } from '../modules'\nimport { bindSocketEventHandler } from './bind-socket-event-handler'\n\n/**\n * This is the hard of establishing the connection and binding to the jsonql events \n * @param {*} nspMap \n * @param {*} ee event emitter\n * @param {function} log function to show internal \n * @return {void}\n */\nexport function connectEventListener(nspMap, ee, log) {\n log(`[2] setup the CONNECT_EVENT_NAME`)\n // this is a automatic trigger from within the framework\n ee.$only(CONNECT_EVENT_NAME, function connectEventNameHandler($config, $ee) {\n log(`[3] CONNECT_EVENT_NAME`, $ee)\n\n return createNsp($config, nspMap)\n .then(nsps => namespaceEventListener(bindSocketEventHandler, nsps))\n .then(listenerFn => listenerFn($config, nspMap, $ee))\n })\n\n // log(`[3] after setup the CONNECT_EVENT_NAME`)\n}","// share method to create the wsClientResolver\nimport { \n NSP_CLIENT, \n NSP_AUTH_CLIENT,\n ENABLE_AUTH_PROP_KEY\n} from 'jsonql-constants'\nimport { \n setupWebsocketClientFn \n} from './setup-websocket-client-fn'\nimport { \n loginEventListener, \n connectEventListener \n} from '../setup-socket-listeners'\n\n/**\n * Create the framework <---> jsonql client binding\n * @param {object} websocket the different WebSocket module\n * @return {function} the wsClientResolver\n */\nfunction setupConnectClient(websocket) {\n /**\n * wsClientResolver\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\n return function createClientBindingAction(opts, nspMap, ee) {\n const { log } = opts\n\n log(`There is problem here with passing the opts`, opts)\n // this will put two callable methods into the opts \n opts[NSP_CLIENT] = setupWebsocketClientFn(websocket)\n // we don't need this one unless enableAuth === true \n if (opts[ENABLE_AUTH_PROP_KEY] === true) {\n opts[NSP_AUTH_CLIENT] = setupWebsocketClientFn(websocket, true)\n } \n // debug \n log(`[1] bindWebsocketToJsonql`, ee.$name, nspMap)\n // @2020-03-20 @NOTE \n \n connectEventListener(nspMap, ee, log)\n \n // next we need to setup the login event handler\n // But the same design (see above) when we received a login event \n // from the http-client or the standalone login call \n // we received a token here --> update the opts then trigger \n // the CONNECT_EVENT_NAME again\n loginEventListener(opts, nspMap, ee)\n\n log(`just before returing the values for the next operation from createClientBindingAction`)\n\n // we just return what comes in\n return { opts, nspMap, ee }\n }\n}\n\nexport { setupConnectClient }","// this will be the news style interface that will pass to the jsonql-ws-client\n// then return a function for accepting an opts to generate the final\n// client api\nimport WebSocket from 'ws'\nimport { setupConnectClient } from '../core/setup-connect-client'\n\nconst setupSocketClientListener = setupConnectClient(WebSocket)\n\n/**\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\nexport {\n setupSocketClientListener\n} \n","// this is the module entry point for node client\nimport {\n wsClientCore\n} from './core/modules'\nimport { \n wsClientCheckMap,\n wsClientConstProps\n} from './options'\nimport { \n setupSocketClientListener \n} from './node/setup-socket-client-listener'\n\n// export back the function and that's it\nexport default function wsNodeClient(config = {}, constProps = {}) {\n \n return wsClientCore(\n setupSocketClientListener, \n wsClientCheckMap, \n Object.assign({}, wsClientConstProps, constProps)\n )(config)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;ACAA;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;ACAA;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/packages/@jsonql/ws/node.js b/packages/@jsonql/ws/node.js deleted file mode 100644 index 6e140d84a9a963237f733f1638b0f1ca6eea0f05..0000000000000000000000000000000000000000 --- a/packages/@jsonql/ws/node.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=(t=require("ws"))&&"object"==typeof t&&"default"in t?t.default:t,r={version:"version: 1.2.0 module: cjs-module",serverType:"ws"},n=Array.isArray,o="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},i="object"==typeof o&&o&&o.Object===Object&&o,a="object"==typeof self&&self&&self.Object===Object&&self,u=i||a||Function("return this")(),c=u.Symbol,s=Object.prototype,f=s.hasOwnProperty,l=s.toString,p=c?c.toStringTag:void 0;var h=Object.prototype.toString;var v=c?c.toStringTag:void 0;function g(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":v&&v in Object(t)?function(t){var e=f.call(t,p),r=t[p];try{t[p]=void 0;var n=!0}catch(t){}var o=l.call(t);return n&&(e?t[p]=r:delete t[p]),o}(t):function(t){return h.call(t)}(t)}function d(t,e){return function(r){return t(e(r))}}var y=d(Object.getPrototypeOf,Object);function _(t){return null!=t&&"object"==typeof t}var b=Function.prototype,m=Object.prototype,j=b.toString,w=m.hasOwnProperty,O=j.call(Object);function S(t){if(!_(t)||"[object Object]"!=g(t))return!1;var e=y(t);if(null===e)return!0;var r=w.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&j.call(r)==O}function E(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&P(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var H=function(t){return n(t)?t:[t]},K=function(t,e){void 0===e&&(e=!0);try{return JSON.parse(t)}catch(r){if(e)return t;throw new Error(r)}},Y=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},Q=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},X=function(t){return K("string"==typeof t?t:JSON.stringify(t))},Z=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},tt=function(){return!1},et=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,H(t))}),Reflect.apply(t,null,r))}};function rt(t,e){return t===e||t!=t&&e!=e}function nt(t,e){for(var r=t.length;r--;)if(rt(t[r][0],e))return r;return-1}var ot=Array.prototype.splice;function it(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},it.prototype.set=function(t,e){var r=this.__data__,n=nt(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function ut(t){if(!at(t))return!1;var e=g(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var ct,st=u["__core-js_shared__"],ft=(ct=/[^.]+$/.exec(st&&st.keys&&st.keys.IE_PROTO||""))?"Symbol(src)_1."+ct:"";var lt=Function.prototype.toString;function pt(t){if(null!=t){try{return lt.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ht=/^\[object .+?Constructor\]$/,vt=Function.prototype,gt=Object.prototype,dt=vt.toString,yt=gt.hasOwnProperty,_t=RegExp("^"+dt.call(yt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function bt(t){return!(!at(t)||(e=t,ft&&ft in e))&&(ut(t)?_t:ht).test(pt(t));var e}function mt(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return bt(r)?r:void 0}var jt=mt(u,"Map"),wt=mt(Object,"create");var Ot=Object.prototype.hasOwnProperty;var St=Object.prototype.hasOwnProperty;function Et(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Yt(t){return null!=t&&Kt(t.length)&&!ut(t)}var Qt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Xt=Qt&&"object"==typeof module&&module&&!module.nodeType&&module,Zt=Xt&&Xt.exports===Qt?u.Buffer:void 0,te=(Zt?Zt.isBuffer:void 0)||function(){return!1},ee={};ee["[object Float32Array]"]=ee["[object Float64Array]"]=ee["[object Int8Array]"]=ee["[object Int16Array]"]=ee["[object Int32Array]"]=ee["[object Uint8Array]"]=ee["[object Uint8ClampedArray]"]=ee["[object Uint16Array]"]=ee["[object Uint32Array]"]=!0,ee["[object Arguments]"]=ee["[object Array]"]=ee["[object ArrayBuffer]"]=ee["[object Boolean]"]=ee["[object DataView]"]=ee["[object Date]"]=ee["[object Error]"]=ee["[object Function]"]=ee["[object Map]"]=ee["[object Number]"]=ee["[object Object]"]=ee["[object RegExp]"]=ee["[object Set]"]=ee["[object String]"]=ee["[object WeakMap]"]=!1;var re,ne="object"==typeof exports&&exports&&!exports.nodeType&&exports,oe=ne&&"object"==typeof module&&module&&!module.nodeType&&module,ie=oe&&oe.exports===ne&&i.process,ae=function(){try{var t=oe&&oe.require&&oe.require("util").types;return t||ie&&ie.binding&&ie.binding("util")}catch(t){}}(),ue=ae&&ae.isTypedArray,ce=ue?(re=ue,function(t){return re(t)}):function(t){return _(t)&&Kt(t.length)&&!!ee[g(t)]};function se(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var fe=Object.prototype.hasOwnProperty;function le(t,e,r){var n=t[e];fe.call(t,e)&&rt(n,r)&&(void 0!==r||e in t)||Nt(t,e,r)}var pe=/^(?:0|[1-9]\d*)$/;function he(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&pe.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Ee);function xe(t,e){return ke(function(t,e,r){return e=Se(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Se(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Ae.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!at(r))return!1;var n=typeof e;return!!("number"==n?Yt(r)&&he(e,r.length):"string"==n&&e in r)&&rt(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0))},sr=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},fr=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ur(e)(t)})).length)})).length:e.length>e.filter((function(t){return!cr(r,t)})).length},lr=function(t,e){if(void 0===e&&(e=null),S(t)){if(!e)return!0;if(cr(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return void 0===r||(!1!==(e=sr(t))?!fr({arg:r},e):!ur(t)(r))})).length)})).length}return!1},pr=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(lr,null,a);case"array"===t:return!cr(e.arg);case!1!==(r=sr(t)):return!fr(e,r);default:return!ur(t)(e.arg)}},hr=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},vr=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!cr(e))throw new Ie("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!cr(t))throw console.info(t),new Ie("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?hr(t,a):t,index:r,param:a,optional:i}}));default:throw new Be("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!er(e)&&!(r.type.length>r.type.filter((function(e){return pr(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return pr(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},gr=d(Object.keys,Object),dr=Object.prototype.hasOwnProperty;function yr(t){return Yt(t)?ge(t):function(t){if(!It(t))return gr(t);var e=[];for(var r in Object(t))dr.call(t,r)&&"constructor"!=r&&e.push(r);return e}(t)}function _r(t,e){return t&&Ct(t,e,yr)}function br(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new kt;++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=2&r?new br:void 0;for(i.set(t,e),i.set(e,t);++f0){if(!1!==this.$get(t,!0)){var n=this.searchMapEvt(t);if(n.length){var o=n[0][3],i=(this.checkMaxStore(t,e),this);return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var a=i.getMaxStore(t),u=-1;if(a>0){var c=i.$call(t,o,r);if(Reflect.apply(c,i,e),-1===(u=i.checkMaxStore(t)))return i.$off(t),-1}return u}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,n))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var a=Array.from(i.get(t)),u=a.length,c=!1,s=0;s0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,r=t[3];return e=r,!!Rn.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var n=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',n),r.delete(t),n}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];var o=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||o.add(r)}else this.checkContentExist(r,o)||(this.logger("(addToStore) insert new",r),o.add(r));else o.add(r);return t.set(e,o),[t,o.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,this.logger("(addToLazyStore) size: "+u),u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Ln.set(this,t)},r.normalStore.get=function(){return Ln.get(this)},r.lazyStore.set=function(t){Dn.set(this,t)},r.lazyStore.get=function(){return Dn.get(this)},Object.defineProperties(e.prototype,r),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=null,this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(t){var e=function(t){switch(!0){case!0===qn(t):return t;case!0===Mn(t):return new RegExp(t);default:return!1}}(t);if(qn(e))return this.__pattern__=e,this.$suspend();throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof e+'" instead')},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];if(this.logger("($queue) get called"),!0===this.__suspend_state__){if(qn(this.__pattern__)){var n=this.__pattern__.test(t);if(!n)return!1}this.logger("($queue) added to $queue",e),this.queueStore.add([t].concat(e))}return!!this.__suspend_state__},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=null,this.logger("(release) was called with "+e+(r?' for "'+r+'"':"")+" item"+(e>1?"s":"")),e>0){var n=Array.from(this.queueStore);this.queueStore.clear(),this.logger("(release queue)",n),n.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(Jn))),Bn=function(t){function e(e){if("function"!=typeof e)throw new Error("Just die here the logger is not a function!");e("---\x3e Create a new EventEmitter <---"),t.call(this,{logger:e})}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"jsonql-ws-client-core"},Object.defineProperties(e.prototype,r),e}(In),Vn=function(t){var e=t.log,r=t.eventEmitter;return r?(e("eventEmitter is:",r.name),r):new Bn(t.log)},Wn=function(t){var e=t.toLowerCase();return e.indexOf("http")>-1?e.indexOf("https")>-1?e.replace("https","wss"):e.replace("http","ws"):e},Gn=function(t,e){H(e).forEach((function(e){t.$off(Q(e,"emit_reply"))}))};function Hn(t,e,r){Y(t,"error")?r(t.error):Y(t,"data")?Reflect.apply(e,null,[].concat(t.data)):r({message:"UKNNOWN RESULT!",error:t})}function Kn(t,e,r,n,o){void 0===n&&(n=[]);var i=Q(e,"emit_reply");return o("actionCall: "+i+" --\x3e "+r,n),t.$trigger(i,[r,H(n)]),new Promise((function(n,i){var a=Q(e,r,"onResult");t.$on(a,(function(t){o("got the first result",t),Hn(t,n,i)}))}))}var Yn=function(t,e,r,n,o,i){return Te(t,"send",tt,(function(){return i("running call getter method"),function(){for(var t=[],a=arguments.length;a--;)t[a]=arguments[a];return kn(t,o.params,!0).then((function(t){return i("execute send",r,n,t),Kn(e,r,n,t,i)})).catch((function(t){i("send error",t),e.$call(Q(r,n,"onError"),[new Ie(n,t)])}))}}))};function Qn(t,e,r,n,o){return function(){for(var i=[],a=arguments.length;a--;)i[a]=arguments[a];return kn(i,n.params,!0).then((function(n){return Kn(t,e,r,n,o)})).catch(We)}}var Xn=function(t,e,r,n,o,i){return[Pe(t,"myNamespace",r),e,r,n,o,i]},Zn=function(t,e,r,n,o,i){return[Te(t,"onResult",(function(t){Z(t)&&e.$on(Q(r,n,"onResult"),(function(o){Hn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(Q(r,n,"onError"),t)}))}))})),e,r,n,o,i]},to=function(t,e,r,n,o,i){return[Te(t,"onMessage",(function(t){if(Z(t)){e.$only(Q(r,n,"onMessage"),(function(o){i("onMessageCallback",o),Hn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(Q(r,n,"onError"),t)}))}))}})),e,r,n,o,i]},eo=function(t,e,r,n,o,i){return[Te(t,"onError",(function(t){Z(t)&&e.$only(Q(r,n,"onError"),t)})),e,r,n,o,i]};function ro(t,e,r,n,o,i){var a=[Xn,Zn,to,eo,Yn];return Reflect.apply(et,null,a)(n,o,t,e,r,i)}function no(t,e,r){var n=t.log,o={};for(var i in r){var a=r[i];for(var u in a){var c=a[u];o=Pe(o,u,ro(i,u,c,Qn(e,i,u,c,n),e,n))}}return[o,t,e,r]}function oo(t,e,r){return[Te(t,"onReady",(function(t){Z(t)&&r.$only("onReady",t)})),e,r]}function io(t,e,r,n){return[Te(t,"onError",(function(t){if(Z(t))for(var e in n)r.$on(Q(e,"onError"),t)})),e,r]}var ao,uo,co,so=function(t,e,r){return[Pe(t,e.loginHandlerName,(function(t){if(t&&$n(t))return e.log("Received __login__ with "+t),r.$trigger("__login__",[t]);throw new Ie(e.loginHandlerName,"Unexpected token "+t)})),e,r]},fo=function(t,e,r){return[Pe(t,e.logoutHandlerName,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__logout__",t)})),e,r]},lo=function(t,e,r){return[Te(t,"onLogin",(function(t){Z(t)&&r.$only("onLogin",t)})),e,r]};function po(t,e,r){return et(so,fo,lo)(t,e,r)}function ho(t,e,r){return(0,e.log)("[1] setupConnectPropKey"),[t=Pe(t,"connected",!1,!0),e,r]}function vo(t,e,r){var n=e.log;return n("[2] setupConnectEvtListener"),r.$on("__connect__",(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];n("setupConnectEvtListener pass and do nothing at the moment",t)})),[t,e,r]}function go(t,e,r){var n=e.log;return n("[3] setupConnectedEvtListener"),r.$on("__connected__",(function(){var e;t.connected=!0;var o=r.$release();return n("CONNECTED_EVENT_NAME",!0,"queue count",o),(e={}).connected=!0,e})),[t,e,r]}function yo(t,e,r){var n=e.log;return n("[4] setupDisconnectListener"),r.$on("__disconnect__",(function(){var e;return t.connected=!1,n("CONNECTED_EVENT_NAME",!1),(e={}).connected=!1,e})),[t,e,r]}function _o(t,e,r){var n=e.disconnectHandlerName;return(0,e.log)("[5] setupDisconectAction"),Pe(t,n,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__disconnect__",t)}))}function bo(t,e,r){var n=function(t,e,r){var n=[ho,vo,go,yo,_o];return Reflect.apply(et,null,n)(t,e,r)}(t,e,r);return n.verifyEventEmitter=function(){return r.is},n.eventEmitter=e.eventEmitter,n.log=e.log,r.$trigger("__connect__",[e,r]),!0===e.suspendOnStart&&e.$releaseNamespace(),n}var mo=["roundtip","handshake"],jo={};jo.standalone=xn(!1,["boolean"]),jo.debugOn=xn(!1,["boolean"]),jo.loginHandlerName=xn("login",["string"]),jo.logoutHandlerName=xn("logout",["string"]),jo.disconnectHandlerName=xn("disconnect",["string"]),jo.switchUserHandlerName=xn("switch-user",["string"]),jo.hostname=xn(!1,["string"]),jo.namespace=xn("jsonql",["string"]),jo.wsOptions=xn({},["object"]),jo.contract=xn({},["object"],((ao={}).checker=function(t){return!!function(t){return S(t)&&(Y(t,"query")||Y(t,"mutation")||Y(t,"socket"))}(t)&&t},ao)),jo.enableAuth=xn(!1,["boolean"]),jo.token=xn(!1,["string"]),jo.loginMethod=xn("handshake",["string"],((uo={}).enumv=mo,uo)),jo.useJwt=xn(!0,["boolean","string"]),jo.authStrKey=xn(null,["string"]),jo.suspendOnStart=xn(!1,["boolean"]);var wo={};wo.serverType=xn(null,["string"],((co={}).alias="socketClientType",co));var Oo=Object.assign(jo,wo),So={log:null,eventEmitter:null,nspClient:null,nspAuthClient:null,wssPath:"",publicNamespace:"public",privateNamespace:"private"};function Eo(t){return Promise.resolve(t).then((function(t){return t.hostname||(t.hostname=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new Ie(t)}}()),t.wssPath=Wn([t.hostname,t.namespace].join("/"),t.serverType),t.log=Pn(t),t.eventEmitter=Vn(t),t}))}function $o(t){var e=function(t){var e=t.contract,r=t.enableAuth,n=function(t){var e="jsonql";return t.enableAuth?[[e,t.privateNamespace].join("/"),[e,t.publicNamespace].join("/")]:[e]}(t),o=r?Qe(e):function(t,e){var r,n={};for(var o in t){var i=t[o];n[o]=i}return{size:1,nspGroup:(r={},r[e]=n,r),publicNamespace:e}}(e.socket,n[0]);return Object.assign(o,{namespaces:n})}(t),r=t.eventEmitter,n=t.log,o=e.namespaces;return n("namespaces",o),!0===t.suspendOnStart&&(t.$suspendNamepsace=function(){return o.forEach((function(t){return r.$suspendEvent(t)}))},t.$releaseNamespace=function(){return r.$release()},t.$suspendNamepsace()),{opts:t,nspMap:e,ee:r}}function ko(t){return function(e){return void 0===e&&(e={}),Eo(e).then($o).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return function(t,e,r){var n=[no,oo,io];return t.enableAuth&&n.push(po),n.push(bo),Reflect.apply(et,null,n)(t,r,e.nspGroup)}(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("[jsonql-ws-core-client init error]",t)}))}}function xo(t,e){var r=e.hostname,n=e.wssPath,o=e.wsOptions,i=e.nspClient,a=e.log,u=t?[r,t].join("/"):n;return a("createNspClient --\x3e ",u),i(u,o)}var Ao=function(t,e,r,n){var o=n.log;r.$on("__logout__",(function(){var i=getPrivateNamespace(e);o("__logout__ event triggered"),function(t,e,r){e.forEach((function(e){t.$trigger(Q(e,"onError"),[{message:r,namespace:e}])}))}(r,[i],"__logout__"),o("logout from "+i),Gn(r,i),t[i]=null,notLoginWsListerner(i,r,n)}))};function No(t,e){return function(r,n,o){var i=r.log,a=n.namespaces,u=function(t){return t.length>1&&t[0]}(a);return a.map((function(n){var c=u===n;if(i(n," --\x3e "+(c?"private":"public")+" nsp --\x3e ",!1!==e[n]),e[n]){i("[call bindWsHandler]",c,n);var s=[n,e[n],o,c,r];Reflect.apply(t,null,s)}else i("binding notLoginWsHandler to "+n),function(t,e,r){var n=r.log;e.$only(Q(t,"emit_reply"),(function(r,o){n("[notLoginListerner] hijack the ws call",t,r,o);var i={message:"NOT LOGIN"};e.$call(Q(t,r,"onError"),[i]),e.$call(Q(t,r,"onResult"),[{error:i}])}))}(n,o,r);return c&&(i("Has private and add logoutEvtHandler"),Ao(e,a,o,r)),c}))}}function To(t,e,r,n){var o=function(t,e){var r=Object.assign({},t,Oo),n=Object.assign({},e,So);return function(t){return An(t,r,n)}}(r,n);return function(r){return void 0===r&&(r={}),o(r).then((function(e){return t(e)})).then((function(t){var r=ko(e)(opts);return t.socket=r,t}))}}function Po(t,e,r,n,o,i){return t.onopen=function(){t.send(Ye("__intercom__",["__ping__",Ge()]))},t.onmessage=function(a){try{var u=tr(a.data);setTimeout((function(){t.terminate()}),50);var c=new e(r,Object.assign(i,u));n(c)}catch(t){o(t)}},t.onerror=function(t){o(t)},t}function Co(t,e,r){return new Promise((function(n,o){return Po(new t(e,r),t,e,n,o,r)}))}function zo(t,e,r){var n=r.log;return!1===e?function(e,r){void 0===r&&(r={});var o=Wn(e);return n("nspClient: \n"+o+"\n",r),Co(t,o,r)}:function(e,r,o){void 0===o&&(o={});var i=Wn(e),a=r&&"string"==typeof r?i+"?token="+r:i;return n("nspAuthClient: \n"+a+"\n",o),Co(t,a,o)}}var Ro="object"==typeof o&&o&&o.Object===Object&&o,qo="object"==typeof self&&self&&self.Object===Object&&self,Mo=Ro||qo||Function("return this")(),Fo=Mo.Symbol,Lo=Object.prototype,Do=Lo.hasOwnProperty,Jo=Lo.toString,Uo=Fo?Fo.toStringTag:void 0;var Io=Object.prototype.toString;var Bo=Fo?Fo.toStringTag:void 0;function Vo(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":Bo&&Bo in Object(t)?function(t){var e=Do.call(t,Uo),r=t[Uo];try{t[Uo]=void 0;var n=!0}catch(t){}var o=Jo.call(t);return n&&(e?t[Uo]=r:delete t[Uo]),o}(t):function(t){return Io.call(t)}(t)}var Wo=function(t,e){return function(r){return t(e(r))}}(Object.getPrototypeOf,Object);function Go(t){return null!=t&&"object"==typeof t}var Ho=Function.prototype,Ko=Object.prototype,Yo=Ho.toString,Qo=Ko.hasOwnProperty,Xo=Yo.call(Object);function Zo(t){if(!Go(t)||"[object Object]"!=Vo(t))return!1;var e=Wo(t);if(null===e)return!0;var r=Qo.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&Yo.call(r)==Xo}function ti(t,e){return t===e||t!=t&&e!=e}function ei(t,e){for(var r=t.length;r--;)if(ti(t[r][0],e))return r;return-1}var ri=Array.prototype.splice;function ni(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},ni.prototype.set=function(t,e){var r=this.__data__,n=ei(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function ii(t){if(!oi(t))return!1;var e=Vo(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var ai=Mo["__core-js_shared__"],ui=function(){var t=/[^.]+$/.exec(ai&&ai.keys&&ai.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();var ci=Function.prototype.toString;var si=/^\[object .+?Constructor\]$/,fi=Function.prototype,li=Object.prototype,pi=fi.toString,hi=li.hasOwnProperty,vi=RegExp("^"+pi.call(hi).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function gi(t){return!(!oi(t)||function(t){return!!ui&&ui in t}(t))&&(ii(t)?vi:si).test(function(t){if(null!=t){try{return ci.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function di(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return gi(r)?r:void 0}var yi=di(Mo,"Map"),_i=di(Object,"create");var bi=Object.prototype.hasOwnProperty;var mi=Object.prototype.hasOwnProperty;function ji(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Wi(t){return null!=t&&Vi(t.length)&&!ii(t)}var Gi="object"==typeof exports&&exports&&!exports.nodeType&&exports,Hi=Gi&&"object"==typeof module&&module&&!module.nodeType&&module,Ki=Hi&&Hi.exports===Gi?Mo.Buffer:void 0,Yi=(Ki?Ki.isBuffer:void 0)||function(){return!1},Qi={};Qi["[object Float32Array]"]=Qi["[object Float64Array]"]=Qi["[object Int8Array]"]=Qi["[object Int16Array]"]=Qi["[object Int32Array]"]=Qi["[object Uint8Array]"]=Qi["[object Uint8ClampedArray]"]=Qi["[object Uint16Array]"]=Qi["[object Uint32Array]"]=!0,Qi["[object Arguments]"]=Qi["[object Array]"]=Qi["[object ArrayBuffer]"]=Qi["[object Boolean]"]=Qi["[object DataView]"]=Qi["[object Date]"]=Qi["[object Error]"]=Qi["[object Function]"]=Qi["[object Map]"]=Qi["[object Number]"]=Qi["[object Object]"]=Qi["[object RegExp]"]=Qi["[object Set]"]=Qi["[object String]"]=Qi["[object WeakMap]"]=!1;var Xi="object"==typeof exports&&exports&&!exports.nodeType&&exports,Zi=Xi&&"object"==typeof module&&module&&!module.nodeType&&module,ta=Zi&&Zi.exports===Xi&&Ro.process,ea=function(){try{var t=Zi&&Zi.require&&Zi.require("util").types;return t||ta&&ta.binding&&ta.binding("util")}catch(t){}}(),ra=ea&&ea.isTypedArray,na=ra?function(t){return function(e){return t(e)}}(ra):function(t){return Go(t)&&Vi(t.length)&&!!Qi[Vo(t)]};function oa(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ia=Object.prototype.hasOwnProperty;function aa(t,e,r){var n=t[e];ia.call(t,e)&&ti(n,r)&&(void 0!==r||e in t)||$i(t,e,r)}var ua=/^(?:0|[1-9]\d*)$/;function ca(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&ua.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(ma);function Oa(t,e){return wa(function(t,e,r){return e=ba(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=ba(n.length-e,0),a=Array(i);++o1?r[o-1]:void 0,a=o>2?r[2]:void 0;for(i=t.length>3&&"function"==typeof i?(o--,i):void 0,a&&function(t,e,r){if(!oi(r))return!1;var n=typeof e;return!!("number"==n?Wi(r)&&ca(e,r.length):"string"==n&&e in r)&&ti(r[e],t)}(r[0],r[1],a)&&(i=o<3?void 0:i,o=1),e=Object(e);++n0;)e[r]=arguments[r+1];var n=Ge(),o=[t].concat(e);return o.push(n),Ye("__intercom__",o)}(LOGOUT_EVENT_NAME)),log("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var Fa=function(t,e,r,n){var o=[e];r&&o.push(r),o.push("onError");var i=Reflect.apply(ka,null,o),a=n.data||n;t.$trigger(i,[a])};function La(t,e,r,n,o){var i=o.log,a=2;return n&&(i("Private namespace",t," binding to the DISCONNECT ws.terminate"),Ma(r,e)),e.onopen=function(){i("=== ws.onopen listened --\x3e",t),r.$trigger("onReady",[t]),0===--a&&r.$off("onReady"),n&&(i("isPrivate and fire the onLogin"),r.$call("onLogin")(t)),r.$only(ka(t,"emit_reply"),(function(t,r){var n=function(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(za(t,e,r))}(t,r);i("ws.onopen.send",t,r,n),e.send(n)}))},e.onmessage=function(e){i("ws.onmessage raw payload",e.data);try{var n=function(t,e){void 0===e&&(e=Aa);try{var r,n=xa(t);if(!1!==(r=qa(n)))return e("_data",r),{data:xa(r.__data__),resolverName:r.__event__,type:r.__reply__};throw new Ta("payload can not decoded",t)}catch(t){return e("error",t)}}(e.data),o=n.resolverName,a=n.type;switch(i("Respond from server",a,n),a){case"emit_reply":var u=ka(t,o,"onMessage"),c=r.$call(u)(n);i("EMIT_REPLY_TYPE",u,c);break;case"emit_acknowledge":var s=ka(t,o,"onResult"),f=r.$call(s)(n);i("ACKNOWLEDGE_REPLY_TYPE",s,f);break;case"error":i("ERROR_KEY"),Fa(r,t,o,n);break;default:i("Unhandled event!",n),Fa(r,t,o,n)}}catch(e){i("ws.onmessage error",e),Fa(r,t,!1,e)}},e.onclose=function(){i("ws.onclose callback")},e.onerror=function(e){i("ws.onerror",e),function(t,e,r){t.$trigger(Q(e,"onError"),[r])}(r,t,e)},e}var Da,Ja,Ua=(Da=e,function(t,e,r){var n=t.log;return n("There is problem here with passing the opts",t),t.nspClient=zo(Da,!1,t),t.nspAuthClient=zo(Da,!0,t),n("[1] bindWebsocketToJsonql",r.name,e),function(t,e,r){r("[2] setup the CONNECT_EVENT_NAME"),e.$only("__connect__",(function(e,n){return r("[3] CONNECT_EVENT_NAME",n),Ea(e,t).then((function(t){return No(La,t)})).then((function(r){return r(e,t,n)}))}))}(e,r,n),function(t,e,r){var n=t.log,o=e.namespaces;n("[4] loginEventHandler"),r.$only("__login__",(function(e){n("createClient LOGIN_EVENT_NAME $only handler"),Gn(r,o),t.token=e,r.$trigger("__connect__",[t,r])}))}(t,e,r),n("just before returing the values for the next operation from createClientBindingAction"),{opts:t,nspMap:e,ee:r}}),Ia=(Ja=Ua,function(t,e,n){var o=Object.assign({},n,r);return To(t,Ja,e,o)});exports.EventEmitterClass=In,exports.checkSocketClientType=function(t){return Nn(t,wo)},exports.createCombineWsClient=Ia,exports.getEventEmitter=Vn; -//# sourceMappingURL=node.js.map diff --git a/packages/@jsonql/ws/node.js.map b/packages/@jsonql/ws/node.js.map deleted file mode 100644 index 712c46076e7cf2b8eec55df78edf3283dad5bf49..0000000000000000000000000000000000000000 --- a/packages/@jsonql/ws/node.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"node.js","sources":["../../ws-client-core/node_modules/lodash-es/_arraySome.js"],"sourcesContent":["/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n"],"names":["SetCache"],"mappings":"uwxBAAAA"} \ No newline at end of file diff --git a/packages/@jsonql/ws/package.json b/packages/@jsonql/ws/package.json index dd00fe3f5d4e38a6513fd846b1e7792cb8ede3ae..bd731d826f55c9af55700bed0d09e3badad81680 100644 --- a/packages/@jsonql/ws/package.json +++ b/packages/@jsonql/ws/package.json @@ -2,17 +2,18 @@ "name": "@jsonql/ws", "version": "1.2.0", "description": "jsonql WS (WebSocket) client module for browser / node", - "main": "main.js", + "main": "node-ws-client.js", "browser": "dist/jsonql-ws.umd.js", "module": "index.js", "files": [ "dist", "src", "index.js", - "main.js", - "main.js.map", - "node.js", - "node.js.map" + "module.js", + "node-ws-client.js", + "node-ws-client.js.map", + "node-module.js", + "node-module.js.map" ], "scripts": { "test": "ava", @@ -31,7 +32,7 @@ "test:basic": "npm run build:cjs && DEBUG=jsonql-ws-* ava ./tests/ws-client-basic.test.js", "test:auth": "npm run build:cjs && DEBUG=jsonql-ws-* ava ./tests/ws-client-auth.test.js", "test:login": "npm run build:cjs && DEBUG=jsonql-ws* ava ./tests/ws-client-auth-login.test.js", - "test:chain": "npm run build:cjs && DEBUG=jsonql-ws-client* ava ./tests/ws-client-chain.test.js", + "test:chain": "npm run build:cjs && DEBUG=jsonql-ws-* ava ./tests/ws-client-chain.test.js", "test:int": "npm run build:cjs && DEBUG=jsonql-ws* ava ./tests/integration.test.js", "test:conn": "npm run build:cjs && DEBUG=jsonql-ws-* ava ./tests/connect.test.js" }, @@ -48,7 +49,7 @@ "license": "ISC", "homepage": "jsonql.org", "dependencies": { - "jsonql-constants": "^2.0.14", + "jsonql-constants": "^2.0.16", "jsonql-errors": "^1.2.1", "jsonql-params-validator": "^1.6.2", "jsonql-utils": "^1.2.6", @@ -63,11 +64,11 @@ "glob": "^7.1.6", "jsonql-contract": "^1.9.1", "jsonql-koa": "^1.6.2", - "jsonql-ws-server": "^1.7.9", + "jsonql-ws-server": "^1.7.12", "kefir": "^3.8.6", "koa": "^2.11.0", "koa-bodyparser": "^4.3.0", - "rollup": "^2.2.0", + "rollup": "^2.3.0", "rollup-plugin-alias": "^2.2.0", "rollup-plugin-async": "^1.2.0", "rollup-plugin-buble": "^0.19.8", @@ -81,8 +82,7 @@ "rollup-plugin-replace": "^2.2.0", "rollup-plugin-serve": "^1.0.1", "rollup-plugin-terser": "^5.3.0", - "rollup-pluginutils": "^2.8.2", - "server-io-core": "^1.3.3" + "rollup-pluginutils": "^2.8.2" }, "ava": { "files": [ diff --git a/packages/@jsonql/ws/rollup.config.js b/packages/@jsonql/ws/rollup.config.js index f116a9ce2f48bfba5f80c5d2d9979ea9e5f65659..c1d48f8fbda685f1e7155ed2e3b3297adb120665 100644 --- a/packages/@jsonql/ws/rollup.config.js +++ b/packages/@jsonql/ws/rollup.config.js @@ -56,12 +56,12 @@ let inFile, outFile, _target switch (target) { case 'cjs': inFile = 'src/node-ws-client.js' - outFile = join(__dirname, 'main.js') + outFile = join(__dirname, 'node-ws-client.js') _target = 'cjs' break case 'cjs-module': inFile = 'src/node/module.js' - outFile = join(__dirname, 'node.js') + outFile = join(__dirname, 'node-module.js') _target = 'cjs' break case 'umd': diff --git a/packages/@jsonql/ws/src/browser-ws-client.js b/packages/@jsonql/ws/src/browser-ws-client.js index 9a48139b64ed4ca3152fede7226f104744be6249..b8dcbdc96bf0712b828f1872a3d838a4993fc31a 100644 --- a/packages/@jsonql/ws/src/browser-ws-client.js +++ b/packages/@jsonql/ws/src/browser-ws-client.js @@ -3,17 +3,19 @@ import { wsClientCore } from './core/modules' -import { wsClientConstProps } from './options' - - -import setupSocketClientListener from './core/setup-socket-client-listener' +import { + wsClientCheckMap, + wsClientConstProps +} from './options' +import { + setupSocketClientListener +} from './core/setup-socket-client-listener' // export back the function and that's it export default function wsBrowserClient(config = {}, constProps = {}) { - const initMethod = wsClientCore( + return wsClientCore( setupSocketClientListener, - {}, + wsClientCheckMap, Object.assign({}, wsClientConstProps, constProps) - ) - return initMethod(config) + )(config) } diff --git a/packages/@jsonql/ws/src/core/create-websocket-binding/index.js b/packages/@jsonql/ws/src/core/create-websocket-binding/index.js deleted file mode 100644 index c859f222e81477dd43d412167ce1e85f510253fb..0000000000000000000000000000000000000000 --- a/packages/@jsonql/ws/src/core/create-websocket-binding/index.js +++ /dev/null @@ -1,3 +0,0 @@ -import { bindWebsocketToJsonql } from './bind-websocket-to-jsonql' - -export default bindWebsocketToJsonql \ No newline at end of file diff --git a/packages/@jsonql/ws/src/core/modules.js b/packages/@jsonql/ws/src/core/modules.js index 51b50f8b1f50bee9b6397d6cc24110e393434bba..c9297666151bb12d2c27a37cce2699d773e4526b 100644 --- a/packages/@jsonql/ws/src/core/modules.js +++ b/packages/@jsonql/ws/src/core/modules.js @@ -9,14 +9,12 @@ import { wsClientCoreAction, // helper methods checkSocketClientType, - // construct url and call the nspClient - createNspClient, - createNspAuthClient, + + createCombineConfigCheck, triggerNamespacesOnError, handleNamespaceOnError, - fixWss, clearMainEmitEvt, getEventEmitter, EventEmitterClass, @@ -26,7 +24,12 @@ import { createInitPing, extractPingResult, - createIntercomPayload + createIntercomPayload, + + prepareConnectConfig, + + createNspClient, + createNspAuthClient } from '../../../../ws-client-core/index' // 'jsonql-ws-client-core' // export @@ -40,13 +43,11 @@ export { // helper methods checkSocketClientType, - createNspClient, - createNspAuthClient, + createCombineConfigCheck, triggerNamespacesOnError, handleNamespaceOnError, - fixWss, clearMainEmitEvt, getEventEmitter, EventEmitterClass, @@ -56,5 +57,10 @@ export { createInitPing, extractPingResult, - createIntercomPayload + createIntercomPayload, + + prepareConnectConfig, + + createNspClient, + createNspAuthClient } \ No newline at end of file diff --git a/packages/@jsonql/ws/src/core/setup-connect-client/index.js b/packages/@jsonql/ws/src/core/setup-connect-client/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9f78bf57e924a995ed2f1e51a397a6c1de13dbc8 --- /dev/null +++ b/packages/@jsonql/ws/src/core/setup-connect-client/index.js @@ -0,0 +1,4 @@ +// name what the folder is +import { setupConnectClient } from './setup-connect-client' + +export { setupConnectClient } \ No newline at end of file diff --git a/packages/@jsonql/ws/src/core/create-websocket-binding/bind-websocket-to-jsonql.js b/packages/@jsonql/ws/src/core/setup-connect-client/setup-connect-client.js similarity index 66% rename from packages/@jsonql/ws/src/core/create-websocket-binding/bind-websocket-to-jsonql.js rename to packages/@jsonql/ws/src/core/setup-connect-client/setup-connect-client.js index cc0093c111bfcc4d47dbd14cca28cf015422900b..1f6779f3f1f75d418b0b963b6f7137c575a42689 100644 --- a/packages/@jsonql/ws/src/core/create-websocket-binding/bind-websocket-to-jsonql.js +++ b/packages/@jsonql/ws/src/core/setup-connect-client/setup-connect-client.js @@ -1,17 +1,23 @@ // share method to create the wsClientResolver -import { NSP_CLIENT, NSP_AUTH_CLIENT } from 'jsonql-constants' -import { initWebSocketClient } from './init-websocket-client' +import { + NSP_CLIENT, + NSP_AUTH_CLIENT, + ENABLE_AUTH_PROP_KEY +} from 'jsonql-constants' +import { + setupWebsocketClientFn +} from './setup-websocket-client-fn' import { loginEventListener, connectEventListener -} from '../listeners' +} from '../setup-socket-listeners' /** * Create the framework <---> jsonql client binding - * @param {object} frameworkModule the different WebSocket module + * @param {object} websocket the different WebSocket module * @return {function} the wsClientResolver */ -function bindWebsocketToJsonql(frameworkModule) { +function setupConnectClient(websocket) { /** * wsClientResolver * @param {object} opts configuration @@ -23,9 +29,12 @@ function bindWebsocketToJsonql(frameworkModule) { const { log } = opts log(`There is problem here with passing the opts`, opts) - - opts[NSP_CLIENT] = initWebSocketClient(frameworkModule, opts) - opts[NSP_AUTH_CLIENT] = initWebSocketClient(frameworkModule, opts, true) + // this will put two callable methods into the opts + opts[NSP_CLIENT] = setupWebsocketClientFn(websocket) + // we don't need this one unless enableAuth === true + if (opts[ENABLE_AUTH_PROP_KEY] === true) { + opts[NSP_AUTH_CLIENT] = setupWebsocketClientFn(websocket, true) + } // debug log(`[1] bindWebsocketToJsonql`, ee.$name, nspMap) // @2020-03-20 @NOTE @@ -46,4 +55,4 @@ function bindWebsocketToJsonql(frameworkModule) { } } -export { bindWebsocketToJsonql } \ No newline at end of file +export { setupConnectClient } \ No newline at end of file diff --git a/packages/@jsonql/ws/src/core/create-websocket-binding/init-websocket-client.js b/packages/@jsonql/ws/src/core/setup-connect-client/setup-websocket-client-fn.js similarity index 66% rename from packages/@jsonql/ws/src/core/create-websocket-binding/init-websocket-client.js rename to packages/@jsonql/ws/src/core/setup-connect-client/setup-websocket-client-fn.js index 4194d9b55f183324823a5b3bf83f176bd8eac9f6..e504de193e98688379257458e53411bcd584ba14 100644 --- a/packages/@jsonql/ws/src/core/create-websocket-binding/init-websocket-client.js +++ b/packages/@jsonql/ws/src/core/setup-connect-client/setup-websocket-client-fn.js @@ -1,10 +1,10 @@ // pass the different type of ws to generate the client // this is where the framework specific code get injected -import { TOKEN_PARAM_NAME } from 'jsonql-constants' -import { fixWss } from '../modules' + import { createInitPing, - extractPingResult + extractPingResult, + prepareConnectConfig } from '../modules' /** @@ -17,7 +17,8 @@ import { * @param {boolean} auth client or not * @return {promise} resolve the confirm client */ -function initPingAction(ws, WebSocket, url, resolver, rejecter, wsOptions) { +function initPingAction(ws, WebSocket, url, wsOptions, resolver, rejecter) { + // @TODO how to we id this client can issue a CSRF // by origin? ws.onopen = function onOpenCallback() { @@ -29,11 +30,14 @@ function initPingAction(ws, WebSocket, url, resolver, rejecter, wsOptions) { const header = extractPingResult(payload.data) // @NOTE the break down test in ws-client-core show no problems // the problem was cause by malform nspInfo that time? + setTimeout(() => { // delay or not show no different but just on the safe side ws.terminate() }, 50) const newWs = new WebSocket(url, Object.assign(wsOptions, header)) + resolver(newWs) + } catch(e) { rejecter(e) } @@ -42,8 +46,6 @@ function initPingAction(ws, WebSocket, url, resolver, rejecter, wsOptions) { ws.onerror = function onErrorCallback(err) { rejecter(err) } - - return ws // just return it } /** @@ -58,11 +60,10 @@ function asyncConnect(WebSocket, url, options) { return new Promise((resolver, rejecter) => { const unconfirmClient = new WebSocket(url, options) - return initPingAction(unconfirmClient, WebSocket, url, resolver, rejecter, options) + return initPingAction(unconfirmClient, WebSocket, url, options, resolver, rejecter) }) } - /** * The bug was in the wsOptions where ws don't need it but socket.io do * therefore the object was pass as second parameter! @@ -72,38 +73,40 @@ function asyncConnect(WebSocket, url, options) { * @param {boolean} [auth = false] if it's auth then 3 param or just one * @return {function} the client method to connect to the ws socket server */ -function initWebSocketClient(WebSocket, opts, auth = false) { - const { log } = opts +function setupWebsocketClientFn(WebSocket, auth = false) { + if (auth === false) { /** * Create a non-protected client - * @param {string} url - * @param {object} [wsOptions={}] + * @param {string} uri already constructed url + * @param {object} config from the ws-client-core this will be wsOptions taken out from opts * @return {promise} resolve to the confirmed client */ - return function createWsClient(url, wsOptions = {}) { - const _url = fixWss(url) - log(`nspClient: \n${_url}\n`, wsOptions) + return function createWsClient(uri, config) { + // const { log } = config + const { url, opts } = prepareConnectConfig(uri, config, false) - return asyncConnect(WebSocket, _url, wsOptions) + // log(`createWsClient url: ${url} with opts:`, opts) + + return asyncConnect(WebSocket, url, opts) } } /** * Create a client with auth token - * @param {string} url start with ws:// @TODO check this? + * @param {string} uri start with ws:// @TODO check this? + * @param {object} config this is the full configuration because we need something from it * @param {string} token the jwt token - * @param {object} [wsOptions={}] extra options pass to the WebSocket object * @return {object} ws instance */ - return function createWsAuthClient(url, token, wsOptions = {}) { - const ws_url = fixWss(url) - // console.log('what happen here?', url, ws_url, token) - const _url = token && typeof token === 'string' ? `${ws_url}?${TOKEN_PARAM_NAME}=${token}` : ws_url - log(`nspAuthClient: \n${_url}\n`, wsOptions) + return function createWsAuthClient(uri, config, token) { + // const { log } = config + const { url, opts } = prepareConnectConfig(uri, config, token) + + // log(`createWsAuthClient url: ${url} with opts:`, opts) - return asyncConnect(WebSocket, _url, wsOptions) + return asyncConnect(WebSocket, url, opts) } } -export { initWebSocketClient } \ No newline at end of file +export { setupWebsocketClientFn } \ No newline at end of file diff --git a/packages/@jsonql/ws/src/core/setup-socket-client-listener.js b/packages/@jsonql/ws/src/core/setup-socket-client-listener.js index 63e551f145cb4638092a63ab1a3129d4de4d7ab4..c6e6fd0b00710e429a982822df66151153b3c1b1 100644 --- a/packages/@jsonql/ws/src/core/setup-socket-client-listener.js +++ b/packages/@jsonql/ws/src/core/setup-socket-client-listener.js @@ -1,15 +1,19 @@ -// rename from ws-client-resolver to create-ws-client - // this will be the news style interface that will pass to the jsonql-ws-client // then return a function for accepting an opts to generate the final // client api import WebSocket from './ws' -import createWebSocketBinding from './create-websocket-binding' +import { setupConnectClient } from './setup-connect-client' + +const setupSocketClientListener = setupConnectClient(WebSocket) /** + * We export it as a default and use the file name to id the function + * but it just way too confusing, therefore we change it to a name export * @param {object} opts configuration * @param {object} nspMap from the contract * @param {object} ee instance of the eventEmitter * @return {object} passing the same 3 input out with additional in the opts */ -export default createWebSocketBinding(WebSocket) \ No newline at end of file +export { + setupSocketClientListener +} diff --git a/packages/@jsonql/ws/src/core/listeners/bind-socket-event-handler.js b/packages/@jsonql/ws/src/core/setup-socket-listeners/bind-socket-event-handler.js similarity index 100% rename from packages/@jsonql/ws/src/core/listeners/bind-socket-event-handler.js rename to packages/@jsonql/ws/src/core/setup-socket-listeners/bind-socket-event-handler.js diff --git a/packages/@jsonql/ws/src/core/listeners/connect-event-listener.js b/packages/@jsonql/ws/src/core/setup-socket-listeners/connect-event-listener.js similarity index 100% rename from packages/@jsonql/ws/src/core/listeners/connect-event-listener.js rename to packages/@jsonql/ws/src/core/setup-socket-listeners/connect-event-listener.js index 80876dbdc3f02a67f6816f6e7b399f15d0390397..b0cc416c341a5698484614c20be098de5eec8ef7 100644 --- a/packages/@jsonql/ws/src/core/listeners/connect-event-listener.js +++ b/packages/@jsonql/ws/src/core/setup-socket-listeners/connect-event-listener.js @@ -1,7 +1,7 @@ // take out from the bind-framework-to-jsonql import { CONNECT_EVENT_NAME } from 'jsonql-constants' -import { namespaceEventListener } from '../modules' import { createNsp } from '../create-nsp' +import { namespaceEventListener } from '../modules' import { bindSocketEventHandler } from './bind-socket-event-handler' /** diff --git a/packages/@jsonql/ws/src/core/listeners/disconnect-event-listener.js b/packages/@jsonql/ws/src/core/setup-socket-listeners/disconnect-event-listener.js similarity index 100% rename from packages/@jsonql/ws/src/core/listeners/disconnect-event-listener.js rename to packages/@jsonql/ws/src/core/setup-socket-listeners/disconnect-event-listener.js diff --git a/packages/@jsonql/ws/src/core/listeners/disconnect.js b/packages/@jsonql/ws/src/core/setup-socket-listeners/disconnect.js similarity index 100% rename from packages/@jsonql/ws/src/core/listeners/disconnect.js rename to packages/@jsonql/ws/src/core/setup-socket-listeners/disconnect.js diff --git a/packages/@jsonql/ws/src/core/listeners/index.js b/packages/@jsonql/ws/src/core/setup-socket-listeners/index.js similarity index 100% rename from packages/@jsonql/ws/src/core/listeners/index.js rename to packages/@jsonql/ws/src/core/setup-socket-listeners/index.js diff --git a/packages/@jsonql/ws/src/core/listeners/login-event-listener.js b/packages/@jsonql/ws/src/core/setup-socket-listeners/login-event-listener.js similarity index 100% rename from packages/@jsonql/ws/src/core/listeners/login-event-listener.js rename to packages/@jsonql/ws/src/core/setup-socket-listeners/login-event-listener.js diff --git a/packages/@jsonql/ws/src/create-combine-client.js b/packages/@jsonql/ws/src/create-combine-client.js index de8c45bfdec800f289588a7c132d886f7f3d37ef..7f26267e59492bfff9c0ea3dc59c2dab5c22d7e0 100644 --- a/packages/@jsonql/ws/src/create-combine-client.js +++ b/packages/@jsonql/ws/src/create-combine-client.js @@ -3,6 +3,7 @@ // just pass the engine here to create the client import { + wsClientCheckMap, wsClientConstProps } from './options' import { @@ -14,10 +15,10 @@ import { /** * Overload the createCombineCreate to create a combine http / ws client - * @param {object} frameworkSocketEngine + * @param {object} setupSocketClientListener * @return {function} to accept config then generate the client */ -function createCombineWsClientConstructor(frameworkSocketEngine) { +function createCombineWsClientConstructor(setupSocketClientListener) { /** * @param {object} httpClientConstructor * @param {object} configCheckMap @@ -26,11 +27,12 @@ function createCombineWsClientConstructor(frameworkSocketEngine) { */ return function createCombineWsClient(httpClientConstructor, configCheckMap, constProps) { const localConstProps = Object.assign({}, constProps, wsClientConstProps) - + const localCheckMap = Object.assign({}, configCheckMap, wsClientCheckMap) + return createCombineClient( httpClientConstructor, - frameworkSocketEngine, - configCheckMap, + setupSocketClientListener, + localCheckMap, localConstProps ) } diff --git a/packages/@jsonql/ws/src/node-ws-client.js b/packages/@jsonql/ws/src/node-ws-client.js index 1e64c048b6dc6668e4c4bf443604f9e029c57c78..17432eebc1bf8eaf83690f4333703e1ae352a81a 100644 --- a/packages/@jsonql/ws/src/node-ws-client.js +++ b/packages/@jsonql/ws/src/node-ws-client.js @@ -2,16 +2,20 @@ import { wsClientCore } from './core/modules' -import { wsClientConstProps } from './options' - -import setupSocketClientListener from './node/setup-socket-client-listener' +import { + wsClientCheckMap, + wsClientConstProps +} from './options' +import { + setupSocketClientListener +} from './node/setup-socket-client-listener' // export back the function and that's it export default function wsNodeClient(config = {}, constProps = {}) { return wsClientCore( setupSocketClientListener, - {}, + wsClientCheckMap, Object.assign({}, wsClientConstProps, constProps) )(config) } diff --git a/packages/@jsonql/ws/src/node/module.js b/packages/@jsonql/ws/src/node/module.js index 49dcd495a431021ca0dd9a402397ead4b04e121a..acb23a30cc3d94f78dd211a71b2ff300f5d82c9b 100644 --- a/packages/@jsonql/ws/src/node/module.js +++ b/packages/@jsonql/ws/src/node/module.js @@ -1,4 +1,5 @@ // this is for node upstream client to include and construct their own client +// this will get build by rollup and becomes the node.js output import { createCombineWsClientConstructor, // straight export @@ -6,7 +7,7 @@ import { getEventEmitter, EventEmitterClass } from '../create-combine-client' -import setupSocketClientListener from './setup-socket-client-listener' +import { setupSocketClientListener } from './setup-socket-client-listener' const createCombineWsClient = createCombineWsClientConstructor(setupSocketClientListener) diff --git a/packages/@jsonql/ws/src/node/setup-socket-client-listener.js b/packages/@jsonql/ws/src/node/setup-socket-client-listener.js index cf9d0a27a735c9f133a5d07b32aeceaee0ac88a5..13a265e5c75cae411cff7fff32dc95f60c4c4f4f 100644 --- a/packages/@jsonql/ws/src/node/setup-socket-client-listener.js +++ b/packages/@jsonql/ws/src/node/setup-socket-client-listener.js @@ -2,7 +2,9 @@ // then return a function for accepting an opts to generate the final // client api import WebSocket from 'ws' -import createWebSocketBinding from '../core/create-websocket-binding' +import { setupConnectClient } from '../core/setup-connect-client' + +const setupSocketClientListener = setupConnectClient(WebSocket) /** * @param {object} opts configuration @@ -10,4 +12,6 @@ import createWebSocketBinding from '../core/create-websocket-binding' * @param {object} ee instance of the eventEmitter * @return {object} passing the same 3 input out with additional in the opts */ -export default createWebSocketBinding(WebSocket) +export { + setupSocketClientListener +} diff --git a/packages/@jsonql/ws/src/options/index.js b/packages/@jsonql/ws/src/options/index.js index 31b5a1e7e68b591a572cc9ff3a31b5081b374dde..c130ae4a7792e476ecd44756f027f8d645487a71 100644 --- a/packages/@jsonql/ws/src/options/index.js +++ b/packages/@jsonql/ws/src/options/index.js @@ -1,11 +1,36 @@ // jsonql-ws-core takes over the check configuration // here we only have to supply the options that is unique to this client // create options -import { JS_WS_NAME } from 'jsonql-constants' +import { + JS_WS_NAME, + ENUM_KEY, + TOKEN_DELIVER_LOCATION_PROP_KEY, + TOKEN_IN_URL, + TOKEN_IN_HEADER, + STRING_TYPE +} from 'jsonql-constants' +import { + createConfig +} from 'jsonql-params-validator' + +const AVAILABLE_PLACES = [ + TOKEN_IN_URL, + TOKEN_IN_HEADER +] + // constant props const wsClientConstProps = { version: '__PLACEHOLDER__', // will get replace serverType: JS_WS_NAME } -export { wsClientConstProps } +const wsClientCheckMap = { + [TOKEN_DELIVER_LOCATION_PROP_KEY]: createConfig(TOKEN_IN_URL, [STRING_TYPE], { + [ENUM_KEY]: AVAILABLE_PLACES + }) +} + +export { + wsClientCheckMap, + wsClientConstProps +} diff --git a/packages/@jsonql/ws/tests/fixtures/create-config.js b/packages/@jsonql/ws/tests/fixtures/create-config.js new file mode 100644 index 0000000000000000000000000000000000000000..a5c44129c875a4a121e69434bb993c85eb8ba490 --- /dev/null +++ b/packages/@jsonql/ws/tests/fixtures/create-config.js @@ -0,0 +1,35 @@ +// we need to create a configuration to do a break down test + +const { + createCombineConfigCheck, + // postCheckInjectOpts, + // createRequiredParams +} = require('../../src/core/modules') + +const { + wsClientCheckMap, + wsClientConstProps +} = require('../../src/options') + +const debug = require('debug')('jsonql-ws-client:fixtures/create-config') + +module.exports = function(config) { + + const constProps = Object.assign(wsClientConstProps, {log: debug}) + + const fn = createCombineConfigCheck( + wsClientCheckMap, + constProps, + true + ) + + return fn(config) + .then(opts => { + // debug('fixtures:createConfig', opts) + + return opts + }) + .catch(err => { + debug('init config error', err) + }) +} \ No newline at end of file diff --git a/packages/@jsonql/ws/tests/fixtures/server-setup.js b/packages/@jsonql/ws/tests/fixtures/server-setup.js index 6e63867935833533a44ffcb84238e2e89cadd704..dc3730879b409cd44fb9042c52f1a18e8ae55b81 100644 --- a/packages/@jsonql/ws/tests/fixtures/server-setup.js +++ b/packages/@jsonql/ws/tests/fixtures/server-setup.js @@ -1,20 +1,12 @@ -const http = require('http') -const fsx = require('fs-extra') + const { join } = require('path') -const debug = require('debug')('jsonql-ws-client:fixtures:server') -const { JSONQL_PATH } = require('jsonql-constants') -const colors = require('colors/safe') + const resolverDir = join(__dirname, 'resolvers') const contractDir = join(__dirname, 'contract') -// require('../../../ws-server') -const { jsonqlWsServer } = require('jsonql-ws-server') -// start -const server = http.createServer(function(req, res) { - res.writeHead(200, { 'Content-Type': 'text/plain' }) - res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2)) - res.end() -}) +const { jsonqlWsStandaloneServer } = require('../../../../ws-server') +// require('jsonql-ws-server') + module.exports = function(extra = {}) { const config = Object.assign({ @@ -23,14 +15,11 @@ module.exports = function(extra = {}) { serverType: 'ws' }, extra) - // extra.contract = extra.contract || contract; - return new Promise(resolver => { - jsonqlWsServer(config, server) - .then(io => { - resolver({ - io, + return jsonqlWsStandaloneServer(config, false) + .then(({ws, server}) => { + return { + io: ws, app: server - }) + } }) - }) } diff --git a/packages/@jsonql/ws/tests/integration.test.js b/packages/@jsonql/ws/tests/integration.test.js index 1535431ca8e370aaa9097270dafc3e8c825a2bcc..645a0e2781a206daaef5f322770660a4ed08779b 100644 --- a/packages/@jsonql/ws/tests/integration.test.js +++ b/packages/@jsonql/ws/tests/integration.test.js @@ -10,23 +10,27 @@ test.before(t => { debug(ee.name) }) -let ctn = 0 -const total = 130000 -function add20(base) { - let value = base*1.2 - ++ctn - if (value >= total) { - return ctn - } - return add20(value) -} + + + test(`How long does it take to reach 65million people`, t => { + + let ctn = 0 + const total = 130000 + function add20(base) { + let value = base*1.2 + ++ctn + if (value >= total) { + return ctn + } + return add20(value) + } + const days = add20(4000) - debug(`it will take ${days} days and ${total*0.044} died`) + debug(`it will take ${days} days and ${total*0.065} died`) t.pass() - }) diff --git a/packages/@jsonql/ws/tests/jwt/tokens.js b/packages/@jsonql/ws/tests/jwt/tokens.js new file mode 100644 index 0000000000000000000000000000000000000000..1232b7649f13f2de603fe73cd5f617df449811d6 --- /dev/null +++ b/packages/@jsonql/ws/tests/jwt/tokens.js @@ -0,0 +1,9 @@ + +const token1 = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9lbCIsImlhdCI6MTU4NTU4MDAxOX0.tcr0GvaZT2-24zp2ZddstwJXRHYgCxy1Xk2C5ooLPaV0vTT8A1tN-DEJBuWEWpJ-_WnehsbFwOvEBl_NnYsc-Z3n9SBZGw_20BpnfGoz2Ql0mPnPSHHf1VOxi5peK6wg1twM1GZ8rbPRk3Rz3ioGSTFX0CiVeVveaW-ztYOHh_k' + +const token2 = 'eyjhbgcioijsuzi1niisinr5cci6ikpxvcj9.eyjuyw1lijoism9lbcisimlhdci6mtu4ntu4mdaxox0.tcr0gvazt2-24zp2zddstwjxrhygcxy1xk2c5oolpav0vtt8a1tn-dejbuwewpj-_wnehsbfwovebl_nnysc-z3n9sbzgw_20bpnfgoz2ql0mpnpshhf1voxi5pek6wg1twm1gz8rbprk3rz3iogstfx0civevveaw-ztyohh_k' + +module.exports = { + token1, + token2 +} \ No newline at end of file diff --git a/packages/@jsonql/ws/tests/ws-client-auth-login.test.js b/packages/@jsonql/ws/tests/ws-client-auth-login.test.js index f2ffedf326a3e8a6d277ea61d0c7ad0e744088e3..be72dd07e54ab5bb85931c0ff47fddd19f55a957 100644 --- a/packages/@jsonql/ws/tests/ws-client-auth-login.test.js +++ b/packages/@jsonql/ws/tests/ws-client-auth-login.test.js @@ -3,7 +3,7 @@ const test = require('ava') const { join } = require('path') const fsx = require('fs-extra') const rainbow = require('./fixtures/rainbow') -const wsClient = require('../main') +const wsClient = require('../node-ws-client') const serverSetup = require('./fixtures/server-setup') const genToken = require('./fixtures/token') @@ -12,7 +12,7 @@ const contract = fsx.readJsonSync(join(contractDir, 'contract.json')) const publicContract = fsx.readJsonSync(join(contractDir, 'public-contract.json')) const { NOT_LOGIN_ERR_MSG } = require('jsonql-constants') -const payload = {name: 'Joel'}; +const payload = {name: 'Joel'} const _debug = require('debug') const debug = _debug('jsonql-ws-client:test:login') diff --git a/packages/@jsonql/ws/tests/ws-client-auth.test.js b/packages/@jsonql/ws/tests/ws-client-auth.test.js index daf424731376e03d4b9b0e563817e6c1bea4c426..275070ffc355cb9a7db073b0ec146ae12efcdfac 100644 --- a/packages/@jsonql/ws/tests/ws-client-auth.test.js +++ b/packages/@jsonql/ws/tests/ws-client-auth.test.js @@ -1,7 +1,7 @@ // standard ws client test without auth const test = require('ava') const EventClass = require('@to1source/event') -const modulePath = process.env.JSONQL_DEBUG ? '../node-org' : '../main' +const modulePath = process.env.JSONQL_DEBUG ? '../node-module' : '../node-ws-client' const wsClient = require(modulePath) const serverSetup = require('./fixtures/server-setup') diff --git a/packages/@jsonql/ws/tests/ws-client-basic.test.js b/packages/@jsonql/ws/tests/ws-client-basic.test.js index 0d807f466a9fdbfc5ace2f5e07d6c4d8b0a7319c..bb9a4119aa12bd679de2a4f68d736bbf38e62884 100644 --- a/packages/@jsonql/ws/tests/ws-client-basic.test.js +++ b/packages/@jsonql/ws/tests/ws-client-basic.test.js @@ -3,7 +3,7 @@ const test = require('ava') const { join } = require('path') const fsx = require('fs-extra') -const wsClient = require('../main') +const wsClient = require('../node-ws-client') const serverSetup = require('./fixtures/server-setup') const contractDir = join(__dirname, 'fixtures', 'contract') diff --git a/packages/@jsonql/ws/tests/ws-client-chain.test.js b/packages/@jsonql/ws/tests/ws-client-chain.test.js index c2f7a8503228c775971bd9d82add7113e8609be1..3fd6fc0fa8b44849b8043977eb5202f9d085568a 100644 --- a/packages/@jsonql/ws/tests/ws-client-chain.test.js +++ b/packages/@jsonql/ws/tests/ws-client-chain.test.js @@ -3,12 +3,13 @@ const test = require('ava') const { join } = require('path') const fsx = require('fs-extra') const { chainPromises } = require('jsonql-utils') -const { initWebSocketClient } = require('../src/core/create-websocket-binding/init-websocket-client') +const { setupWebsocketClientFn } = require('../src/core/setup-connect-client/setup-websocket-client-fn') +const createConfig = require('./fixtures/create-config') const WebSocket = require('ws') -const wsNodeAuthClient = initWebSocketClient(WebSocket, true) -const wsNodeClient = initWebSocketClient(WebSocket) +const wsNodeAuthClient = setupWebsocketClientFn(WebSocket, true) +const wsNodeClient = setupWebsocketClientFn(WebSocket) const serverSetup = require('./fixtures/server-setup') const genToken = require('./fixtures/token') @@ -16,9 +17,6 @@ const genToken = require('./fixtures/token') const contractDir = join(__dirname, 'fixtures', 'contract', 'auth') const contract = fsx.readJsonSync(join(contractDir, 'contract.json')) -// const publicContract = fsx.readJsonSync(join(contractDir, 'public-contract.json')) -// const { NOT_LOGIN_ERR_MSG } = require('jsonql-constants') - const payload = {name: 'Joel'} const token = genToken(payload) @@ -26,6 +24,7 @@ const rainbow = require('./fixtures/rainbow') const debug = require('debug')('jsonql-ws-client:test:ws-client-chain') const port = 8004 +// debug('wsNodeAuthClient', wsNodeAuthClient) test.before(async t => { const { app } = await serverSetup({ @@ -39,37 +38,68 @@ test.before(async t => { t.context.server = app.listen(port) - let baseUrl = `ws://localhost:${port}`; + let baseUrl = `ws://localhost:${port}` t.context.nsp1url = [baseUrl, 'jsonql/private'].join('/') t.context.nsp2url = [baseUrl, 'jsonql/public'].join('/') + // TBC + t.context.config = await createConfig({ + enableAuth: true, + debugOn: true, + hostname: baseUrl + }) }) -test.serial.cb('First test the connection individually', t => { +test.serial.cb.only('First test the connection individually', t => { t.plan(2) - let ws1 = wsNodeAuthClient(t.context.nsp1url, token) - let ws2 = wsNodeClient(t.context.nsp2url) + + const opts = t.context.config + + /* + let ws1 = wsNodeAuthClient(t.context.nsp1url, opts, token) ws1.onopen = function() { + + debug('ws1 onopen') + t.pass() ws1.terminate() } + */ - ws2.onopen = function() { - t.pass() - ws2.terminate() - t.end() - } + setTimeout(() => { + let ws2 = wsNodeClient(t.context.nsp2url, opts) + + debug(ws2) + + ws2.onopen = function() { + + debug('ws2 onopen') + + t.pass() + ws2.terminate() + t.end() + } + }, 100) + + + + + }) // @BUG whenever I wrap this code in the promise the ws just hang up // @TODO The bug still here after we port it over -test.serial.cb.only('Try to create a promise based ws client and using the chainPromises method to login', t => { +/* +test.serial.cb('Try to create a promise based ws client and using the chainPromises method to login', t => { t.plan(1) + + const opts = t.context.config + const { nsp1url, nsp2url } = t.context let p1 = () => ( new Promise((resolver, rejecter) => { - let ws1 = wsNodeAuthClient(nsp1url, token) + let ws1 = wsNodeAuthClient(nsp1url, opts, token) ws1.onerror = (err) => { rejecter(err) } @@ -80,7 +110,7 @@ test.serial.cb.only('Try to create a promise based ws client and using the chain ) let p2 = () => ( new Promise((resolver, rejecter) => { - let ws2 = wsNodeClient(nsp2url) + let ws2 = wsNodeClient(nsp2url, opts) ws2.onopen = () => { resolver(ws2) } @@ -109,3 +139,4 @@ test.serial.cb.only('Try to create a promise based ws client and using the chain }) }) +*/ \ No newline at end of file diff --git a/packages/constants/README.md b/packages/constants/README.md index 7051f88b4dda7001ed5fd277cd3295384085e71f..70bb0d6128e11b21ae47b7dda6aeabb74dc5a58a 100755 --- a/packages/constants/README.md +++ b/packages/constants/README.md @@ -203,7 +203,9 @@ Please consult the detail break down below. - ON_READY_FN_NAME - ON_LOGIN_FN_NAME - SEND_MSG_FN_NAME +- EMIT_MSG_FN_NAME - ON_MSG_FN_NAME +- TO_MSG_FN_NAME - CLIENT_PROP_NAME - USERDATA_PROP_NAME - EMIT_REPLY_TYPE diff --git a/packages/constants/browser.js b/packages/constants/browser.js index 0d6fdb4d0c573f1dd849f1e94ca8debee4b96c45..7827a6d0d27f868c6330d1c7da43a90d961feb0a 100644 --- a/packages/constants/browser.js +++ b/packages/constants/browser.js @@ -209,7 +209,9 @@ var jsonqlConstants = { "ON_READY_FN_NAME": "onReady", "ON_LOGIN_FN_NAME": "onLogin", "SEND_MSG_FN_NAME": "send", + "EMIT_MSG_FN_NAME": "emit", "ON_MSG_FN_NAME": "on", + "TO_MSG_FN_NAME": "to", "CLIENT_PROP_NAME": "client", "USERDATA_PROP_NAME": "userdata", "EMIT_REPLY_TYPE": "emit_reply", diff --git a/packages/constants/constants.json b/packages/constants/constants.json index 8c2fef986459e95d60b7bdd7b7c14f644aa88a38..e74c12a9ba92be9ec59f93d694fd9aab2d8a43fc 100644 --- a/packages/constants/constants.json +++ b/packages/constants/constants.json @@ -209,7 +209,9 @@ "ON_READY_FN_NAME": "onReady", "ON_LOGIN_FN_NAME": "onLogin", "SEND_MSG_FN_NAME": "send", + "EMIT_MSG_FN_NAME": "emit", "ON_MSG_FN_NAME": "on", + "TO_MSG_FN_NAME": "to", "CLIENT_PROP_NAME": "client", "USERDATA_PROP_NAME": "userdata", "EMIT_REPLY_TYPE": "emit_reply", diff --git a/packages/constants/index.js b/packages/constants/index.js index 403a34c7c79e9f786bf3b9ae0bd5a6f0d729eb85..92321f59f9b1ced31e1ced9ca5d569b935bcb768 100644 --- a/packages/constants/index.js +++ b/packages/constants/index.js @@ -319,7 +319,9 @@ export const ON_READY_FN_NAME = 'onReady' export const ON_LOGIN_FN_NAME = 'onLogin' // new @1.8.6 // the actual method name client.resolverName.send export const SEND_MSG_FN_NAME = 'send' +export const EMIT_MSG_FN_NAME = 'emit' // this is just an alias to send export const ON_MSG_FN_NAME = 'on' +export const TO_MSG_FN_NAME = 'to' // this one is for nodeClient inject into the resolver export const CLIENT_PROP_NAME = 'client' export const USERDATA_PROP_NAME = 'userdata' diff --git a/packages/constants/main.js b/packages/constants/main.js index 0c7444aff2ee21bd5e09cbe3a2d177e81b08da66..65969a001b647b7003d8d6df6254f965e90100fa 100644 --- a/packages/constants/main.js +++ b/packages/constants/main.js @@ -209,7 +209,9 @@ module.exports = { "ON_READY_FN_NAME": "onReady", "ON_LOGIN_FN_NAME": "onLogin", "SEND_MSG_FN_NAME": "send", + "EMIT_MSG_FN_NAME": "emit", "ON_MSG_FN_NAME": "on", + "TO_MSG_FN_NAME": "to", "CLIENT_PROP_NAME": "client", "USERDATA_PROP_NAME": "userdata", "EMIT_REPLY_TYPE": "emit_reply", diff --git a/packages/constants/package.json b/packages/constants/package.json index b7ae6811534c45aef36dc5a9b72818dc60d40816..c322861b171814e325622f4dd866dbdda3c2c862 100755 --- a/packages/constants/package.json +++ b/packages/constants/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-constants", - "version": "2.0.16", + "version": "2.0.17", "description": "All the share constants for jsonql modules", "main": "main.js", "module": "index.js", diff --git a/packages/constants/socket.js b/packages/constants/socket.js index 4e0487960f36c54e716dc95ea92bf6473ef80640..3341ce1501f496ac7280157bd9e1593f4bd9701e 100644 --- a/packages/constants/socket.js +++ b/packages/constants/socket.js @@ -57,7 +57,9 @@ export const ON_READY_FN_NAME = 'onReady' export const ON_LOGIN_FN_NAME = 'onLogin' // new @1.8.6 // the actual method name client.resolverName.send export const SEND_MSG_FN_NAME = 'send' +export const EMIT_MSG_FN_NAME = 'emit' // this is just an alias to send export const ON_MSG_FN_NAME = 'on' +export const TO_MSG_FN_NAME = 'to' // this one is for nodeClient inject into the resolver export const CLIENT_PROP_NAME = 'client' export const USERDATA_PROP_NAME = 'userdata' diff --git a/packages/koa/src/utils/auth-middleware-helpers.js b/packages/koa/src/utils/auth-middleware-helpers.js index 8b3d1b65c3e46e4063c5967358378333c2869e03..f327a2d40c634af87da49699d559bc3e15c36c0d 100644 --- a/packages/koa/src/utils/auth-middleware-helpers.js +++ b/packages/koa/src/utils/auth-middleware-helpers.js @@ -28,7 +28,7 @@ import { trim } from 'lodash' const debug = getDebug('auth-middleware-helpers') // this will create a cache version without keep calling the getter -var validatorFn; +var validatorFn // declare a global variable to store the userdata with null value // this way we don't mess up with the resolver have to check @@ -44,7 +44,7 @@ export const authHeaderParser = ctx => { let header = ctx.request.get(AUTH_CHECK_HEADER) // debug(_header, AUTH_CHECK_HEADER); // debug('Did we get the token?', header); - return header ? getToken(header) : false; + return header ? getToken(header) : false } /** diff --git a/packages/ws-client-core/index.js b/packages/ws-client-core/index.js index 88cd9ce8f862fe81e58baf7a6c6a20190df4549e..aad2bd18459b35787a5cdf0b05d439f012c17f79 100644 --- a/packages/ws-client-core/index.js +++ b/packages/ws-client-core/index.js @@ -6,14 +6,17 @@ import { import { wsCoreCheckMap, wsCoreConstProps, - checkSocketClientType + + checkSocketClientType, + + createCombineConfigCheck, + postCheckInjectOpts, + createRequiredParams } from './src/options' // these were in the share.js and now we combine into one import * as jsonqlWsConstants from './src/options/constants' import { - createNspClient, - createNspAuthClient, namespaceEventListener, triggerNamespacesOnError, handleNamespaceOnError @@ -22,8 +25,7 @@ import { import { EventEmitterClass, getEventEmitter, - clearMainEmitEvt, - fixWss + clearMainEmitEvt } from './src/utils' // new ping methods import { @@ -37,7 +39,13 @@ import { import { createCombineClient } from './src/create-combine-client' - +import { + createNspClient, + createNspAuthClient +} from './src/create-nsp-client' +import { + prepareConnectConfig +} from '@jsonql/security' // export export { // props @@ -50,15 +58,14 @@ export { // helper methods checkSocketClientType, - // from share.js - createNspClient, - createNspAuthClient, + // this is for testing + createCombineConfigCheck, + postCheckInjectOpts, + createRequiredParams, triggerNamespacesOnError, handleNamespaceOnError, - - fixWss, clearMainEmitEvt, getEventEmitter, EventEmitterClass, @@ -70,5 +77,10 @@ export { extractPingResult, createIntercomPayload, extractSrvPayload, - helloWorld + helloWorld, + + createNspClient, + createNspAuthClient, + + prepareConnectConfig } diff --git a/packages/ws-client-core/package.json b/packages/ws-client-core/package.json index 083a8376d31bef45a3f728213fbfa0d7d81c9e47..85ae6fe33a9a3d3743f52505b57df5c6596de115 100644 --- a/packages/ws-client-core/package.json +++ b/packages/ws-client-core/package.json @@ -13,6 +13,7 @@ "test": "ava ", "prepare": "npm run test", "update:version": "node ./build.js", + "test:config": "DEBUG=jsonql-ws* ava ./tests/config.test.js", "test:tbd": "DEBUG=jsonql-ws* ava ./tests/tbd.test.js", "test:exp": "DEBUG=jsonql-ws* ava ./tests/experiment.test.js", "test:event": "DEBUG=jsonql-ws* ava ./tests/event.test.js", @@ -55,8 +56,9 @@ "node": ">=8" }, "dependencies": { + "@jsonql/security": "^0.9.9", "@to1source/event": "^1.1.1", - "jsonql-constants": "^2.0.14", + "jsonql-constants": "^2.0.16", "jsonql-errors": "^1.2.1", "jsonql-params-validator": "^1.6.2", "jsonql-utils": "^1.2.6" @@ -66,8 +68,7 @@ "esm": "^3.2.25", "fs-extra": "^9.0.0", "jsonql-contract": "^1.9.1", - "jsonql-jwt": "^1.4.0", - "jsonql-ws-server": "^1.7.9", + "jsonql-ws-server": "^1.7.13", "kefir": "^3.8.6", "ws": "^7.2.3" }, diff --git a/packages/ws-client-core/src/auth/index.js b/packages/ws-client-core/src/auth/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1fb7ddf255031beb98146460cae08cd50b04d270 --- /dev/null +++ b/packages/ws-client-core/src/auth/index.js @@ -0,0 +1,2 @@ +// when this is running standalone mode then we need to +// provide the extra methods for it to store and retrieve the userdata \ No newline at end of file diff --git a/packages/ws-client-core/src/listener/create-nsp-clients.js b/packages/ws-client-core/src/create-nsp-client.js similarity index 60% rename from packages/ws-client-core/src/listener/create-nsp-clients.js rename to packages/ws-client-core/src/create-nsp-client.js index 4347eb6a29cf43ed530e4a32403c9e4806a3123b..0d5b086eac138d3282d02737d56c62aeaa98aef1 100644 --- a/packages/ws-client-core/src/listener/create-nsp-clients.js +++ b/packages/ws-client-core/src/create-nsp-client.js @@ -1,5 +1,9 @@ -// this is getting too confusing -// therefore we move it back to the framework specific +/* +This two client is the final one that gets call +all it does is to create the url that connect to +and actually trigger the connection and return the socket +therefore they are as generic as it can be +*/ /** * wrapper method to create a nsp without login @@ -8,11 +12,11 @@ * @return {object} ws client instance */ function createNspClient(namespace, opts) { - const { hostname, wssPath, wsOptions, nspClient, log } = opts + const { hostname, wssPath, nspClient, log } = opts const url = namespace ? [hostname, namespace].join('/') : wssPath log(`createNspClient --> `, url) - return nspClient(url, wsOptions) + return nspClient(url, opts) } /** @@ -22,7 +26,7 @@ function createNspClient(namespace, opts) { * @return {object} ws client instance */ function createNspAuthClient(namespace, opts) { - const { hostname, wssPath, token, wsOptions, nspAuthClient, log } = opts + const { hostname, wssPath, token, nspAuthClient, log } = opts const url = namespace ? [hostname, namespace].join('/') : wssPath log(`createNspAuthClient -->`, url) @@ -30,8 +34,10 @@ function createNspAuthClient(namespace, opts) { if (token && typeof token !== 'string') { throw new Error(`Expect token to be string, but got ${token}`) } - - return nspAuthClient(url, token, wsOptions) + // now we need to get an extra options for framework specific method, which is not great + // instead we just pass the entrie opts to the authClient + + return nspAuthClient(url, opts, token) } export { diff --git a/packages/ws-client-core/src/listener/index.js b/packages/ws-client-core/src/listener/index.js index e66be28bad1298bdf3870283a25fd1a8c6b2853b..5012252eb67dac22135ae538d7ef679b9eaaa0f3 100644 --- a/packages/ws-client-core/src/listener/index.js +++ b/packages/ws-client-core/src/listener/index.js @@ -1,8 +1,3 @@ -// moving it back because it's the same for two different framework -import { - createNspClient, - createNspAuthClient -} from './create-nsp-clients' // this one bind the framework engine and our event engine together import { namespaceEventListener @@ -16,8 +11,7 @@ import { // group all the import export in one place export { - createNspClient, - createNspAuthClient, + namespaceEventListener, triggerNamespacesOnError, handleNamespaceOnError diff --git a/packages/ws-client-core/src/options/defaults.js b/packages/ws-client-core/src/options/defaults.js index efc670d50dbbbdcff45eb5a09309137788c7ed06..4bb49c96aa8f5e5d90665e7469465db09263b82a 100644 --- a/packages/ws-client-core/src/options/defaults.js +++ b/packages/ws-client-core/src/options/defaults.js @@ -6,11 +6,10 @@ import { STRING_TYPE, BOOLEAN_TYPE, OBJECT_TYPE, - ENUM_KEY, + CHECKER_KEY, JSONQL_PATH, - IO_ROUNDTRIP_LOGIN, - IO_HANDSHAKE_LOGIN, + SOCKET_TYPE_CLIENT_ALIAS, ALIAS_KEY, @@ -34,15 +33,17 @@ import { ENABLE_AUTH_PROP_KEY, TOKEN_PROP_KEY, SUSPEND_EVENT_PROP_KEY, + + CSRF_PROP_KEY, + CSRF_HEADER_KEY, + USE_JWT_PROP_KEY, PUBLIC_KEY, - PRIVATE_KEY + PRIVATE_KEY, + } from 'jsonql-constants' -// import { AVAILABLE_SERVERS } from './constants' -const AVAILABLE_METHODS = [ - IO_ROUNDTRIP_LOGIN, - IO_HANDSHAKE_LOGIN -] + + const configCheckMap = { [STANDALONE_PROP_KEY]: createConfig(false, [BOOLEAN_TYPE]), // to turn on or off some of the features @@ -66,14 +67,16 @@ const configCheckMap = { [ENABLE_AUTH_PROP_KEY]: createConfig(false, [BOOLEAN_TYPE]), [TOKEN_PROP_KEY]: createConfig(false, [STRING_TYPE]), - // this is for socket.io - loginMethod: createConfig(IO_HANDSHAKE_LOGIN, [STRING_TYPE], {[ENUM_KEY]: AVAILABLE_METHODS}), + [CSRF_PROP_KEY]: createConfig(CSRF_HEADER_KEY, [STRING_TYPE]), // we will use this for determine the socket.io client type as well - @TODO remove or rename - useJwt: createConfig(true, [BOOLEAN_TYPE, STRING_TYPE]), + // [USE_JWT_PROP_KEY]: createConfig(true, [BOOLEAN_TYPE, STRING_TYPE]), // this is going to replace the use of useJwt === string next - authStrKey: createConfig(null, [STRING_TYPE]), + // @TODO remove this, use the interceptor to replace this options + // authStrKey: createConfig(null, [STRING_TYPE]), // this is experimental to see the effects, might take downlater [SUSPEND_EVENT_PROP_KEY]: createConfig(false, [BOOLEAN_TYPE]) + // should this be moved to the framework instead + } // socket client @@ -87,6 +90,7 @@ const wsCoreCheckMap = Object.assign(configCheckMap, socketCheckMap) // constant props const wsCoreConstProps = { + [USE_JWT_PROP_KEY]: true, // should not allow to change anymore log: null, // contract: null, eventEmitter: null, @@ -101,4 +105,8 @@ const wsCoreConstProps = { privateNamespace: PRIVATE_KEY } -export { wsCoreCheckMap, wsCoreConstProps, socketCheckMap } +export { + wsCoreCheckMap, + wsCoreConstProps, + socketCheckMap +} diff --git a/packages/ws-client-core/src/options/index.js b/packages/ws-client-core/src/options/index.js index 9f277bf52dbe335dab175f77ca06cb0a843196b9..f18316b1a00bc527b65a459ccac0350b1d09c912 100644 --- a/packages/ws-client-core/src/options/index.js +++ b/packages/ws-client-core/src/options/index.js @@ -33,12 +33,17 @@ function checkSocketClientType(config) { * Create a combine checkConfig for the creating the combine client * @param {*} configCheckMap * @param {*} constProps + * @param {boolean} [withInject=false] if we need to run the postCheckInjectOpts * @return {function} takes the user input config then resolve the configuration */ -function createCombineConfigCheck(configCheckMap, constProps) { - const combineCheckMap = Object.assign({}, configCheckMap, wsCoreCheckMap) - const combineConstProps = Object.assign({}, constProps, wsCoreConstProps) - return config => checkConfigAsync(config, combineCheckMap, combineConstProps) +function createCombineConfigCheck(configCheckMap, constProps, withInject = false) { + const combineCheckMap = Object.assign({}, wsCoreCheckMap, configCheckMap) + const combineConstProps = Object.assign({}, wsCoreConstProps, constProps) + + return function runCheckConfigAsync(config) { + return checkConfigAsync(config, combineCheckMap, combineConstProps) + .then(opts => withInject ? postCheckInjectOpts(opts) : opts) + } } @@ -62,6 +67,7 @@ function checkConfiguration(config, defaultOptions, constProps) { * @return {promise} opts all done */ function postCheckInjectOpts(opts) { + return Promise.resolve(opts) .then(opts => { if (!opts.hostname) { @@ -69,12 +75,13 @@ function postCheckInjectOpts(opts) { } // @TODO the contract now will supply the namespace information // and we need to use that to group the namespace call + opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType) // get the log function here opts.log = getLogFn(opts) opts.eventEmitter = getEventEmitter(opts) - + return opts }) } @@ -95,9 +102,7 @@ function createRequiredParams(opts) { // @TODO here we are going to add suspend event to the namespace related methods const { log } = opts const { namespaces } = nspMap - log(`namespaces`, namespaces) - // next we loop the namespace and suspend all the events prefix with namespace if (opts[SUSPEND_EVENT_PROP_KEY] === true) { // we create this as a function then we can call it again diff --git a/packages/ws-client-core/src/utils/helpers.js b/packages/ws-client-core/src/utils/helpers.js index a2b89f10b5a3079d82f1412740ea42126209851e..5cc40ae9fee77b659ed0ca670d3fa71c05a1bec7 100644 --- a/packages/ws-client-core/src/utils/helpers.js +++ b/packages/ws-client-core/src/utils/helpers.js @@ -7,9 +7,10 @@ import JsonqlValidationError from 'jsonql-errors/src/validation-error' /** * WebSocket is strict about the path, therefore we need to make sure before it goes in * @param {string} url input url + * @param {string} serverType this is not in use at the moment * @return {string} url with correct path name */ -export const fixWss = url => { +export const fixWss = (url, serverType=false) => { const uri = url.toLowerCase() if (uri.indexOf('http') > -1) { if (uri.indexOf('https') > -1) { diff --git a/packages/ws-client-core/tests/auth.test.js b/packages/ws-client-core/tests/auth.test.js index fa8db4dd08ad159bc456b6a5466438f0d16f35b1..c520b700d93955763f1e755dfbdf901f3e679ba7 100644 --- a/packages/ws-client-core/tests/auth.test.js +++ b/packages/ws-client-core/tests/auth.test.js @@ -25,8 +25,8 @@ test.cb(`We should able to get a list of event register via the eventEmitter`, t t.truthy(client) // note it's one name onError that will listen to all the nsp errors - client[ON_ERROR_FN_NAME] = function() { - log(`OnError callback added`) + client[ON_ERROR_FN_NAME] = function(err) { + log(`OnError callback added`, err) } // there is only one onReady call now diff --git a/packages/ws-client-core/tests/config.test.js b/packages/ws-client-core/tests/config.test.js new file mode 100644 index 0000000000000000000000000000000000000000..dc236945bf9e64e0051d1006ed99010c80202056 --- /dev/null +++ b/packages/ws-client-core/tests/config.test.js @@ -0,0 +1,39 @@ +// there is a problem with the configuration how create correctly +const test = require('ava') +const { + checkSocketClientType, + + createCombineConfigCheck, + postCheckInjectOpts, + createRequiredParams +} = require('../index') +const debug = require('debug')('jsonql-ws-client:test:config') + +const isF = f => typeof f === 'function' + +test(`These functions from options should be exported`, t => { + + t.true(isF(checkSocketClientType)) + t.true(isF(createCombineConfigCheck)) + t.true(isF(postCheckInjectOpts)) + t.true(isF(createRequiredParams)) + +}) + +test(`It should able to pass a log method via the checkCombineConfigCheck`, async t => { + + const msg = 'this is a log function' + + const checkFn = createCombineConfigCheck({}, {log: function() { + return msg + }}, true) + + const config = await checkFn({hostname: 'http://localhost', debugOn: true, enableAuth: true}) + + debug('config result', config) + + t.true(isF(config.log)) + + t.is(msg, config.log()) + +}) \ No newline at end of file diff --git a/packages/ws-client-core/tests/experiment.test.js b/packages/ws-client-core/tests/experiment.test.js index 723b486b6e48e9b6c14540567e118e0e795cf160..1f9d463d5376f65a2c65f3c0a7ada4e82d81179c 100644 --- a/packages/ws-client-core/tests/experiment.test.js +++ b/packages/ws-client-core/tests/experiment.test.js @@ -26,7 +26,7 @@ const baseUrl = `ws://localhost:${port}/${JSONQL_PATH}` const userdata = {name: 'Joel', id: 1} const asyncClient = (url, token) => { - return Promise.resolve(basicClient(url, token)) + return Promise.resolve(basicClient(url, {}, token)) } const namespaces = ['public', 'private'] @@ -91,7 +91,7 @@ test.cb.only(`Testing the fullClient with csrf`, t => { const plus = () => evt.$trigger('count', 1) chainPromises([ - fullClient([baseUrl, namespaces[1]].join('/'), t.context.token), + fullClient([baseUrl, namespaces[1]].join('/'), {}, t.context.token), fullClient([baseUrl, namespaces[0]].join('/')) ]).then(clients => clients .map((client, i) => { diff --git a/packages/ws-client-core/tests/fixtures/server-setup.js b/packages/ws-client-core/tests/fixtures/server-setup.js index 0a432a9ea903320bf4bb4e03d1756ad8219a537e..cc368886bb95612f8977d3fff6f0dae739456a5b 100644 --- a/packages/ws-client-core/tests/fixtures/server-setup.js +++ b/packages/ws-client-core/tests/fixtures/server-setup.js @@ -1,42 +1,25 @@ -const http = require('http') -// const fsx = require('fs-extra') const { join } = require('path') -// const debug = require('debug')('jsonql-ws-client:fixtures:server') -// const { JSONQL_PATH } = require('jsonql-constants') -// const colors = require('colors/safe') -// const logger = (str, ...args) => Reflect.apply(debug, null, [colors.white.bgMagenta(str), ...args]) +const { jsonqlWsStandaloneServer } = require('jsonql-ws-server') const resolverDir = join(__dirname, 'resolvers') -const { jsonqlWsServer } = require('jsonql-ws-server') -// require('../../../ws-server') -// - -// start -const server = http.createServer(function(req, res) { - res.writeHead(200, { 'Content-Type': 'text/plain' }) - res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2)) - res.end() -}) - module.exports = function(extra = {}) { const contractDir = extra.enableAuth ? join(__dirname, 'contract', 'auth') : join(__dirname, 'contract') - // extra.contract = extra.contract || contract; return new Promise(resolver => { - jsonqlWsServer( + jsonqlWsStandaloneServer( Object.assign({ resolverDir, contractDir, serverType: 'ws' }, extra), - server + false ) - .then(io => { + .then(({ws, server}) => { resolver({ - io, + io: ws, app: server }) }) diff --git a/packages/ws-server-core/index.js b/packages/ws-server-core/index.js index 2a788724f80f64393b3fc691162b0edd08ef2786..5d8705cb3c93e5bc6eaedba5d7e2eba4e6904f36 100644 --- a/packages/ws-server-core/index.js +++ b/packages/ws-server-core/index.js @@ -13,8 +13,19 @@ const { } = require('./src') // we also need to export all the share methods here because they will get use // in the respective external methods - -const { getContract } = require('./src/share/get-contract') +const { + getTokenFromUrl, + processAuthTokenHeader, + getTokenFromHeader, + getWsAuthToken, + extractConfig, + prepareConnectConfig, + getCache, + isCacheObj +} = require('@jsonql/security') +const { + getContract +} = require('./src/share/get-contract') const { createWsReply, @@ -67,5 +78,14 @@ module.exports = { jsonqlWsServerCore, jsonqlWsServerCoreAction, // @0.6.0 - getSocketHandler + getSocketHandler, + // @0.8.5 + extractConfig, + prepareConnectConfig, + getCache, + isCacheObj, + getTokenFromUrl, + processAuthTokenHeader, + getTokenFromHeader, + getWsAuthToken } diff --git a/packages/ws-server-core/package.json b/packages/ws-server-core/package.json index e9bb624185d984b8ea0d324ee71518c6cce9eed2..a5137641555f452599d7a62f9a804029088d60dd 100644 --- a/packages/ws-server-core/package.json +++ b/packages/ws-server-core/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-ws-server-core", - "version": "0.8.4", + "version": "0.8.8", "description": "This is the core module that drive the Jsonql WS Socket server, not for direct use.", "main": "index.js", "files": [ @@ -27,7 +27,7 @@ "author": "Joel Chu ", "license": "MIT", "dependencies": { - "@jsonql/security": "^0.9.5", + "@jsonql/security": "^0.9.9", "@to1source/event": "^1.1.1", "colors": "^1.4.0", "debug": "^4.1.1", diff --git a/packages/ws-server-core/src/core.js b/packages/ws-server-core/src/core.js index 14377020e0fc92f6da2230517588b5339103d3e4..00eef0fa4d6dc5589f1b981519a573e4472dd020 100644 --- a/packages/ws-server-core/src/core.js +++ b/packages/ws-server-core/src/core.js @@ -36,18 +36,15 @@ function jsonqlWsServerCoreAction({ opts, server, setupSocketServer }) { * This will take the two methods and return a method to generate the web socket server * This is for standalone server type which unlikely to get use often * @param {function} setupSocketServer generate the base server + * @param {object} checkMaps because each framework has it's own property we should pass back the map here * @return {function} the method that accept the config and server instance to run */ -function jsonqlWsServerCore(setupSocketServer) { +function jsonqlWsServerCore(setupSocketServer, checkMaps = {}) { return (config, server) => ( - wsServerCheckConfiguration(config) + wsServerCheckConfiguration(config, checkMaps) .then(opts => ({ opts, server, setupSocketServer })) .then(jsonqlWsServerCoreAction) - .then(_server => { - console.log(`===================== Server inited ==================`) - return _server - }) ) } diff --git a/packages/ws-server-core/src/handles/setup-event-handler.js b/packages/ws-server-core/src/handles/setup-event-handler.js deleted file mode 100644 index 1db1c628f7e71bace6f1f058a92f6952c4e3445a..0000000000000000000000000000000000000000 --- a/packages/ws-server-core/src/handles/setup-event-handler.js +++ /dev/null @@ -1,8 +0,0 @@ -// this is the inter communication event setup - - -function setupEventHandler() { - -} - -module.exports = { setupEventHandler } \ No newline at end of file diff --git a/packages/ws-server-core/src/handles/setup-internal-event-handler.js b/packages/ws-server-core/src/handles/setup-internal-event-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..0880a86facec97276fcb04e1cd5e67b1a50bfdf5 --- /dev/null +++ b/packages/ws-server-core/src/handles/setup-internal-event-handler.js @@ -0,0 +1,76 @@ +// this is the inter communication event setup +// what we need to do is take the namespace / contract +// then create event caller here +// then on the framework part they will listen to these events +// in fact, both can be completely do here +// 1) also we should implement the suspend feature as well +// 2) also we will only deal with the socket part here +// where the http part will deal with by other part of the system +const debug = require('debug')('jsonql-ws-server:handles:setup-internal') +const { createEvt } = require('jsonql-utils') +const { INTERNAL_PREFIX } = require('../options/constants') + +/** + * wrapper method to create the event name for re-use + * @param {string} namespace + * @param {string} resolverName + * @return {string} + */ +function createInternalEvtName(namespace, resolverName) { + return createEvt(INTERNAL_PREFIX, namespace, resolverName) +} + + +/** + * This is the same in both cases therefore we just pass callback to handle it + * @param {array} namespaces from nspInfo + * @param {object} socket from contract + * @param {function} callback + * @return {void} + */ +function generateEvtNames(namespaces, socket, callback) { + namespaces.forEach(namespace => { + for (let resolverName in socket) { + let evtName = createInternalEvtName(namespace, resolverName) + callback(evtName, resolverName) + } + }) +} + +/** + * Create the internal call via the Event system + * This should get call in the handle-nsp-resolvers + * @param {*} opts configuration + * @return {void} + */ +function setupInternalEventCallers(opts) { + const { nspInfo, eventEmitter, contract, log } = opts + const { namespaces } = nspInfo + const { socket } = contract + // @TODO might need a few more props here +} + +/** + * Create the internal listener via the Event system + * @param {*} opts configuration + * @return {void} + */ +function setupInternalEventListeners(opts) { + // debug('initWsServerOption', opts) + const { nspInfo, eventEmitter, contract, log } = opts + const { namespaces } = nspInfo + const { socket } = contract + // run the create event name for each + generateEvtNames(namespaces, socket, (evtName, resolverName) => { + // we might need to create a new type of delivery struture ? + eventEmitter.$only(evtName, function(args) { + log(`resolverName`, resolverName, args) + }) + }) +} + +module.exports = { + createInternalEvtName, + setupInternalEventListeners, + setupInternalEventCallers +} \ No newline at end of file diff --git a/packages/ws-server-core/src/options/constants.js b/packages/ws-server-core/src/options/constants.js index bcbec1f6f8560815b59b84471c78a3844c16acc2..af844cf24fa31132a4e4d6f45db572ac2a9bb3ff 100644 --- a/packages/ws-server-core/src/options/constants.js +++ b/packages/ws-server-core/src/options/constants.js @@ -27,6 +27,8 @@ const CONTRACT_NOT_FOUND_ERR = `No contract presented!` const NO_TOKEN_ERR_MSG = `No token!` const HEADER_CHECK_FAIL_MSG = 'Header check failed' +// prefix to those internal events +const INTERNAL_PREFIX = 'internal' module.exports = { SOCKET_IO, @@ -41,5 +43,7 @@ module.exports = { SOCKET_STATE_KEY, HEADER_CHECK_FAIL_MSG, - NO_TOKEN_ERR_MSG + NO_TOKEN_ERR_MSG, + + INTERNAL_PREFIX } diff --git a/packages/ws-server-core/src/options/props.js b/packages/ws-server-core/src/options/defaults.js similarity index 94% rename from packages/ws-server-core/src/options/props.js rename to packages/ws-server-core/src/options/defaults.js index 97a89de686522c9a8d400c99e6566fd0f2fe55c6..5341b9fe41b40c0101fc5ebb4fdbeb3317321996 100644 --- a/packages/ws-server-core/src/options/props.js +++ b/packages/ws-server-core/src/options/defaults.js @@ -49,7 +49,6 @@ const { SWITCH_USER_FN_NAME_PROP_KEY, PUBLIC_FN_DIR_PROP_KEY, PRIVATE_FN_DIR_DROP_KEY, - SOCKET_IO_AUTH_TYPE_PROP_KEY, ALLOW_ORIGIN_PROP_KEY, SERVER_INIT_OPT_PROP_KEY, CSRF_PROP_KEY, @@ -59,7 +58,8 @@ const { CONTRACT_PROP_KEY, SECRET_PROP_KEY, PUBLIC_NAMESPACE_PROP_KEY, - PRIVATE_NAMESPACE_PROP_KEY + PRIVATE_NAMESPACE_PROP_KEY, + STANDALONE_PROP_KEY } = require('jsonql-constants') // default root folder const dirname = process.cwd() @@ -92,10 +92,7 @@ const wsBaseOptions = { // this should be following what is the contract-cli using [PUBLIC_FN_DIR_PROP_KEY]: createConfig(PUBLIC_KEY, [STRING_TYPE]), [PRIVATE_FN_DIR_DROP_KEY]: createConfig(PRIVATE_KEY, [STRING_TYPE, BOOLEAN_TYPE]), - // this should move to the post check option because it's framework specific - [SOCKET_IO_AUTH_TYPE_PROP_KEY]: createConfig(false, [STRING_TYPE], { - [ENUM_KEY]: [IO_HANDSHAKE_LOGIN, IO_ROUNDTRIP_LOGIN] - }), + [STANDALONE_PROP_KEY]: createConfig(false, [BOOLEAN_TYPE]), // check the origin if we can [ALLOW_ORIGIN_PROP_KEY]: createConfig(['*'], [ARRAY_TYPE]), [SERVER_INIT_OPT_PROP_KEY]: createConfig({}, [OBJECT_TYPE]), diff --git a/packages/ws-server-core/src/options/index.js b/packages/ws-server-core/src/options/index.js index 41ff6e2138348a1cf8fb78e1b966153dcd5ffa40..1b9126cb731cfd1b17b482a4fbac8e31fc809fc6 100644 --- a/packages/ws-server-core/src/options/index.js +++ b/packages/ws-server-core/src/options/index.js @@ -2,14 +2,15 @@ // methods const { join } = require('path') const fsx = require('fs-extra') + +const { getCache, isCacheObj } = require('@jsonql/security') const { JsonqlValidationError } = require('jsonql-errors') const { getNspInfoByConfig } = require('jsonql-utils') const { checkConfig, - checkConfigAsync, - // isString + checkConfigAsync } = require('jsonql-params-validator') -const { getContract } = require('../share/get-contract') + // properties const { PEM_EXT, @@ -23,9 +24,11 @@ const { wsDefaultOptions, wsConstProps, socketAppProps -} = require('./props') +} = require('./defaults') +const { getContract } = require('../share/get-contract') const { WsServerEventEmitter } = require('./event-emitter') -const { getCache, isCacheObj } = require('@jsonql/security') +const { setupInternalEventListeners } = require('../handles/setup-internal-event-handler') + const debug = require('debug')('jsonql-ws-server-core:options') @@ -41,12 +44,11 @@ function checkSocketServerType(config) { /** * Add pre-check method to see if it's already pass the check earlier * @param {object} config configuration - * @param {object} defaultOptions as its - * @param {object} constProps as its + * @param {object} checkMap as its * @return {object} checked opts */ -function localCheckConfig(config) { - return checkConfigAsync(config, wsDefaultOptions, wsConstProps) +function localCheckConfig(config, checkMap) { + return checkConfigAsync(config, Object.assign(wsDefaultOptions, checkMap), wsConstProps) } /** @@ -92,10 +94,11 @@ function initWsServerOption(config) { // we init an cache object here now for re-use through out the app opts[CACHE_STORE_PROP_KEY] = getCacheStore(opts) - debug(CACHE_STORE_PROP_KEY, opts[CACHE_STORE_PROP_KEY]) - opts[EVENT_EMITTER_PROP_KEY] = new WsServerEventEmitter(log) + // @TODO continue later + setupInternalEventListeners(opts) + return opts }) } @@ -103,11 +106,12 @@ function initWsServerOption(config) { /** * This is a combine method that will check the options * @param {object} config user supply + * @param {object} checkMap the additional property to add to the checkMap * @param {boolean} [init=false] this is mainly for internal test * @return {object} promise resolve the opts */ -function wsServerCheckConfiguration(config, init = false) { - return localCheckConfig(config) +function wsServerCheckConfiguration(config, checkMap = {}, init = false) { + return localCheckConfig(config, checkMap) .then(config => init ? initWsServerOption(config) : config) } diff --git a/packages/ws-server-core/src/resolver/setup-to-method.js b/packages/ws-server-core/src/resolver/setup-to-method.js new file mode 100644 index 0000000000000000000000000000000000000000..432e644c79f9ae216987ba192a155d61c2e848ac --- /dev/null +++ b/packages/ws-server-core/src/resolver/setup-to-method.js @@ -0,0 +1,37 @@ +// this is the new internal event +// resolverName.to('resolverName').send(...args) +// then you can call another socket resolver or just a regular resolver +const { TO_MSG_FN_NAME, EMIT_REPLY_TYPE } = require('jsonql-constants') +const { objDefineProps } = require('jsonql-utils') +const { deliverMsg } = require('./resolver-methods') +const { nil, getRainbowDebug } = require('../share/helpers') +const debug = getRainbowDebug('create-send-method', 'x') + +/** + * It was just a simple resolverName.send setter + * Now we make it full feature, also it should pair with a `receive` method? + * @param {function} deliveryFn framework specific to deliver message to client + * @param {function} resolver the function itself + * @param {string} resolverName the name of this resolver + * @param {object} opts configuration + * @return {function} resolver with a `send` method property + */ +const setupToMethod = function(deliverFn, resolver, resolverName, opts) { + return objDefineProps( + resolver, + TO_MSG_FN_NAME, + nil, + function sendHandler() { + // @NOTE we don't need to validate here, if we need to in the future, + // we should validate it against the return params + return function sendCallback(...args) { + + debug('sendCallback', args) + + deliverMsg(deliverFn, resolverName, args, EMIT_REPLY_TYPE) + } + } + ) +} + +module.exports = { setupSendMethod } diff --git a/packages/ws-server-core/tests/fn.test.js b/packages/ws-server-core/tests/fn.test.js index 9ccba4d4cbe10877f715e1ee5618d6b0402d9be5..49805873c7bdce520ee1ca832c799e1a34319009 100644 --- a/packages/ws-server-core/tests/fn.test.js +++ b/packages/ws-server-core/tests/fn.test.js @@ -1,6 +1,11 @@ const test = require('ava') const { handleInterCom } = require('../src/handles/handle-intercom') -const { getCache } = require('@jsonql/security') +const { + extractConfig, + prepareConnectConfig, + getCache, + isCacheObj +} = require('../index') // const fsx = require('fs-extra') const { join } = require('path') const debug = require('debug')('jsonql-ws-core:test:fn') @@ -13,7 +18,12 @@ const { wsServerCheckConfiguration } = require('../src/options') +test(`just testing that rexport methods existed`, t => { + t.true(typeof extractConfig === 'function') + t.true(typeof prepareConnectConfig === 'function') + t.true(typeof isCacheObj === 'function') +}) test.cb(`Just testing the handleInterCom function interface`, t => { @@ -50,7 +60,7 @@ test(`test the get-socket-resolver method mainly to look at the cache`, async t contractDir: join(__dirname, 'fixtures'), resolverDir: join(__dirname, 'fixtures', 'resolvers') } - const config = await wsServerCheckConfiguration(opts, true) + const config = await wsServerCheckConfiguration(opts, {}, true) const callbackFn = (str) => { console.info(str) } diff --git a/packages/ws-server/client.js b/packages/ws-server/client.js index 0e21505c3378e54ed457392fcc8e186a7c6cf220..f568d8be904eb1eb7c7c0da20419e73dcdb51fc0 100644 --- a/packages/ws-server/client.js +++ b/packages/ws-server/client.js @@ -1,12 +1,14 @@ // we also provide a node client here const WebSocket = require('ws') -const { TOKEN_PARAM_NAME } = require('jsonql-constants') const { JsonqlError } = require('jsonql-errors') const { createInitPing, extractPingResult } = require('./src/intercom-methods') const debug = require('debug')('jsonql-ws-server:client') +const { prepareConnectConfig } = require('jsonql-ws-server-core') + + /** * Create a client with auth token * @param {string} url start with ws:// @TODO check this? @@ -14,9 +16,12 @@ const debug = require('debug')('jsonql-ws-server:client') * @param {object} [opts = {}] pass init options to it * @return {object} ws instance */ -function basicClient(url, token = false, opts = {}) { - let uri = token ? `${url}?${TOKEN_PARAM_NAME}=${token}` : url - return new WebSocket(uri, opts) +function basicClient(uri, config = {}, token = false) { + // let uri = token ? `${url}?${TOKEN_PARAM_NAME}=${token}` : url + const { url, opts } = prepareConnectConfig(uri, config, token) + debug('basicClient', url, opts) + + return new WebSocket(url, opts) } /** @@ -32,11 +37,6 @@ function initConnect(ws) { ws.onmessage = function(payload) { try { - /* - setTimeout(() => { - ws.terminate() - }, 300) - */ ws.terminate() resolver(extractPingResult(payload.data)) } catch(e) { @@ -57,10 +57,10 @@ function initConnect(ws) { * @param {*} opts * @return {promise} resolve the verify connected client */ -function fullClient(url, token = false, opts = {}) { +function fullClient(url, opts = {}, token = false) { return new Promise((resolver, rejecter) => { - const bc = basicClient(url, token, opts) + const bc = basicClient(url, opts, token) return initConnect(bc) .then(header => { @@ -68,7 +68,7 @@ function fullClient(url, token = false, opts = {}) { debug(`config`, config) - const client = basicClient(url, token, config) + const client = basicClient(url, config, token) resolver(client) }) @@ -79,4 +79,7 @@ function fullClient(url, token = false, opts = {}) { } // breaking change export as name -module.exports = { basicClient, fullClient } \ No newline at end of file +module.exports = { + basicClient, + fullClient +} \ No newline at end of file diff --git a/packages/ws-server/index.js b/packages/ws-server/index.js index 7231d52ec659c75b0f2bea827b4dd031988da586..1ff477f1457e1ac76f2263d388aaf3f40d025b49 100644 --- a/packages/ws-server/index.js +++ b/packages/ws-server/index.js @@ -8,16 +8,20 @@ const { } = require('./src/modules') const { jsonqlWsServer, - jsonqlWsServerAction + jsonqlWsServerAction, + jsonqlWsStandaloneServer } = require('./src') +const { createServer } = require('./src/server') // breaking change @1.6.0 we export it as a name module module.exports = { jsonqlWsServer, jsonqlWsServerAction, + jsonqlWsStandaloneServer, // util export checkSocketServerType, // props export wsServerDefaultOptions, - wsServerConstProps + wsServerConstProps, + createServer } diff --git a/packages/ws-server/package.json b/packages/ws-server/package.json index f022ac9e6e81217090699959c395692ebd9c4a3b..6e3e7dd7a0a9e6a2f5e59f3729fbf5fe48184de8 100755 --- a/packages/ws-server/package.json +++ b/packages/ws-server/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-ws-server", - "version": "1.7.10", + "version": "1.7.13", "description": "Setup WebSocket server for the jsonql to run on the same host, automatic generate public / private channel using contract", "main": "index.js", "files": [ @@ -11,6 +11,7 @@ "scripts": { "test": "ava", "prepare": "npm run test", + "test:con": "DEBUG=jsonql-ws-server:fn:getWsAuthHeader ava ./tests/connect.test.js", "test:init": "DEBUG=jsonql-ws-* ava ./tests/init.test.js", "test:send": "DEBUG=jsonql-ws-* ava ./tests/send.test.js", "test:basic": "DEBUG=jsonql-* ava ./tests/basic.test.js", @@ -35,7 +36,7 @@ "debug": "^4.1.1", "jsonql-constants": "^2.0.16", "jsonql-utils": "^1.2.6", - "jsonql-ws-server-core": "^0.8.4", + "jsonql-ws-server-core": "^0.8.8", "ws": "^7.2.3" }, "devDependencies": { diff --git a/packages/ws-server/src/core/options.js b/packages/ws-server/src/core/options.js index 6f634c3d7bf9b60b920a419a9ad1f70017ccfd0f..2e05a71bba396176641968e79b8bb003cb16efcb 100644 --- a/packages/ws-server/src/core/options.js +++ b/packages/ws-server/src/core/options.js @@ -22,6 +22,10 @@ const configCheckMap = { }) } +const DEFAULT_PORT = 9981 + module.exports = { - wsServerDefaultOptions: Object.assign(wsServerDefaultOptions, configCheckMap) + DEFAULT_PORT, + configCheckMap, + wsServerDefaultOptions: Object.assign(wsServerDefaultOptions, configCheckMap) } \ No newline at end of file diff --git a/packages/ws-server/src/core/security/create-verify-client.js b/packages/ws-server/src/core/security/create-verify-client.js index 41bace5faedb07cba2d186596285b5227384470f..f03bb13036687741c69d386cced8f6a4a6681241 100644 --- a/packages/ws-server/src/core/security/create-verify-client.js +++ b/packages/ws-server/src/core/security/create-verify-client.js @@ -1,79 +1,13 @@ // @TBC each different server might have different way to verify the client? // export the verifyClient at init time for a handshake authentication -const url = require('url') -const { parse } = require('querystring') -const { jwtDecode } = require('jsonql-jwt') - const { - TOKEN_PARAM_NAME, - TOKEN_DELIVER_LOCATION_PROP_KEY, - TOKEN_IN_URL, - TOKEN_IN_HEADER, - AUTH_CHECK_HEADER -} = require('jsonql-constants') - -const { SOCKET_STATE_KEY } = require('../../modules') -const { debug } = require('../../utils') - -/* -old method keep for reference -const params = query.split('&') -return params.filter(param => ( - param.indexOf(TOKEN_PARAM_NAME) > -1 - )) - .reduce((f, n) => n ? n.split('=')[1] : f, false) -*/ - -/** - * What the name said - * @param {string} uri to decode - * @return {string|boolean} token or false means didn't find it - */ -function getTokenFromQuery(uri) { - const { query } = url.parse(uri) - if (query) { - const params = parse(query) - return params[TOKEN_PARAM_NAME] || false - } - return false -} - -/** - * new method to get the token from the header - * @param {*} opts - * @param {*} req - */ -function getTokenFromHeader(req) { - const { headers } = req - if (headers) { - return headers[AUTH_CHECK_HEADER] || false - } - - return false -} - -/** - * New combine get token method using the options to switch - * @param {object} opts configuration - * @param {object} req request object - * @return {string|boolean} false on failed - */ -function getAuthToken(opts, req) { - switch (opts[TOKEN_DELIVER_LOCATION_PROP_KEY]) { - case TOKEN_IN_URL: - - return getTokenFromQuery(req.url) - case TOKEN_IN_HEADER: - - return getTokenFromHeader(req) - default: - - return false - } - -} + SOCKET_STATE_KEY, + jwtDecode, + getWsAuthToken +} = require('../../modules') +const { debug } = require('../../utils') /** * We need to check the origin from the header to make sure it's match @@ -144,22 +78,17 @@ function createVerifyClient(namespace, opts, jwtOptions = {}, cb = localCb) { return done(false) } - debug('nspInfo', nspInfo) - // debug('what the fuck is happening here?', namespace, publicNamespace) - // also need to check if this is the private namespace as well! if (!enableAuth || namespace === publicNamespace) { - // cb(`public namespace no need to check`, namespace, publicNamespace) - return done(true) // job done here } // @TODO here we need to take the interceptor.validate method that created by // develop to run their own checks // using a new method to group the getToken method - const token = getAuthToken(opts, req) + const token = getWsAuthToken(opts, req) if (token) { - debug(`Got a token`) + debug(`Got a token`, token) try { const payload = jwtDecode(token, publicKey, jwtOptions) @@ -173,12 +102,16 @@ function createVerifyClient(namespace, opts, jwtOptions = {}, cb = localCb) { return done(payload) } catch(e) { + debug('verifyClient', e, token) + cb(e) // just show the error done(false) } } // @TODO replace with share constants from ws-server-core - cb('no token!') + + + cb('================= no token! =================') done(false) } } diff --git a/packages/ws-server/src/index.js b/packages/ws-server/src/index.js index 55bcd83322b8c964b215152a9df84436fca6df85..ce5b5f5636515c01de07316b80f3ae5ecfaa1b09 100644 --- a/packages/ws-server/src/index.js +++ b/packages/ws-server/src/index.js @@ -1,11 +1,22 @@ // re-export here -const { setupSocketServer } = require('./core/setup-socket-server') +const { + setupSocketServer +} = require('./core/setup-socket-server') // move back from the root index.js const { jsonqlWsServerCore, jsonqlWsServerCoreAction } = require('./modules') - +const { + DEFAULT_PORT, + configCheckMap +} = require('./core/options') +const { + createServer +} = require('./server') +const { + STANDALONE_PROP_KEY +} = require('jsonql-constants') /** * This is the method that is the actual create server without the config check * @param {object} opts the already checked configuration @@ -14,6 +25,7 @@ const { */ function jsonqlWsServerAction(opts, server) { const params = { opts, server, setupSocketServer } + return jsonqlWsServerCoreAction(params) } @@ -23,19 +35,38 @@ function jsonqlWsServerAction(opts, server) { * @param {string} config.serverType socket.io or ws in the background * @param {object} config.options the actual options to pass to the underlying setups * @param {object} config.server this is the http/s server that required to bind to the socket to run on the same connection - * @return {mixed} return the undelying socket server instance for further use + * @return {promise} return the undelying socket server instance for further use */ -function jsonqlWsServer(config, server) { - // @TODO when this is using the standalone mode - // we should just init the http.createServer instead of expecting to pass - // the server - - const setupFn = jsonqlWsServerCore(setupSocketServer) +function jsonqlWsServer(config, server) { + const setupFn = jsonqlWsServerCore(setupSocketServer, configCheckMap) + return setupFn(config, server) + .then(ws => { + return { ws, server } + }) } +/** + * quick way to create a standalone server + * @param {*} config + * @param {*} port pass FALSE then no auto start + * @return {promise} jsonqlWsServer, server + */ +function jsonqlWsStandaloneServer(config, port = DEFAULT_PORT) { + const server = createServer() + const opts = Object.assign(config, {[STANDALONE_PROP_KEY]: true}) + + return jsonqlWsServer(opts, server) + .then(({ws,server}) => { + if (port !== false) { + server.listen(port) + } + return { ws, server } + }) +} module.exports = { jsonqlWsServerAction, - jsonqlWsServer + jsonqlWsServer, + jsonqlWsStandaloneServer } diff --git a/packages/ws-server/src/modules.js b/packages/ws-server/src/modules.js index f3a91e769054eccc118384f9a17007e3b432e5f3..903c5edfbf63c33d89c0655958e099583f108ce5 100644 --- a/packages/ws-server/src/modules.js +++ b/packages/ws-server/src/modules.js @@ -1,14 +1,17 @@ // keep all the import from ws-server-core in one place // for easy switching to debug const WebSocket = require('ws') -const { wsServerDefaultOptions } = require('./core/options') - +const { + wsServerDefaultOptions +} = require('./core/options') const { checkSocketServerType, + + SOCKET_STATE_KEY, + jsonqlWsServerCore, jsonqlWsServerCoreAction, - // wsServerDefaultOptions, wsServerConstProps, getNamespace, @@ -19,12 +22,16 @@ const { isUserdata, prepareUserdata, - SOCKET_STATE_KEY, getSocketHandler -} = require('jsonql-ws-server-core') -// require('../../ws-server-core') - +} = require('../../ws-server-core') +// require('jsonql-ws-server-core') + +const { + jwtDecode, + getWsAuthToken +} = require('@jsonql/security') + module.exports = { WebSocket, // ours @@ -45,5 +52,8 @@ module.exports = { SOCKET_STATE_KEY, - getSocketHandler + getSocketHandler, + + jwtDecode, + getWsAuthToken } diff --git a/packages/ws-server/src/server.js b/packages/ws-server/src/server.js new file mode 100644 index 0000000000000000000000000000000000000000..bf1887c86c1f7ad603734fc50e128fa66b8fe3df --- /dev/null +++ b/packages/ws-server/src/server.js @@ -0,0 +1,18 @@ +// this is for standalone mode then we just create a server +const http = require('http') + +function createServer(port = false) { + const server = http.createServer(function(req, res) { + res.writeHead(200, { 'Content-Type': 'text/plain' }) + res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2)) + res.end() + }) + + if (port && !isNaN(parseInt(port))) { + server.listen(port) + } + + return server +} + +module.exports = { createServer } \ No newline at end of file diff --git a/packages/ws-server/tests/basic.test.js b/packages/ws-server/tests/basic.test.js index 49490e9447e05e3e7c08a05320a0d617d39a07c1..60691bf01b9686b38c8bbab311bc39dd31f6712b 100644 --- a/packages/ws-server/tests/basic.test.js +++ b/packages/ws-server/tests/basic.test.js @@ -4,7 +4,7 @@ const { join } = require('path') const fsx = require('fs-extra') const colors = require('colors/safe') // this will get the umd version of the client module -const { JSONQL_PATH, SOCKET_NAME } = require('jsonql-constants') +const { JSONQL_PATH } = require('jsonql-constants') // const { decodeToken } = require('jsonql-jwt') const { basicClient } = require('../client') @@ -22,7 +22,7 @@ const payload = {name: 'Joel', Location: 'Zhuhai'} const payload1 = {name: 'Davide', location: 'London'} const port = 3003 const baseUrl = `ws://localhost:${port}/${JSONQL_PATH}/` -const { rainbow } = colors +// const { rainbow } = colors test.before(async t => { @@ -44,7 +44,7 @@ test.before(async t => { // @1.3.0 there is no different between the two only need the token param now t.context.client_public = basicClient(baseUrl + 'public') - t.context.client_private = basicClient(baseUrl + 'private', t.context.token) + // t.context.client_private = basicClient(baseUrl + 'private', {}, t.context.token) }) test.after(t => { diff --git a/packages/ws-server/tests/connect.test.js b/packages/ws-server/tests/connect.test.js new file mode 100644 index 0000000000000000000000000000000000000000..8b295ec7b8c813f86c8ada9aebf8f84b5d56d6f5 --- /dev/null +++ b/packages/ws-server/tests/connect.test.js @@ -0,0 +1,71 @@ +// this will be testing the new auth client using the header options +const test = require('ava') + +const { join } = require('path') +const fsx = require('fs-extra') +const colors = require('colors/safe') +// this will get the umd version of the client module +const { + JSONQL_PATH, + TOKEN_IN_HEADER, + TOKEN_DELIVER_LOCATION_PROP_KEY +} = require('jsonql-constants') + +const { basicClient } = require('../client') +const { extractWsPayload } = require('jsonql-ws-server-core') +const serverSetup = require('./fixtures/server') +const createToken = require('./fixtures/token') +const createPayload = require('./fixtures/create-payload') + +const debug = require('debug')('jsonql-ws-server:test:jwt-auth') + +const contractDir = join(__dirname, 'fixtures', 'contract', 'auth') +const contract = fsx.readJsonSync(join(contractDir, 'contract.json')) + +const payload = {name: 'Joel', Location: 'Zhuhai'} +// const payload1 = {name: 'Davide', location: 'London'} +const port = 3008 +const baseUrl = `ws://localhost:${port}/${JSONQL_PATH}/` +// const { rainbow } = colors +// const EventEmitter = require('@to1source/event') + +test.before(async t => { + + const { app } = await serverSetup({ + contract, + contractDir, + enableAuth: true, + keysDir: join(__dirname, 'fixtures', 'keys'), + [TOKEN_DELIVER_LOCATION_PROP_KEY]: TOKEN_IN_HEADER + }) + + app.listen(port) + t.context.app = app + t.context.token = createToken(payload) +}) + +test.after(t => { + t.context.app.close() +}) + +test.cb(`Should able to use the new header option to create a auth client`, t => { + + t.plan(1) + const config = {[TOKEN_DELIVER_LOCATION_PROP_KEY]: TOKEN_IN_HEADER} + const client = basicClient(baseUrl + 'private', config, t.context.token) + + client.on('open', function() { + client.send( createPayload('secretChatroom', 'what', 'ever') ) + }) + + client.on('message', function(payload) { + let json = extractWsPayload(payload) + + debug(colors.blue.bgYellow('on.message from private'), json) + + t.truthy(json) + t.end() + + }) + +}) \ No newline at end of file diff --git a/packages/ws-server/tests/fixtures/server.js b/packages/ws-server/tests/fixtures/server.js index d494c7933012069b1dd16a019886fa4d9986c890..d2980843825def40ab05f3073070775229e2c3e4 100644 --- a/packages/ws-server/tests/fixtures/server.js +++ b/packages/ws-server/tests/fixtures/server.js @@ -1,39 +1,32 @@ -const http = require('http') -// const fsx = require('fs-extra') const debug = require('debug')('jsonql-ws-server:fixtures:server') -// const fs = require('fs') const { join } = require('path') -// const { JSONQL_PATH } = require('jsonql-constants') const resolverDir = join(__dirname, 'resolvers') const contractDir = join(__dirname, 'contract') -const { jsonqlWsServer } = require('../../index') - -// start -const server = http.createServer(function(req, res) { - res.writeHead(200, { 'Content-Type': 'text/plain' }) - res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2)) - res.end() -}) +const { jsonqlWsStandaloneServer } = require('../../index') module.exports = function(extra = {}) { // extra.contract = extra.contract || contract; - return new Promise(resolver => { - Promise.resolve(Object.assign({ + return Promise.resolve( + Object.assign({ resolverDir, contractDir, serverType: 'ws' - }, extra)) + }, extra) + ) .then(config => { debug('server setup config', config) - return jsonqlWsServer(config, server) - .then(io => { - resolver({ - io, + + return jsonqlWsStandaloneServer(config, false) + .then(({ws, server}) => { + + // just keep it consistent + return { + io: ws , app: server - }) + } }) }) - }) + } diff --git a/packages/ws-server/tests/init.test.js b/packages/ws-server/tests/init.test.js index 8e360147f01558d1291660da0f09ddf922bceda1..24c7bbaaea81b0393da015588d51222416231a63 100644 --- a/packages/ws-server/tests/init.test.js +++ b/packages/ws-server/tests/init.test.js @@ -57,7 +57,7 @@ test.cb(`Testing the init ping call`, t => { // t.end() // reinit the client with an options - const newClient = basicClient(`ws://localhost:${port}/${JSONQL_PATH}`, false, { + const newClient = basicClient(`ws://localhost:${port}/${JSONQL_PATH}`, { headers: json.data }) diff --git a/packages/ws-server/tests/ws-jwt-auth.test.js b/packages/ws-server/tests/ws-jwt-auth.test.js index cc3f741f107d72efb271a4cceef7022161f696ad..bef4ae5b765d5899e9434c9795da36bc3676cc81 100644 --- a/packages/ws-server/tests/ws-jwt-auth.test.js +++ b/packages/ws-server/tests/ws-jwt-auth.test.js @@ -5,7 +5,7 @@ const colors = require('colors/safe') // this will get the umd version of the client module const { JSONQL_PATH } = require('jsonql-constants') -const { fullClient, basicClient } = require('../client') +const { basicClient } = require('../client') const { extractWsPayload } = require('jsonql-ws-server-core') const serverSetup = require('./fixtures/server') const createToken = require('./fixtures/token') @@ -42,14 +42,9 @@ test.before(async t => { t.context.app.listen(port) - // @1.3.0 there is no different between the two only need the token param now - // t.context.client_public = await fullClient(baseUrl + 'public') - // t.context.client_private = await fullClient(baseUrl + 'private', t.context.token) - - t.context.client_private = basicClient(baseUrl + 'private', t.context.token) + t.context.client_private = basicClient(baseUrl + 'private', {}, t.context.token) t.context.client_public = basicClient(baseUrl + 'public') - // t.context.client_private_1 = await fullClient(baseUrl + 'private', t.context.token) t.context.eventEmitter = new EventEmitter() @@ -74,9 +69,9 @@ test.cb('It should able to connect to public namespace without a token', t => { client.on('message', data => { let json = extractWsPayload(data) - // debug('reply', json) + debug('public namespace reply', json) + t.truthy(json.data) - // client.close() t.end() }) }) @@ -96,7 +91,7 @@ test.cb('It should able to connect to the private namespace', t => { t.truthy(json.data) client.close() - debug('second json', json) + debug('second payload from public namespace', json) t.end() }) }) @@ -154,7 +149,7 @@ test.cb(`first try to connect to the private without login and see what happens` }) setTimeout(() => { - authClient = basicClient(baseUrl + 'private', t.context.token1) + authClient = basicClient(baseUrl + 'private', {}, t.context.token1) authClient.on('message', data => { ++ctn