diff --git a/packages/@jsonql/security/README.md b/packages/@jsonql/security/README.md index 48ddc25743a415ee72d9e4125df3e16363c5a315..71a0ef87b61f5a85009da91c2738995bda068a44 100644 --- a/packages/@jsonql/security/README.md +++ b/packages/@jsonql/security/README.md @@ -2,11 +2,11 @@ > A collection of security related tools for jsonql -This library provide several JWT authenticatioin methods. +This library provides -CSRF token management - -Header check implementation +- several JWT authenticatioin methods +- CSRF token management +- Header check implementation and a few other things @@ -58,8 +58,6 @@ it will get you a whole different tool set for browser only. And it has a global --- -ISC - [Joel Chu](https://joelchu.com) -[NEWBRAN LTD](https://newbran.ch) (c) 2020 +[NEWBRAN LTD](https://newbran.ch) & [TO1SOURCE LTD](https://to1source.com) (c) 2020 diff --git a/packages/@jsonql/security/dist/jsonql-jwt.js b/packages/@jsonql/security/dist/jsonql-jwt.js deleted file mode 100644 index fe08afb500c7ce5d88f9c14c83cb0f3b221a904b..0000000000000000000000000000000000000000 --- a/packages/@jsonql/security/dist/jsonql-jwt.js +++ /dev/null @@ -1,2 +0,0 @@ -!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlJwt={})}(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})})); -//# sourceMappingURL=jsonql-jwt.js.map diff --git a/packages/@jsonql/security/dist/jsonql-jwt.js.map b/packages/@jsonql/security/dist/jsonql-jwt.js.map deleted file mode 100644 index f74b03f103a754a58fe9570ecf25e1aa4291b9a1..0000000000000000000000000000000000000000 --- a/packages/@jsonql/security/dist/jsonql-jwt.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"jsonql-jwt.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":"0qhBAAAA"} \ No newline at end of file diff --git a/packages/@jsonql/security/dist/jsonql-security.js b/packages/@jsonql/security/dist/jsonql-security.js new file mode 100644 index 0000000000000000000000000000000000000000..e492277e93abdc4391852a170b577acadbd4caaf --- /dev/null +++ b/packages/@jsonql/security/dist/jsonql-security.js @@ -0,0 +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})})); +//# 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 new file mode 100644 index 0000000000000000000000000000000000000000..6fd8220f5c7f75033cc809f8d782eb2e31d7e78e --- /dev/null +++ b/packages/@jsonql/security/dist/jsonql-security.js.map @@ -0,0 +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 diff --git a/packages/@jsonql/security/main.js b/packages/@jsonql/security/main.js index fe48fdf270a79e5f28599aed353cfdab3b20b782..83a1928a5f9a07d6055472607d3c2a9fda8e6d85 100644 --- a/packages/@jsonql/security/main.js +++ b/packages/@jsonql/security/main.js @@ -16,6 +16,13 @@ const { createTokenValidator } = require('./src/server') +const { + getNodeCache, + getToken, + createCSRFToken, + isCSRFTokenExist +} = require('./src/cache') + // output module.exports = { rsaKeys, @@ -33,5 +40,11 @@ module.exports = { tokenValidator, encryptWithPublicPem, - decryptWithPrivatePem + decryptWithPrivatePem, + + // new csrf and node cache related stuff + getNodeCache, + getToken, + createCSRFToken, + isCSRFTokenExist } diff --git a/packages/@jsonql/security/package.json b/packages/@jsonql/security/package.json index 476b9215ad16e84df787ce29e6b8e8a540b18704..4350f2321261574700b85fd45feab2d79572f9e2 100644 --- a/packages/@jsonql/security/package.json +++ b/packages/@jsonql/security/package.json @@ -1,6 +1,6 @@ { "name": "@jsonql/security", - "version": "1.0.0", + "version": "0.9.0", "description": "jwt authentication helpers library for jsonql browser / node", "main": "main.js", "module": "index.js", @@ -38,15 +38,17 @@ "license": "ISC", "dependencies": { "colors": "^1.4.0", - "fs-extra": "^8.1.0", - "jsonql-constants": "^2.0.2", + "fs-extra": "^9.0.0", + "jsonql-constants": "^2.0.10", "jsonql-errors": "^1.2.1", - "jsonql-params-validator": "^1.6.1", - "jsonql-utils": "^1.2.0", + "jsonql-params-validator": "^1.6.2", + "jsonql-utils": "^1.2.5", "jsonwebtoken": "^8.5.1", "jwt-decode": "^2.2.0", + "nanoid": "^2.1.11", + "node-cache": "^5.1.0", "socketio-jwt": "^4.5.0", - "yargs": "^15.3.0" + "yargs": "^15.3.1" }, "bin": { "jsonql-security": "./cmd.js" @@ -54,11 +56,11 @@ "devDependencies": { "socket.io-client": "^2.3.0", "ws": "^7.2.3", - "ava": "^3.5.0", + "ava": "^3.5.1", "debug": "^4.1.1", "esm": "^3.2.25", "koa": "^2.11.0", - "rollup": "^2.0.6", + "rollup": "^2.1.0", "rollup-plugin-alias": "^2.2.0", "rollup-plugin-async": "^1.2.0", "rollup-plugin-buble": "^0.19.8", diff --git a/packages/@jsonql/security/src/cache/csrf-methods.js b/packages/@jsonql/security/src/cache/csrf-methods.js new file mode 100644 index 0000000000000000000000000000000000000000..ae3d1eaf27c8e1a1ac1b85f0d5cb89115cff92e4 --- /dev/null +++ b/packages/@jsonql/security/src/cache/csrf-methods.js @@ -0,0 +1,48 @@ +const nanoid = require('nanoid') +const { JsonqlError } = require('jsonql-errors') +// const { getNodeCache } = require('./get-node-cache') +// call this first +// const store = getNodeCache() +const STORE_FAIL_ERR = 'unable to store the token in node cache!' + +/** + * Generate a token and check if it's in the store + * @param {object} store explicitly pass the store instead of using the global one + * @return {string} token + */ +function getToken(store) { + let token = nanoid() + // test if the token exist + if (store.has(token)) { + // call itself again until find a key not in store + return getToken(store) + } + return token +} + +/** + * create a set the token in store + * @param {object} store same as getToken + * @return {string} token + */ +function createCSRFToken(store) { + let token = getToken(store) + // not setting the TTL at the moment, but we should in the future + if (store.set(token, Date.now())) { + return token + } + throw new JsonqlError('createCSRFToken', STORE_FAIL_ERR) +} + +/** + * Check if the key existed + * @param {object} store the nodeCache + * @param {string} token token to check + * @return {boolean} + */ +function isCSRFTokenExist(store, token) { + return store.has(token) +} + + +module.exports = { getToken, createCSRFToken, isCSRFTokenExist } diff --git a/packages/@jsonql/security/src/cache/get-node-cache.js b/packages/@jsonql/security/src/cache/get-node-cache.js new file mode 100644 index 0000000000000000000000000000000000000000..a420d93a18fcc8ef9336a3b036ef8e85956c969c --- /dev/null +++ b/packages/@jsonql/security/src/cache/get-node-cache.js @@ -0,0 +1,45 @@ +// here is a problem +// because we need to use global property to store the node-cache instance +// how do we generate a dynamic key wihtout losing it? + +/* +stdTTL: (default: 0) the standard ttl as number in seconds for every generated cache element. 0 = unlimited +checkperiod: (default: 600) The period in seconds, as a number, used for the automatic delete check interval. 0 = no periodic check. +useClones: (default: true) en/disable cloning of variables. If true you'll get a copy of the cached variable. If false you'll save and get just the reference. +Note: +true is recommended if you want simplicity, because it'll behave like a server-based cache (it caches copies of plain data). +false is recommended if you want to achieve performance or save mutable objects or other complex types with mutability involved and wanted, because it'll only store references of your data. +Here's a simple code example showing the different behavior +deleteOnExpire: (default: true) whether variables will be deleted automatically when they expire. If true the variable will be deleted. If false the variable will remain. You are encouraged to handle the variable upon the event expired by yourself. +enableLegacyCallbacks: (default: false) re-enables the usage of callbacks instead of sync functions. Adds an additional cb argument to each function which resolves to (err, result). will be removed in node-cache v6.x. +maxKeys: (default: -1) specifies a maximum amount of keys that can be stored in the cache. If a new item is set and the cache is full, an error is thrown and the key will not be saved in the cache. -1 disables the key limit. +*/ + +// using node-cache to store can be throw away data +// here we implement a simple store to store the CSRF token +// in this structure {CSRF-TOKEN: TIMESTAMP} +// so you can check if this key actually exist or not +// const debug = require('debug')('jsonql-ws-server-core:share:get-node-cache') +const nodeCache = require('node-cache') +// need to rethink should we do it like this +global.jsonqlLocalNodeCacheStore = {} + +/** + * We don't want to init the node cache everytime + * so we put that in a global value + * @param {objec} opts configuration + * @return {object} the nodeCache instance + */ +function getNodeCache(opts = {}) { + + return new nodeCache(opts) + /* + if (!global.localNodeCacheStore) { + debug(`create new node cache`) + global.localNodeCacheStore = + } + return global.localNodeCacheStore + */ +} + +module.exports = { getNodeCache } \ No newline at end of file diff --git a/packages/@jsonql/security/src/cache/index.js b/packages/@jsonql/security/src/cache/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c4ac17a95362fdd549f762cca29620404712e694 --- /dev/null +++ b/packages/@jsonql/security/src/cache/index.js @@ -0,0 +1,11 @@ +// new node side cache module using node-cache and re-use everywhere +const { getNodeCache } = require('./get-node-cache') +const { getToken, createCSRFToken, isCSRFTokenExist } = require('./csrf-methods') + + +module.exports = { + getNodeCache, + getToken, + createCSRFToken, + isCSRFTokenExist +} \ No newline at end of file diff --git a/packages/@jsonql/security/tests/cache.test.js b/packages/@jsonql/security/tests/cache.test.js new file mode 100644 index 0000000000000000000000000000000000000000..4cb5b15355cb226dea96ad43e23f8836a79b6057 --- /dev/null +++ b/packages/@jsonql/security/tests/cache.test.js @@ -0,0 +1,24 @@ +// testing the cache with the associate methods +const test = require('ava') +const { + getNodeCache, + // getToken, + createCSRFToken, + isCSRFTokenExist +} = require('../src/cache') + +test.before(t => { + t.context.store = getNodeCache() +}) + +test(`Test the CSRF token get and store`, t => { + + const token = createCSRFToken(t.context.store) + + t.truthy(token, 'Should able to generate token') + + const existed = isCSRFTokenExist(t.context.store, token) + + t.true(existed, 'The token should existed') + +}) diff --git a/packages/jwt/README.md b/packages/jwt/README.md deleted file mode 100644 index 03a3f15700b96b68243afcc890ee029565a1875c..0000000000000000000000000000000000000000 --- a/packages/jwt/README.md +++ /dev/null @@ -1,54 +0,0 @@ -# jsonql-jwt - -> A jwt based authentication system for jsonql, including http and socket (socket.io and ws) - -This library provide several JWT authenticatioin methods used in several different jsonql modules. - - -## Installation - -```sh -$ npm i jsonql-jwt -``` - -### Node command line utility - -When you install this globally, you can use the command line utility. -You don't usually need to do this manually, this is build into each module -that require to generate the keys (i.e. [jsonql-koa](https://npmjs.com/package/jsonql-koa)) - -```sh -$ jsonql-jwt rsa-pem - -``` - -or - -```sh -$ node ./node_modules/jsonql-jwt/cmd.js -- rsa-pem -``` - -This will create a pair of `RSA256` public / private keys in `PEM` format. - -Or you can output that into a folder - -```sh -$ jsonql-jwt rsa-pem --outputDir ./path/to/directory - -``` - -### Browser tools - -This module export several different modules, when you use in node, it points to the `main.js` -But including the `dist/jsonql-jwt.js` will get you a whole different tool set for browser only. - -** T.B.C. ** - - ---- - -ISC - -[Joel Chu](https://joelchu.com) - -[NEWBRAN LTD](https://newbran.ch) (c) 2019 diff --git a/packages/jwt/client.js b/packages/jwt/client.js deleted file mode 100644 index 59802cb7fac51f67b222055c6260bc69c07ce133..0000000000000000000000000000000000000000 --- a/packages/jwt/client.js +++ /dev/null @@ -1,3 +0,0 @@ -// this will convert the ES6 to cjs for testing purpose -require = require('esm')(module) -module.exports = require('./index.js') diff --git a/packages/jwt/cmd.js b/packages/jwt/cmd.js deleted file mode 100644 index 1fbb10b73fcef69582f4fd2d398d8568060fedf6..0000000000000000000000000000000000000000 --- a/packages/jwt/cmd.js +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env node -// https://nodejs.org/api/crypto.html -// https://stackoverflow.com/questions/8520973/how-to-create-a-pair-private-public-keys-using-node-js-crypto -const { argv } = require('yargs') -const colors = require('colors/safe') -// const fsx = require('fs-extra') -// const debug = require('debug')('jsonql-jwt:cmd') - -const { version } = require('./package.json') -const { rsaKeys, jwtToken, rsaPemKeys } = require('./main') - -const saveMsg = () => { - console.info('-----------------------------------------') - console.info(colors.bgRed.white(`Please make a copy of these keys NOW!`)) -} - -// main method -const run = argv => { - let args = []; - console.info(colors.white(`Running jsonql-jwt cli version ${version}`)) - switch (argv._[0]) { - case 'rsa-keys': - args[0] = argv.format || undefined; - args[1] = argv.len || undefined; - const { publicKey, privateKey } = Reflect.apply(rsaKeys, null, args) - console.log(colors.yellow('[RSA key pairs result]')) - console.log('PUBLIC KEY: ', colors.bgCyan.black(publicKey)) - console.log('PRIVATE KEY: ', colors.bgYellow.black(privateKey)) - saveMsg() - break - case 'rsa-pem': - args[0] = argv.len || undefined; - args[1] = argv.outputDir || ''; - const p = Reflect.apply(rsaPemKeys, null, args) - p.then(result => { - if (!argv.outputDir) { - console.log('PUBLIC PEM KEY: \r\n', colors.bgCyan.black(result.publicKey)) - console.log('PRIVATE PEM KEY: \r\n', colors.bgYellow.black(result.privateKey)) - saveMsg() - } - }) - .catch(err => { - console.error(colors.red(err.message || err)) - }); - break - case 'token': - if (argv.secret && argv.payload) { - console.log(argv.payload) - try { - const payload = JSON.parse(JSON.stringify(argv.payload)) - const token = jwtToken(payload, argv.secret) - - console.log('JWT TOKEN: ', colors.bgCyan.black(token)) - - } catch(e) { - console.error('error!', colors.red(e)) - } - } - break - default: - console.log(colors.red('You need to tell me what you want!')) - } -} - -// now run it -run(argv) diff --git a/packages/jwt/dist/jsonql-jwt.js b/packages/jwt/dist/jsonql-jwt.js deleted file mode 100644 index fe08afb500c7ce5d88f9c14c83cb0f3b221a904b..0000000000000000000000000000000000000000 --- a/packages/jwt/dist/jsonql-jwt.js +++ /dev/null @@ -1,2 +0,0 @@ -!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlJwt={})}(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})})); -//# sourceMappingURL=jsonql-jwt.js.map diff --git a/packages/jwt/dist/jsonql-jwt.js.map b/packages/jwt/dist/jsonql-jwt.js.map deleted file mode 100644 index f74b03f103a754a58fe9570ecf25e1aa4291b9a1..0000000000000000000000000000000000000000 --- a/packages/jwt/dist/jsonql-jwt.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"jsonql-jwt.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":"0qhBAAAA"} \ No newline at end of file diff --git a/packages/jwt/index.js b/packages/jwt/index.js deleted file mode 100644 index 338f4f2516b184583971b467d49d7744300d9bd1..0000000000000000000000000000000000000000 --- a/packages/jwt/index.js +++ /dev/null @@ -1,10 +0,0 @@ -// main export interface for client side modules -import { - decodeToken, - tokenValidator -} from './module' - -export { - decodeToken, - tokenValidator -} diff --git a/packages/jwt/main.js b/packages/jwt/main.js deleted file mode 100644 index fe48fdf270a79e5f28599aed353cfdab3b20b782..0000000000000000000000000000000000000000 --- a/packages/jwt/main.js +++ /dev/null @@ -1,37 +0,0 @@ -// main export interface for node modules -// import export -const rsaKeys = require('./src/crypto/rsa-keys') -const rsaPemKeys = require('./src/crypto/rsa-pem-keys') -// const shaKey = require('./crypto/shaKey'); -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 { - loginResultToJwt, - provideUserdata, - createTokenValidator -} = require('./src/server') - -// output -module.exports = { - rsaKeys, - jwtToken, - jwtDecode, - jwtRsaToken, - - rsaPemKeys, - - loginResultToJwt, - provideUserdata, - createTokenValidator, - - decodeToken, - tokenValidator, - - encryptWithPublicPem, - decryptWithPrivatePem -} diff --git a/packages/jwt/module.js b/packages/jwt/module.js deleted file mode 100644 index d9caa27421fd4d6fdf3774ad2486ee94b752c1c4..0000000000000000000000000000000000000000 --- a/packages/jwt/module.js +++ /dev/null @@ -1,11 +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' - -export { - decodeToken, - tokenValidator -} diff --git a/packages/jwt/package.json b/packages/jwt/package.json deleted file mode 100644 index bd018a89eeb5a12950de2fbbec1192147b88729c..0000000000000000000000000000000000000000 --- a/packages/jwt/package.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "name": "jsonql-jwt", - "version": "1.3.10", - "description": "jwt authentication helpers library for jsonql browser / node", - "main": "main.js", - "module": "index.js", - "browser": "dist/jsonql-jwt.js", - "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:main": "rollup -c", - "build:decode": "rollup -c ./rollup.decode-jwt.config.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", - "prepare": "NODE_ENV=production npm run build" - }, - "files": [ - "cmd.js", - "index.js", - "main.js", - "module.js", - "src", - "dist" - ], - "keywords": [ - "jsonql", - "jwt", - "crypto", - "rsa256", - "socket.io", - "WebSocket" - ], - "author": "Joel Chu ", - "license": "ISC", - "dependencies": { - "colors": "^1.4.0", - "fs-extra": "^8.1.0", - "jsonql-constants": "^2.0.2", - "jsonql-errors": "^1.2.1", - "jsonql-params-validator": "^1.6.1", - "jsonql-utils": "^1.2.0", - "jsonwebtoken": "^8.5.1", - "jwt-decode": "^2.2.0", - "socketio-jwt": "^4.5.0", - "yargs": "^15.3.0" - }, - "bin": { - "jsonql-jwt": "./cmd.js" - }, - "devDependencies": { - "socket.io-client": "^2.3.0", - "ws": "^7.2.3", - "ava": "^3.5.0", - "debug": "^4.1.1", - "esm": "^3.2.25", - "koa": "^2.11.0", - "rollup": "^2.0.6", - "rollup-plugin-alias": "^2.2.0", - "rollup-plugin-async": "^1.2.0", - "rollup-plugin-buble": "^0.19.8", - "rollup-plugin-bundle-size": "^1.0.3", - "rollup-plugin-commonjs": "^10.1.0", - "rollup-plugin-copy": "^3.3.0", - "rollup-plugin-json": "^4.0.0", - "rollup-plugin-node-builtins": "^2.1.2", - "rollup-plugin-node-globals": "^1.4.0", - "rollup-plugin-node-resolve": "^5.2.0", - "rollup-plugin-replace": "^2.2.0", - "rollup-plugin-serve": "^1.0.1", - "rollup-plugin-terser": "^5.3.0", - "server-io-core": "^1.3.3", - "socket.io": "^2.3.0" - }, - "ava": { - "files": [ - "tests/**/*.test.js" - ], - "ignoredByWatcher": [ - "tests/fixtures/**/*.*" - ], - "require": [ - "esm" - ], - "cache": true, - "concurrency": 5, - "failFast": true, - "failWithoutAssertions": false, - "tap": false, - "verbose": true - }, - "engine": { - "node": ">=8" - }, - "homepage": "jsonql.org", - "repository": { - "type": "git", - "url": "git+ssh://git@gitee.com:to1source/jsonql.git" - } -} diff --git a/packages/jwt/rollup.config.js b/packages/jwt/rollup.config.js deleted file mode 100644 index a8aa3d275410713ce605a637257bb9cc2481ed80..0000000000000000000000000000000000000000 --- a/packages/jwt/rollup.config.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Rollup config for building the client package - */ -import { join } from 'path' -import buble from 'rollup-plugin-buble' - -import { terser } from "rollup-plugin-terser" -import replace from 'rollup-plugin-replace' -import commonjs from 'rollup-plugin-commonjs' - -import json from 'rollup-plugin-json' - -import nodeResolve from 'rollup-plugin-node-resolve' -import nodeGlobals from 'rollup-plugin-node-globals' -import builtins from 'rollup-plugin-node-builtins' -import size from 'rollup-plugin-bundle-size' -// support async functions -import async from 'rollup-plugin-async' -// get the version info -import { version } from './package.json' - -const env = process.env.NODE_ENV - -let plugins = [ - json({ - preferConst: true - }), - buble({ - objectAssign: 'Object.assign' - }), - nodeResolve({ preferBuiltins: true }), - commonjs({ - include: 'node_modules/**' - }), - nodeGlobals(), - builtins(), - async(), - replace({ - 'process.env.NODE_ENV': JSON.stringify('production'), - '__PLACEHOLDER__': `version: ${version} module: UMD` - }) -] -plugins.push(terser()) -if (env === 'production') { - -} -plugins.push(size()) - -let config = { - input: join(__dirname, 'index.js'), - output: { - name: 'jsonqlJwt', - file: join(__dirname, 'dist', 'jsonql-jwt.js'), - format: 'umd', - sourcemap: true, - globals: { - 'socket.io-client': 'io', - 'promise-polyfill': 'Promise', - 'debug': 'debug' - } - }, - external: [ - 'WebSocket', - 'socket.io-client', - 'io', - 'debug', - 'Promise', - 'promise-polyfill' - ], - plugins: plugins -}; - -export default config diff --git a/packages/jwt/rollup.decode-jwt.config.js b/packages/jwt/rollup.decode-jwt.config.js deleted file mode 100644 index bf5b4d94c83efc69d968f87eff93f17fe7d04ea0..0000000000000000000000000000000000000000 --- a/packages/jwt/rollup.decode-jwt.config.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Rollup config for just building out the decode token to share between cjs and browser - */ -import { join } from 'path' -import buble from 'rollup-plugin-buble' - -// import { terser } from "rollup-plugin-terser"; -import replace from 'rollup-plugin-replace' -import commonjs from 'rollup-plugin-commonjs' - -import json from 'rollup-plugin-json' - -import nodeResolve from 'rollup-plugin-node-resolve' -import nodeGlobals from 'rollup-plugin-node-globals' -import builtins from 'rollup-plugin-node-builtins' -import size from 'rollup-plugin-bundle-size' -// support async functions -import async from 'rollup-plugin-async' -// get the version info -import { version } from './package.json' - -const env = process.env.NODE_ENV - -let plugins = [ - json({ - preferConst: true - }), - buble({ - objectAssign: 'Object.assign' - }), - nodeResolve({ preferBuiltins: true }), - commonjs({ - include: 'node_modules/**' - }), - nodeGlobals(), - builtins(), - async(), - replace({ - 'process.env.NODE_ENV': JSON.stringify('production'), - '__PLACEHOLDER__': `version: ${version} module: ${env==='prod' ? 'cjs' : 'umd'}` - }), - size() -] - -let config = { - input: join(__dirname, 'src', 'client', 'index.js'), - output: { - name: 'jsonqlJwtHelpers', - file: join(__dirname, 'src', 'jwt', 'decode-token.js'), - format: 'cjs', - sourcemap: false, - globals: { - 'jwt-decode': 'jwt_decode', - 'jsonql-params-validator': 'jsonqlParamsValidator', - 'jsonql-errors': 'jsonqlErrors', - 'jsonwebtoken': 'jwt', - 'socket.io-client': 'io', - 'promise-polyfill': 'Promise', - 'debug': 'debug' - } - }, - external: [ - 'jwt-decode', - 'jsonql-params-validator', - 'jsonql-errors', - 'jsonwebtoken', - 'jwt', - 'WebSocket', - 'socket.io-client', - 'io', - 'debug', - 'Promise', - 'promise-polyfill' - ], - plugins: plugins -} - -export default config diff --git a/packages/jwt/src/client/decode-token/decode-token.js b/packages/jwt/src/client/decode-token/decode-token.js deleted file mode 100644 index 8a7817d809eed4c59ac134618637b8a7a5123d4b..0000000000000000000000000000000000000000 --- a/packages/jwt/src/client/decode-token/decode-token.js +++ /dev/null @@ -1,49 +0,0 @@ -// when the user is login with the jwt -// 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 isString from 'jsonql-params-validator/src/string' -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 - * @return {object} token on success - */ -function validate(token) { - const start = token.iat || timestamp(true) - // we only check the exp for the time being - if (token.exp) { - if (start >= token.exp) { - const expired = new Date(token.exp).toISOString() - throw new JsonqlError(`Token has expired on ${expired}`, token) - } - } - return token -} - -/** - * The browser client version it has far fewer options and it doesn't verify it - * because it couldn't this is the job for the server - * @TODO we need to add some extra proessing here to check for the exp field - * @param {string} token to decrypted - * @return {object} decrypted object - */ -export default function jwtDecode(token) { - if (isString(token)) { - const t = jwt_decode(token) - return validate(t) - } - throw new JsonqlError('Token must be a string!') -} diff --git a/packages/jwt/src/client/decode-token/token-validator.js b/packages/jwt/src/client/decode-token/token-validator.js deleted file mode 100644 index 7c80c50c316e249a7ed15cd5f3a7cf310315f98c..0000000000000000000000000000000000000000 --- a/packages/jwt/src/client/decode-token/token-validator.js +++ /dev/null @@ -1,63 +0,0 @@ -// we need to create a validator to check the token fields -// to determine if this token is valid of not -import { - BOOLEAN_TYPE, - STRING_TYPE, - NUMBER_TYPE, - OPTIONAL_KEY, - ALIAS_KEY, - HSA_ALGO -} from 'jsonql-constants' - -import { createConfig, checkConfig, isObject } from 'jsonql-params-validator' - -const appProps = { - algorithm: createConfig(HSA_ALGO, [STRING_TYPE]), - expiresIn: createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], { - [ALIAS_KEY]: 'exp' , [OPTIONAL_KEY]: true - }), - notBefore: createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], { - [ALIAS_KEY]: 'nbf', [OPTIONAL_KEY]: true - }), - audience: createConfig(false, [BOOLEAN_TYPE, STRING_TYPE], { - [ALIAS_KEY]: 'iss', [OPTIONAL_KEY]: true - }), - subject: createConfig(false, [BOOLEAN_TYPE, STRING_TYPE], { - [ALIAS_KEY]: 'sub', [OPTIONAL_KEY]: true - }), - issuer: createConfig(false, [BOOLEAN_TYPE, STRING_TYPE], { - [ALIAS_KEY]: 'iss', [OPTIONAL_KEY]: true - }), - noTimestamp: createConfig(false, [BOOLEAN_TYPE], { - [OPTIONAL_KEY]: true - }), - header: createConfig(false, [BOOLEAN_TYPE, STRING_TYPE], { - [OPTIONAL_KEY]: true - }), - keyid: createConfig(false, [BOOLEAN_TYPE, STRING_TYPE], { - [OPTIONAL_KEY]: true - }), - mutatePayload: createConfig(false, [BOOLEAN_TYPE], { - [OPTIONAL_KEY]: true - }) -} - -/** - * validate the token type - * @param {object} config options - * @return {object} tested result - */ -export default function tokenValidator(config) { - if (!isObject(config)) { - return {} // @TODO we just ignore it all together? - } - let result = {} - let opts = checkConfig(config, appProps) - // need to remove options that is false - for (let key in opts) { - if (opts[key]) { - result[key] = opts[key] - } - } - return result -} diff --git a/packages/jwt/src/client/index.js b/packages/jwt/src/client/index.js deleted file mode 100644 index dacf2e4cc916a05d18e228198104a901eafe1219..0000000000000000000000000000000000000000 --- a/packages/jwt/src/client/index.js +++ /dev/null @@ -1,8 +0,0 @@ -// this is the client side code interface using ES6 -import decodeToken from './decode-token/decode-token' -import tokenValidator from './decode-token/token-validator' - -export { - decodeToken, - tokenValidator -} diff --git a/packages/jwt/src/crypto/encrypt-decrypt.js b/packages/jwt/src/crypto/encrypt-decrypt.js deleted file mode 100644 index 5f9a4010ae433cd8f44f4587c17efe021f830905..0000000000000000000000000000000000000000 --- a/packages/jwt/src/crypto/encrypt-decrypt.js +++ /dev/null @@ -1,78 +0,0 @@ -const crypto = require('crypto') -const path = require('path') -const fs = require('fs-extra') -const { BASE64_FORMAT, UTF8_FORMAT } = require('jsonql-constants') - -/** - * Encrypt data with a public key in pem file format - * @param {*} toEncrypt data to encypt - * @param {string} relativeOrAbsolutePathToPublicKey path to pem public key file - */ -function encryptWithPublicPem(toEncrypt, relativeOrAbsolutePathToPublicKey) { - const absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey) - const publicKey = fs.readFileSync(absolutePath, UTF8_FORMAT) - const buffer = Buffer.from(toEncrypt, UTF8_FORMAT) - const encrypted = crypto.publicEncrypt(publicKey, buffer) - return encrypted.toString(BASE64_FORMAT) -} - -/** - * Decrypt the data with the public key in pem file format - * @param {*} toDecrypt data to decrypt - * @param {string} relativeOrAbsolutePathtoPrivateKey path to pem private key file - */ -function decryptWithPrivatePem(toDecrypt, relativeOrAbsolutePathtoPrivateKey) { - const absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey) - const privateKey = fs.readFileSync(absolutePath, UTF8_FORMAT) - const buffer = Buffer.from(toDecrypt, BASE64_FORMAT) - const decrypted = crypto.privateDecrypt( - { - key: privateKey.toString(), - passphrase: '', - }, - buffer, - ) - return decrypted.toString(UTF8_FORMAT) -} - - -/** - * not sure how to use it at the moment, but just put it here - * @param {*} str - * @param {*} publicKey - */ -function signObject(str, publicKey) { - const SIGN_KEY_NAME = 'RSA-SHA256' - - const signerObject = crypto.createSign(SIGN_KEY_NAME) - - signerObject.update(str) - - const signature = signerObject.sign({ - key: privateKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING - }, BASE64_FORMAT) - - console.info("signature: %s", signature) - - //verify String - const verifierObject = crypto.createVerify(SIGN_KEY_NAME) - - verifierObject.update(str) - - const verified = verifierObject.verify({ - key: publicKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING - }, signature, BASE64_FORMAT) - - console.info("is signature ok?: %s", verified) - - return verified -} - - -module.exports = { - signObject, - encryptWithPublicPem, - decryptWithPrivatePem -} diff --git a/packages/jwt/src/crypto/rsa-keys.js b/packages/jwt/src/crypto/rsa-keys.js deleted file mode 100644 index ed59e77a7a19f5459b47c78d4de4272b387a5ab7..0000000000000000000000000000000000000000 --- a/packages/jwt/src/crypto/rsa-keys.js +++ /dev/null @@ -1,24 +0,0 @@ -const crypto = require('crypto') -const { BASE64_FORMAT, RSA_FORMATS } = require('jsonql-constants') -const { inArray } = require('jsonql-params-validator') -const { JsonqlError } = require('jsonql-errors') -// HEX_FORMAT, -const PRIME_LENGTH = 60 - -/** - * create RSA public / private key pair - * @param {string} [format=BASE64_FORMAT] what format of key - * @param {number} [len=PRIME_LENGTH] prime length - * @return {object} publicKey, privateKey - */ -module.exports = function rsaKeys(format = BASE64_FORMAT, len = PRIME_LENGTH) { - if (len > 0 && inArray(RSA_FORMATS, format)) { - const diffHell = crypto.createDiffieHellman(len) - diffHell.generateKeys(format); - return { - publicKey: diffHell.getPublicKey(format), - privateKey: diffHell.getPrivateKey(format) - } - } - throw new JsonqlError(`Len(gth) must be greater than zero and format must be one of these two ${RSA_FORMATS}`) -} diff --git a/packages/jwt/src/crypto/rsa-pem-keys.js b/packages/jwt/src/crypto/rsa-pem-keys.js deleted file mode 100644 index 24bf1c23b8b8c497fee715208100d8a7129dd6a8..0000000000000000000000000000000000000000 --- a/packages/jwt/src/crypto/rsa-pem-keys.js +++ /dev/null @@ -1,113 +0,0 @@ -// generate the pem style keys -const { generateKeyPair } = require('crypto') -const fsx = require('fs-extra') -const { join, resolve } = require('path') -const colors = require('colors/safe') -const { - PEM_EXT, - RSA_MIN_MODULE_LEN, - RSA_MAX_MODULE_LEN, - DEFAULT_PRIVATE_KEY_FILE, - DEFAULT_PUBLIC_KEY_FILE -} = require('jsonql-constants') -const { JsonqlValidationError, JsonqlError } = require('jsonql-errors') - -/** - * Double check the input len - * @param {number} len modulusLength - * @return {number} on OK - */ -const checkLen = len => { - len = parseInt(len, 10) - if (isNaN(len)) { - throw new JsonqlValidationError(`modulusLength needs to be an integer!`); - } - if (len === RSA_MIN_MODULE_LEN || len === RSA_MAX_MODULE_LEN) { - return len; - } - if (len > RSA_MIN_MODULE_LEN && len < RSA_MAX_MODULE_LEN) { - let d = len / RSA_MIN_MODULE_LEN - if (d%2 === 0) { - return len - } - } - throw new JsonqlValidationError(`modulusLength needs to be squre by 2 and larger or equal to ${RSA_MIN_MODULE_LEN} and less than or equal to ${RSA_MAX_MODULE_LEN}`) -} - -/** - * write the files out to outputDir - * @param {object} result - * @param {string} result.publicKey - * @param {string} result.privateKey - * @return {object} promise resolve to publicKey / privateKey - */ -const outputToDir = (outputDir, result) => { - const dir = resolve(outputDir) - const { publicKey, privateKey } = result - const files = [publicKey, privateKey] - // @TODO use provide names - const names = [ - DEFAULT_PUBLIC_KEY_FILE, - DEFAULT_PRIVATE_KEY_FILE - ] - // the way this check is wrong ... - return Promise.all( - files.map((file, i) => { - let filePath = join(dir, names[i]) - return fsx.outputFile(filePath, file) - .then(() => { - let key = names[i].replace('.' + PEM_EXT, '') - return {[key]: filePath} - }) - }) - ).then(result => { - if (files.length === result.length) { - console.info(colors.green(`pem files written to ${dir}`)) - // we need to return an object instead of array - return result.reduce((next, last) => Object.assign(next, last), {}) - } - throw new JsonqlError('Something went wrong, some of the file are not written!', { files, result }) - }) - .catch(err => { - console.error(`[rsa-pem-keys] an error occuried!`, err) - }) -} - -/** - * generate a pair of public and private rsa keys in pem format - * @param {integer} len the length of the key - * @return {promise} resolve the publicKey privateKey - */ -function rsaPemKeysAction(len) { - return new Promise((resolver, rejecter) => { - generateKeyPair('rsa', { - modulusLength: checkLen(len), - publicKeyEncoding: { - type: 'spki', - format: 'pem' - }, - privateKeyEncoding: { - type: 'pkcs1', - format: 'pem' - // cipher: 'aes-256-cbc', - // passphrase: passphrase - } - }, (err, publicKey, privateKey) => { - if (err) { - return rejecter(err); - } - resolver({ publicKey, privateKey }) - }) - }) -} - -/** - * Wrap two steps into one with different parameters to control it - * @param {*} passphrase for rsa - * @param {number} [len = = RSA_MIN_MODULE_LEN] 1024 - * @param {*} outputDir for writing the files to - */ -module.exports = function rsaPemKeys(len = RSA_MIN_MODULE_LEN, outputDir = '') { - return rsaPemKeysAction(len) - .then(result => outputDir ? outputToDir(outputDir, result) : result) -} diff --git a/packages/jwt/src/jwt/decode-token.js b/packages/jwt/src/jwt/decode-token.js deleted file mode 100644 index b5e0f1ba0ebef9773dae1a9bbf8981dc44c99ab2..0000000000000000000000000000000000000000 --- a/packages/jwt/src/jwt/decode-token.js +++ /dev/null @@ -1,715 +0,0 @@ -'use strict'; - -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'); - -var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global$1 == 'object' && global$1 && global$1.Object === Object && global$1; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -/** Built-in value references. */ -var Symbol = root.Symbol; - -/** - * 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 arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} - -/** - * 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 = Array.isArray; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; - -/** Built-in value references. */ -var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; -} - -/** Used for built-in method references. */ -var objectProto$1 = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$1.toString; - -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString$1.call(value); -} - -/** `Object#toString` result references. */ -var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - -/** Built-in value references. */ -var symToStringTag$1 = Symbol ? Symbol.toStringTag : undefined; - -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag$1 && symToStringTag$1 in Object(value)) - ? getRawTag(value) - : objectToString(value); -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; -} - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** - * 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(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); -} - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolToString = symbolProto ? symbolProto.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(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-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(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(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(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(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(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(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(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, 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(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(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(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf(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(string) { - return string.split(''); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsVarRange = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsZWJ = '\\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 = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - -/** - * 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(string) { - return reHasUnicode.test(string); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange$1 = '\\ud800-\\udfff', - rsComboMarksRange$1 = '\\u0300-\\u036f', - reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', - rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', - rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, - rsVarRange$1 = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsAstral = '[' + rsAstralRange$1 + ']', - rsCombo = '[' + rsComboRange$1 + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange$1 + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsZWJ$1 = '\\u200d'; - -/** Used to compose unicode regexes. */ -var reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange$1 + ']?', - rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; -} - -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(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(value) { - return value == null ? '' : baseToString(value); -} - -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\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(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), - chrSymbols = stringToArray(chars), - start = charsStartIndex(strSymbols, chrSymbols), - end = charsEndIndex(strSymbols, chrSymbols) + 1; - - return castSlice(strSymbols, start, end).join(''); -} - -/** `Object#toString` result references. */ -var stringTag = '[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(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); -} - -// validate string type -/** - * @param {string} value expected value - * @return {boolean} true if OK - */ -var checkIsString = function(value) { - return (trim(value) !== '') ? isString(value) : false -}; - -var NO_STATUS_CODE = -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 = /*@__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 - }; - - Object.defineProperties( JsonqlError, staticAccessors ); - - return JsonqlError; -}(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 - * @return {object} token on success - */ -function validate(token) { - var start = token.iat || timestamp(true); - // we only check the exp for the time being - if (token.exp) { - if (start >= token.exp) { - var expired = new Date(token.exp).toISOString(); - throw new JsonqlError(("Token has expired on " + expired), token) - } - } - return token -} - -/** - * The browser client version it has far fewer options and it doesn't verify it - * because it couldn't this is the job for the server - * @TODO we need to add some extra proessing here to check for the exp field - * @param {string} token to decrypted - * @return {object} decrypted object - */ -function jwtDecode(token) { - if (checkIsString(token)) { - var t = jwt_decode(token); - return validate(t) - } - throw new JsonqlError('Token must be a string!') -} - -/* base.js */ -var OPTIONAL_KEY = 'optional'; -var ALIAS_KEY = 'alias'; -var HSA_ALGO = 'HS256'; -var STRING_TYPE = 'string'; -var BOOLEAN_TYPE = 'boolean'; - -var NUMBER_TYPE = 'number'; - -var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; - -var appProps = { - algorithm: jsonqlParamsValidator.createConfig(HSA_ALGO, [STRING_TYPE]), - expiresIn: jsonqlParamsValidator.createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), - notBefore: jsonqlParamsValidator.createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), - audience: jsonqlParamsValidator.createConfig(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), - subject: jsonqlParamsValidator.createConfig(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), - issuer: jsonqlParamsValidator.createConfig(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), - noTimestamp: jsonqlParamsValidator.createConfig(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), - header: jsonqlParamsValidator.createConfig(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), - keyid: jsonqlParamsValidator.createConfig(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), - mutatePayload: jsonqlParamsValidator.createConfig(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) -}; - -/** - * validate the token type - * @param {object} config options - * @return {object} tested result - */ -function tokenValidator(config) { - if (!jsonqlParamsValidator.isObject(config)) { - return {} // @TODO we just ignore it all together? - } - var result = {}; - var opts = jsonqlParamsValidator.checkConfig(config, appProps); - // need to remove options that is false - for (var key in opts) { - if (opts[key]) { - result[key] = opts[key]; - } - } - return result -} - -exports.decodeToken = jwtDecode; -exports.tokenValidator = tokenValidator; diff --git a/packages/jwt/src/jwt/jwt-decode.js b/packages/jwt/src/jwt/jwt-decode.js deleted file mode 100644 index 16f51d4134167e73cf08488ce74253ed2748daca..0000000000000000000000000000000000000000 --- a/packages/jwt/src/jwt/jwt-decode.js +++ /dev/null @@ -1,23 +0,0 @@ -const jwt = require('jsonwebtoken') -const { RSA_ALGO } = require('jsonql-constants') -const { isString } = require('jsonql-params-validator') -const { JsonqlError } = require('jsonql-errors') -const { buff } = require('jsonql-utils') -// variable -const baseOptions = { algorithms: RSA_ALGO } -/** - * @param {string} token to decrypted - * @param {string} key public key - * @param {object} [options=baseOptions] configuration options - * @return {object} decrypted object - */ -module.exports = function jwtDecode(token, key, options = {}) { - let opts = Object.assign({}, baseOptions, options) - if (isString(token)) { - if (options.algorithms === RSA_ALGO) { - key = buff(key) - } - return jwt.verify(token, key, opts) - } - throw new JsonqlError('Token must be a string!') -} diff --git a/packages/jwt/src/jwt/jwt-rsa-token.js b/packages/jwt/src/jwt/jwt-rsa-token.js deleted file mode 100644 index 1c27a7e354675b8bf7e11afc787987d6d0c7a675..0000000000000000000000000000000000000000 --- a/packages/jwt/src/jwt/jwt-rsa-token.js +++ /dev/null @@ -1,34 +0,0 @@ -const { - RSA_ALGO, - UTF8_FORMAT, - RSA_PRIVATE_KEY_HEADER -} = require('jsonql-constants') -const { JsonqlValidationError } = require('jsonql-errors') -const jwtToken = require('./jwt-token') -const baseOptions = { algorithm: RSA_ALGO }; -const debug = require('debug')('jsonql-jwt:jwt-rsa-token') -/** - * Double check if provided with a correct private Key - * @param {string|buffer} privateKey RSA format private key - * @return {boolean} true on OK - */ -function checkPrivateKey(privateKey) { - let s = Buffer.isBuffer(privateKey) ? privateKey.toString(UTF8_FORMAT) : privateKey; - if (s.indexOf(RSA_PRIVATE_KEY_HEADER) > -1) { - return true; - } - throw new JsonqlValidationError('Invalid RSA key format!') -} - -/** - * A wrapper method to generate RSA format token - the previous error was cause by the wrong options! - * @param {object} payload - * @param {string|buffer} privateKey the RSA format private key we should check if it's correct one - * @return {string} generated token - */ -module.exports = function jwtRsaToken(payload, privateKey, options = {}) { - debug('options', options) - checkPrivateKey(privateKey) - const config = Object.assign({}, options, baseOptions) - return jwtToken(payload, privateKey, config) -} diff --git a/packages/jwt/src/jwt/jwt-token.js b/packages/jwt/src/jwt/jwt-token.js deleted file mode 100644 index fbdde76f07ebb22a4b494ae56ef397d5af32394b..0000000000000000000000000000000000000000 --- a/packages/jwt/src/jwt/jwt-token.js +++ /dev/null @@ -1,38 +0,0 @@ -const jwt = require('jsonwebtoken') -// HSA_ALGO, , BASE64_FORMAT -const { RSA_ALGO } = require('jsonql-constants') -const { buff } = require('jsonql-utils') -const { tokenValidator } = require('./decode-token') - -// const baseOptions = { algorithm: HSA_ALGO } - -/* -NOTES about the options: - -algorithm -expiresIn --> exp -notBefore --> nbf -audience --> aud -issuer --> iss -subject --> sub -jwtid -noTimestamp -header -keyid -mutatePayload -*/ - -/** - * Generate a jwt token - * @param {object} payload object - * @param {string} secret private key or share secret - * @param {object} [options=baseOptions] configuration options - * @return {string} the token - */ -module.exports = function jwtToken(payload, secret, options = {}) { - if (options.algorithm === RSA_ALGO) { - secret = buff(secret) - } - const opts = tokenValidator(options) - return jwt.sign(payload, secret, opts) -} diff --git a/packages/jwt/src/server/auth/create-token-validator.js b/packages/jwt/src/server/auth/create-token-validator.js deleted file mode 100644 index 10361243ba3c41010fc38686be92b1ca49aa13f4..0000000000000000000000000000000000000000 --- a/packages/jwt/src/server/auth/create-token-validator.js +++ /dev/null @@ -1,30 +0,0 @@ -// const { join, resolve } = require('path') -const { JsonqlValidationError } = require('jsonql-errors') -const { isString } = require('jsonql-params-validator') -const { RSA_ALGO, HSA_ALGO } = require('jsonql-constants') -const jwtDecode = require('../../jwt/jwt-decode') - -/** - * This will overwrite the developer provide one when useJwt is enable - * @param {object} config configuration from the jsonql-koa - * @return {function} the token decode function - */ -module.exports = function createTokenValidator(config) { - const { useJwt, publicKey } = config - // const tokenOpts = tokenValidator(tokenOptions); - // debug('config', useJwt, publicKey, tokenOpts) - let key, opts; - if (isString(useJwt)) { - key = useJwt; - opts = { algorithms: HSA_ALGO } - } else { - key = publicKey; - opts = { algorithms: RSA_ALGO } - } - if (!key) { - throw new JsonqlValidationError(`key is not provided!`) - } - return function tokenValidator(token) { - return jwtDecode(token, key, opts) - } -} diff --git a/packages/jwt/src/server/auth/login-result-to-jwt.js b/packages/jwt/src/server/auth/login-result-to-jwt.js deleted file mode 100644 index 37d2967cd76d3b79009bdbfecf6208486834edf5..0000000000000000000000000000000000000000 --- a/packages/jwt/src/server/auth/login-result-to-jwt.js +++ /dev/null @@ -1,15 +0,0 @@ -const { RSA_ALGO } = require('jsonql-constants') -const jwtToken = require('../../jwt/jwt-token') -const jwtRsaToken = require('../../jwt/jwt-rsa-token') -/** - * This will take the developer provided login method result then create a jwt token with it - * @param {string} key to encrypt with - * @param {object} options for extra fields in the token - * @param {string} [alg = RSA_ALGO] algorithm to use, default to RSA256 - * @return {function} to accept the payload from the login method - */ -module.exports = function loginResultToJwt(key, options = {}, alg = RSA_ALGO) { - return payload => ( - alg === RSA_ALGO ? jwtRsaToken(payload, key, options) : jwtToken(payload, key, options) - ) -} diff --git a/packages/jwt/src/server/auth/provide-userdata.js b/packages/jwt/src/server/auth/provide-userdata.js deleted file mode 100644 index f7bb3e2471ce3c105a4fba935cb70899ca81eb3a..0000000000000000000000000000000000000000 --- a/packages/jwt/src/server/auth/provide-userdata.js +++ /dev/null @@ -1,12 +0,0 @@ -const { injectToFn } = require('jsonql-utils') -const { USERDATA_PROP_NAME } = require('jsonql-constants') -/** - * After the user login we will use this Object.define add a new property - * to the resolver with the decoded user data - * @param {function} resolver target resolver - * @param {object} userdata to add - * @return {function} added property resolver - */ -module.exports = function(resolver, userdata) { - return injectToFn(resolver, USERDATA_PROP_NAME, userdata, true) -} diff --git a/packages/jwt/src/server/index.js b/packages/jwt/src/server/index.js deleted file mode 100644 index 9a2802a2bd20187a8ef61d7d7464cef6c6d5704a..0000000000000000000000000000000000000000 --- a/packages/jwt/src/server/index.js +++ /dev/null @@ -1,20 +0,0 @@ -/* moved to @jsonql/socketio -const socketIoJwtAuth = require('./socketio/socketio-jwt-auth') -const socketIoHandshakeAuth = require('./socketio/handshake-auth') -const socketIoGetUserdata = require('./socketio/get-userdata') -*/ -/* moved to @jsonql/ws -const wsVerifyClient = require('./ws/verify-client') -const wsGetUserdata = require('./ws/get-userdata') -*/ -// auth -const loginResultToJwt = require('./auth/login-result-to-jwt') -const provideUserdata = require('./auth/provide-userdata') -const createTokenValidator = require('./auth/create-token-validator') - - -module.exports = { - loginResultToJwt, - provideUserdata, - createTokenValidator -} diff --git a/packages/jwt/tests/encrypt-decrypt.test.js b/packages/jwt/tests/encrypt-decrypt.test.js deleted file mode 100644 index cf9bcbd5ab1665b85ba40b77950902e07607f98b..0000000000000000000000000000000000000000 --- a/packages/jwt/tests/encrypt-decrypt.test.js +++ /dev/null @@ -1,23 +0,0 @@ -const test = require('ava') -const fsx = require('fs-extra') -const { join } = require('path') -const { - encryptWithPublicPem, - decryptWithPrivatePem -} = require('../main') -const base = join(__dirname, 'fixtures', 'keys') - -test.before( t => { - - t.context.publicKeyPath = join(base, 'publicKey.pem') - t.context.privateKeyPath = join(base, 'privateKey.pem') -}) - -test('It should able to encrypt with public key and decrypt with private key', t => { - const text = 'A little fox jump over the fence and drop dead!'; - - const cryptedText = encryptWithPublicPem(text, t.context.publicKeyPath) - - t.is(text, decryptWithPrivatePem(cryptedText, t.context.privateKeyPath)) - -}) diff --git a/packages/jwt/tests/fixtures/browser/index.html b/packages/jwt/tests/fixtures/browser/index.html deleted file mode 100644 index 52d27ff2275c4bfb4fc11a3b853e0bbfacaa28a5..0000000000000000000000000000000000000000 --- a/packages/jwt/tests/fixtures/browser/index.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - Testing the jsonql-jwt - - -

Testing the jsonql-jwt with browser

-
- - - - diff --git a/packages/jwt/tests/fixtures/keys/privateKey.pem b/packages/jwt/tests/fixtures/keys/privateKey.pem deleted file mode 100644 index ef22701fb7a8dc2b9e7afb96cb7737c83a275926..0000000000000000000000000000000000000000 --- a/packages/jwt/tests/fixtures/keys/privateKey.pem +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXAIBAAKBgQC6I8JkKfxpz7bZcB0UKA0wWl82epFdGIF3qRWY8rpsUR1kXAe3 -Fz0RFVUGUgd6Jv3fu59eg0awaLVHWs0n2mkdRDgXP3h8Va4O67trk1/RW1saabc7 -7DmXdgBUONH+g3Ria3XmwuDU3wNp4xfrTSpnr0RwtTY+9+ZoTRL/qFYOEQIDAQAB -AoGBALc+Hs9GegOchXAXK7k9GIbCYLsb/GB+kG3BWc6hHZ8mV14GL14yFV7s9i/r -rwq0ufZ4GRMM/xkJa3RcUlzqadDDUiDXbz7UnBKqMmQd8OkJLmfxYxNbUf8kA6j8 -WTV3WV/pyxwJtOGRTO68v2IGBBnaROiBzDOoRfDr6Px3rBmFAkEA7ycTJkq2GLpt -ivgHFEP8yW0uE9UTimEzGHUWWLSyrdtsUTpNs4klCM1/DPQgxAJM8UKjO6MGEWOo -WI7gaYwKAwJBAMdAo38YXL4tGd0VL8LdgYM6+OcdOcGbNmF+KM045udJiK6E0rL1 -B91sH5BW1O4h6TiEsbVYbWoQzTFbY7u+1VsCQANhC/Y4jAYhbDbQdlkk9Mdr0YDa -O+JyqSQpU12BgBzQwuEK79ofj/Rl4uut72CVn7yw8ll/XjCUteY6bpVPMz0CQHsV -bun//qpr6eIsSEiz1GFgeIksAJWcb8dhy4qab+jH/+rumcl6m9UoCYd8XCSORidn -sO85JL20i0zGC6HajKkCQHvLLpOlEtxmuQH8VXYdP0DS6EPzaKnYvGzyWxxafHGZ -wgp8wo8VLady7KE9/1PKLJr6QlvadVIybTDS4IGsutc= ------END RSA PRIVATE KEY----- diff --git a/packages/jwt/tests/fixtures/keys/publicKey.pem b/packages/jwt/tests/fixtures/keys/publicKey.pem deleted file mode 100644 index 98b99df1f655bc15c6703ab8541343a21aab6c26..0000000000000000000000000000000000000000 --- a/packages/jwt/tests/fixtures/keys/publicKey.pem +++ /dev/null @@ -1,6 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6I8JkKfxpz7bZcB0UKA0wWl82 -epFdGIF3qRWY8rpsUR1kXAe3Fz0RFVUGUgd6Jv3fu59eg0awaLVHWs0n2mkdRDgX -P3h8Va4O67trk1/RW1saabc77DmXdgBUONH+g3Ria3XmwuDU3wNp4xfrTSpnr0Rw -tTY+9+ZoTRL/qFYOEQIDAQAB ------END PUBLIC KEY----- diff --git a/packages/jwt/tests/fixtures/options.js b/packages/jwt/tests/fixtures/options.js deleted file mode 100644 index 22c476f01e9f6261395d702a5dea2647a34f1507..0000000000000000000000000000000000000000 --- a/packages/jwt/tests/fixtures/options.js +++ /dev/null @@ -1,10 +0,0 @@ -const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9lbCIsImlhdCI6MTU1OTM4MjUyM30.iMrI5lFQOklqgBFmtmON-NsRIQJkB5iSIqfCvov0wXM'; -const secret = '12345678'; -const namespace = 'jsonql'; -const msg = 'world!'; -module.exports = { - token, - secret, - namespace, - msg -}; diff --git a/packages/jwt/tests/fixtures/ws-server.js b/packages/jwt/tests/fixtures/ws-server.js deleted file mode 100644 index 33ba6de3ae457cdf2b05bd2a654bdae6e698b492..0000000000000000000000000000000000000000 --- a/packages/jwt/tests/fixtures/ws-server.js +++ /dev/null @@ -1,45 +0,0 @@ -// just create a simple ws server to test out why the hell -// the ws client is not working in browser -const { join } = require('path') -const url = require('url') -const serverIoCore = require('server-io-core') -const debug = require('debug')('jsonql-jwt:ws-server') -const WebSocket = require('ws') -const ws1 = new WebSocket.Server({ noServer: true }) -ws1.on('connection', function(ws) { - ws.on('open', function() { - debug('connection established') - }) - ws.on('message', function(msg) { - debug('I got something', msg) - ws.send('I got your message') - }) -}) - -// setting up server-io-core -const { start, webserver } = serverIoCore({ - webroot: [ - join(__dirname, 'browser'), - join(__dirname, '..', '..', 'dist') - ], - port: 3011, - debugger: false, - reload: false, - socket: false, - autoStart: false -}) - -// now setup WebSocket -webserver.on('upgrade', function upgrade(request, socket, head) { - const pathname = url.parse(request.url).pathname; - if (pathname === '/jsonql') { - ws1.handleUpgrade(request, socket, head, function done(ws) { - ws1.emit('connection', ws, request) - }) - } else { - socket.destory() - } -}) - -// now run -start() diff --git a/packages/jwt/tests/jwt-decode.test.js b/packages/jwt/tests/jwt-decode.test.js deleted file mode 100644 index 105290b1cf5baed374bd06341df4a2734a4aaee3..0000000000000000000000000000000000000000 --- a/packages/jwt/tests/jwt-decode.test.js +++ /dev/null @@ -1,60 +0,0 @@ -// testing the browser jwt-decode - -const test = require('ava') -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 { - loginResultToJwt, - createTokenValidator, - decodeToken, - tokenValidator -} = require('../main') - -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')); - - t.context.validator = createTokenValidator({ - useJwt: true, - publicKey - }) - - t.context.publicKey = publicKey - const options = {exp: 5}; // expired in 5 seconds - const token = loginResultToJwt(t.context.privateKey, options)(payload) - t.context.token = token; -}); - -test('try to see if its able to decode the token encrypted by rsa key', t => { - - let decodedPayload1 = t.context.validator(t.context.token) - t.true(decodedPayload1.name === payload.name) - -}) - -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 opts = tokenValidator(config) - - debug(opts) - - t.is(time, opts.expiresIn) -}) - -test('Check if the validation works inside the decodeToken when token is expired' , t => { - // t.plan(1) - const fn = () => decodeToken(t.context.token) - setTimeout(() => { - t.throws(() => { - fn() - }, null, 'Expect the decodeToken throw error because the token has expired') - }, 6000) - -}) diff --git a/packages/jwt/tests/rsa-keys.test.js b/packages/jwt/tests/rsa-keys.test.js deleted file mode 100644 index 5d810c50a642deaecf381982867f2c2c0789a513..0000000000000000000000000000000000000000 --- a/packages/jwt/tests/rsa-keys.test.js +++ /dev/null @@ -1,35 +0,0 @@ -// testing if the rsa generate key pair are working or not -const test = require('ava'); -const { join } = require('path') -const fsx = require('fs-extra') -const debug = require('debug')('jsonql-jwt:test:rsa-keys') -const { jwtRsaToken, jwtDecode, rsaPemKeys } = require('../main') -const payload = {name: 'Joel', msg: 'Hello world!'}; -const baseDir = join(__dirname, 'fixtures', 'keys') -const tmp = join(__dirname, 'fixtures', 'tmp') -// start test -test.before( t => { - t.context.publicKey = fsx.readFileSync(join(baseDir, 'publicKey.pem')) - t.context.privateKey = fsx.readFileSync(join(baseDir, 'privateKey.pem')) -}) - -test.after( t => { - fsx.removeSync(join(tmp, 'publicKey.pem')) - fsx.removeSync(join(tmp, 'privateKey.pem')) -}) - -test("It should able to use the privateKey encrypt a message and decrypt with the publicKey", t => { - const token = jwtRsaToken(payload, t.context.privateKey) - debug('token', token) - - const decodedPayload = jwtDecode(token, t.context.publicKey) - debug('decodedPayload', decodedPayload) - - t.true(decodedPayload.name === payload.name) -}) - -test("It should able to generate rsa keys pair and output to folder", async t => { - const files = await rsaPemKeys(1024, tmp) - debug('files', files) - t.truthy(files.publicKey && files.privateKey) -}) diff --git a/packages/jwt/tests/rsa-pem-keys.test.js b/packages/jwt/tests/rsa-pem-keys.test.js deleted file mode 100644 index 3b54c03ebb5bf1e7205b8fe70b3c72015924b2d7..0000000000000000000000000000000000000000 --- a/packages/jwt/tests/rsa-pem-keys.test.js +++ /dev/null @@ -1,45 +0,0 @@ -// test generate key pairs -const test = require('ava') -const { join, resolve } = require('path') -const fsx = require('fs-extra') -const { spawn } = require('child_process') -const debug = require('debug')('jsonql-jwt:test:rsa-pem-keys') - -const outputDir = join(__dirname, 'fixtures', 'tmp', 'pem-test') - -const pubKey = join(outputDir, 'publicKey.pem') -const prvKey = join(outputDir, 'privateKey.pem') - -test.after( t => { - // fsx.removeSync(outputDir) -}) - -test.cb('It should able to generate pair of public and private keys', t => { - t.plan(2) - - t.context.ps = spawn('node', [ - resolve(join(__dirname, '..' , 'cmd.js')), - 'rsa-pem', - '--outputDir', - outputDir - ]); - - t.context.ps.stdout.on('data', data => { - debug('stdout: ', data.toString()); - }); - - t.context.ps.stderr.on('data', data => { - debug('stderr: ', data.toString()); - }); - - t.context.ps.on('close', code => { - debug(`(1) Exited with ${code}`) - - t.truthy(fsx.existsSync(pubKey)) - t.truthy(fsx.existsSync(prvKey)) - - t.end(); - }); - - -}) diff --git a/packages/resolver/index.js b/packages/resolver/index.js index f68d16dcf18d2e1f28c7a79ee70a4b6c7a3a9f72..d9c58368945ac6ead01c18835ab44018f0d0d5f6 100644 --- a/packages/resolver/index.js +++ b/packages/resolver/index.js @@ -29,6 +29,17 @@ const { handleOutput, ctxErrorHandler } = require('./src/utils') +// new feature in 1.3.0 +const { + initCacheStore, + getCacheResolver, + cacheResolver, + isNodeCache +} = require('./src/cache') +const { + getCompleteSocketResolver +} = require('./src/combine-resolver') + // @TODO use the same for the jsonql-ws-server as well module.exports = { @@ -50,5 +61,12 @@ module.exports = { getNodeClientProvider, handleOutput, - ctxErrorHandler + ctxErrorHandler, + + initCacheStore, + getCacheResolver, + cacheResolver, + isNodeCache, + + getCompleteSocketResolver } diff --git a/packages/resolver/package.json b/packages/resolver/package.json index ee439f186709b9e19c905af7b4fc3c0acf69f655..4f8aaf27e23a6e0d200535e2a047aa8978e2ee72 100644 --- a/packages/resolver/package.json +++ b/packages/resolver/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-resolver", - "version": "1.2.0", + "version": "1.2.1", "description": "This is NOT for general use, please do not install it directly. This module is part of the jsonql tools supporting modules.", "main": "index.js", "files": [ @@ -10,6 +10,7 @@ "scripts": { "test": "ava", "prepare": "npm run test", + "test:combine": "DEBUG=jsonql-resolver* ava ./tests/combine.test.js", "test:socket": "DEBUG=jsonql-resolver* ava ./tests/socket.test.js", "test:base": "DEBUG=jsonql* ava ./tests/base.test.js", "test:clients": "DEBUG=jsonql* ava ./tests/clients.test.js", @@ -33,18 +34,18 @@ "url": "https://gitee.com/to1source/jsonql/issues" }, "dependencies": { + "@jsonql/security": "^0.9.0", "debug": "^4.1.1", - "jsonql-constants": "^2.0.6", + "jsonql-constants": "^2.0.10", "jsonql-errors": "^1.2.1", - "jsonql-jwt": "^1.3.10", "jsonql-node-client": "^1.3.1", - "jsonql-params-validator": "^1.6.1", - "jsonql-utils": "^1.2.4", + "jsonql-params-validator": "^1.6.2", + "jsonql-utils": "^1.2.5", "lodash.merge": "^4.6.2" }, "devDependencies": { - "ava": "^3.5.0", - "jsonql-contract": "^1.9.0", + "ava": "^3.5.1", + "jsonql-contract": "^1.9.1", "jsonql-koa": "^1.6.2", "server-io-core": "^1.3.3" }, diff --git a/packages/resolver/src/cache.js b/packages/resolver/src/cache.js new file mode 100644 index 0000000000000000000000000000000000000000..8b5dcc29375ba06fc9d5fb8574e1e5306b162e4d --- /dev/null +++ b/packages/resolver/src/cache.js @@ -0,0 +1,74 @@ +// Try to cache the resolver using the node-cache +/* +experiement using node-cache to store the result resolver + +several problems to note, +1. this is only the first part of the getting the resolver, in each framework inject extra properties to it +therefore simply cache this part is not enough +2. We probably have to create a new method that takes in a list of processor (injectors) take the result fn + and additional params, run through the injector, then we can cache this resolver + + +*/ +const NodeCache = require('node-cache') + +/** + * Wrapper method to init the NodeCache instance + * @param {object} [opts={}] configuration + * @return {object} node cache instance + */ +function initCacheStore(opts = {}) { + return new NodeCache(opts) +} + + +/** + * get it + * @param {*} key + * @param {*} store + * @return {*} false when not found + */ +function getCacheResolver(key, store) { + if (isNodeCache(store)) { + + return store.has(key) ? store.get(key) : false + } + + return false +} + + +/** + * We don't init the store here, we take the store then re-use to fetch the cache resolver + * @param {*} store store object + * @return {function} method to find the resolver + */ +function cacheResolver(store) { + /** + * Although we call it resolverName in the param but this will not just be the resolver name + * to avoid name collison + * @param {string} resolverName + * @return {function} resolver itself it found + */ + return function cacheResolverAction(resolverName, resolver) { + // the set return true on success, then we return the resolver for use next + return store.set(resolverName, resolver) ? resolver : false + } +} + +/** + * Just double check if the store is nodeCache + * @param {*} store + * @return {boolean} + */ +function isNodeCache(store) { + return store instanceof NodeCache +} + + +module.exports = { + initCacheStore, + getCacheResolver, + cacheResolver, + isNodeCache +} \ No newline at end of file diff --git a/packages/resolver/src/combine-resolver.js b/packages/resolver/src/combine-resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..1481eb3d162f386e3e05b8b36bfdcdbdd35d0321 --- /dev/null +++ b/packages/resolver/src/combine-resolver.js @@ -0,0 +1,61 @@ +// combine-resolver with cache and injectors +const { SOCKET_NAME } = require('jsonql-constants') +const { chainFns } = require('jsonql-utils') +const { isString } = require('jsonql-params-validator') + +const { getCacheResolver, cacheResolver } = require('./cache') +const { getResolver } = require('./resolve-methods') + + +/** + * this is a new feature that allow + * the framework to pass a list of injectors, and extra props + * then run through this to get the final injectors + * + * First we create one for the socket callback methods, because they don't hook into the rendering system + * + * 1. pass the original params that the retrieve resolver will get + * 2. pass the array of extra injectors, with their require parameters but leave out the resolver + * 3. then run its to get a complete resolver + * 4. With a additonal key property to id this resolver, and try to get from the cache first + * @param {string} resolverName name of the resolver + * @param {object} opts configuration + * @param {*} key to id the resolver + * @param {*} store instance of the nodeCache + * @return {function} the injectors chain for adding extra props to the fn + */ +function getCompleteSocketResolver(resolverName, opts, key = null, store = null) { + // the contract is within the opts + const { contract } = opts + const fn = getResolver(resolverName, SOCKET_NAME, contract, opts) + let resolver + // [deliverFn, resolverName, args, opts, ws, userdata] + if (isString(key) && store !== null) { + resolver = getCacheResolver(key, store) + if (resolver !== false) { + + return resolver + } + } + /** + * @param {array} injectors to run through the injection + * @param {array<*>} params then we add the resolver at the end to pass through the injectors + * @return {function} the complete resolver + */ + return function runInjectors(injectors, params) { + const executor = Reflect.apply(chainFns, null, injectors) + // please note the final injector must return just the resolver + const resolver = Reflect.apply(executor, null, [fn, ...params]) + + if (isString(key) && store !== null) { + const cacher = cacheResolver(store) + + return cacher(key, resolver) + } + + return resolver + } +} + + +module.exports = { getCompleteSocketResolver } \ No newline at end of file diff --git a/packages/resolver/src/resolve-methods.js b/packages/resolver/src/resolve-methods.js index 73cb3790e3c3142d44a9256d30c9134688cd145f..f97e0177eee39207128282b13435f76942da9912 100644 --- a/packages/resolver/src/resolve-methods.js +++ b/packages/resolver/src/resolve-methods.js @@ -10,7 +10,7 @@ const { UNKNOWN_ERROR } = require('jsonql-errors') // @TODO this should move to the jsonql-utils! -const { provideUserdata } = require('jsonql-jwt') +const { provideUserdata } = require('@jsonql/security') const { MODULE_TYPE } = require('jsonql-constants') const { packResult, diff --git a/packages/resolver/src/validate-and-call.js b/packages/resolver/src/validate-and-call.js index 28c97bbe8a513f1269affcda1970d54ee2920d9a..0c5f1511222367ae04dfe73c27dfd41f13ed2f49 100644 --- a/packages/resolver/src/validate-and-call.js +++ b/packages/resolver/src/validate-and-call.js @@ -1,13 +1,14 @@ // validation wrapper -const { AUTH_TYPE, HSA_ALGO, RSA_ALGO } = require('jsonql-constants') -const { validateSync, isString } = require('jsonql-params-validator') const { JsonqlValidationError, JsonqlResolverAppError, JsonqlAuthorisationError } = require('jsonql-errors') +const { AUTH_TYPE, HSA_ALGO, RSA_ALGO } = require('jsonql-constants') +const { validateSync, isString } = require('jsonql-params-validator') const { extractParamsFromContract } = require('jsonql-utils') -const { loginResultToJwt } = require('jsonql-jwt') +const { loginResultToJwt } = require('@jsonql/security') + const { getDebug } = require('./utils') const debug = getDebug('validate-and-call') // for caching @TODO should this be more a protective way to cache @@ -20,7 +21,7 @@ var resultMethod */ const getEncodeJwtMethod = opts => { if (resultMethod && typeof resultMethod === 'function') { - return resultMethod; + return resultMethod } let key = isString(opts.useJwt) ? opts.useJwt : opts.privateKey let alg = isString(opts.useJwt) ? HSA_ALGO : RSA_ALGO diff --git a/packages/resolver/tests/base.test.js b/packages/resolver/tests/base.test.js index 6b0757b7da2ace9daa36cbe3cbceb909753165c7..eef021afb4388a34761130c589cec64b47db67b7 100644 --- a/packages/resolver/tests/base.test.js +++ b/packages/resolver/tests/base.test.js @@ -15,6 +15,17 @@ test.before(async t => { } }) +test(`Just testing a way to pass an extra param to an array`, t => { + const value = 'a' + const values = ['b', 'c', 'd'] + + const params = [value, ...values] + + // console.info(params) + t.is(4, params.length) +}) + + test(`It should able to call a resolver`, async t => { const resolverName = 'getSomething' const payload = createQuery(resolverName, ['Joel']) diff --git a/packages/resolver/tests/combine.test.js b/packages/resolver/tests/combine.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2324accc26ade6005225e90a57b602a8db79275c --- /dev/null +++ b/packages/resolver/tests/combine.test.js @@ -0,0 +1,77 @@ +// test a new combine resolver and associate methods +const test = require('ava') +const { + isNodeCache, + getCompleteSocketResolver, + getCacheResolver +} = require('../index') +const NodeCache = require('node-cache') +const debug = require('debug')('jsonql-resolver:test:combine') +const fsx = require('fs-extra') +const { join } = require('path') +const { injectToFn, objHasProp } = require('jsonql-utils') + +test.before(t => { + t.context.nodeCacheInstance = new NodeCache() + t.context.contract = fsx.readJsonSync(join(__dirname, 'fixtures', 'contract', 'contract.json')) +}) + +test(`Testing the basic cache function first`, t => { + const nodeCacheInstance = t.context.nodeCacheInstance + const check = isNodeCache(nodeCacheInstance) + + t.true(check) +}) + +test(`Test the nodeCache interface`, t => { + const cache = t.context.nodeCacheInstance + const result = cache.set('some-key', 'some-value') + + t.true(result) +}) + +test(`Test the getCompleteSocketResolver method`, t => { + + const args = [ + 'sendSomething', + {contract: t.context.contract}, + 'sendSomething', + t.context.nodeCacheInstance + ] + + const runInjectorsFn = Reflect.apply(getCompleteSocketResolver, null, args) + const ts = Date.now() + // part 2 add injector + const injectors = [ + (fn, key, value) => { + // debug('pass fn with', fn, key, value) + return injectToFn(fn, key, value, true) + }, + (fn) => { + // debug('next pass with ', fn) + return injectToFn(fn, 'timestamp', ts) + } + ] + + const somekey = 'some-key' + const someval = 'some-value' + + const resolver = runInjectorsFn(injectors, [somekey, someval]) + + debug(somekey, objHasProp(resolver, somekey)) + + debug(resolver('na na na')) + + t.truthy(objHasProp(resolver, somekey)) + t.is(resolver.timestamp, ts) + + + const resolver1 = getCacheResolver('sendSomething', t.context.nodeCacheInstance) + + const msg = resolver1('la la la') + + debug('resolver1 result', msg) + + t.is(resolver1.timestamp, ts) + +}) \ No newline at end of file diff --git a/packages/utils/browser.js b/packages/utils/browser.js index 9221604117480aa91ab8f5b109536050215b43d3..a2433804dbc508733529cdff2ce61c690745d390 100644 --- a/packages/utils/browser.js +++ b/packages/utils/browser.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).jsonqlUtils={})}(this,(function(t){"use strict";var r=Array.isArray,e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof e&&e&&e.Object===Object&&e,o="object"==typeof self&&self&&self.Object===Object&&self,u=n||o||Function("return this")(),i=u.Symbol,a=Object.prototype,c=a.hasOwnProperty,f=a.toString,s=i?i.toStringTag:void 0;var l=Object.prototype.toString;var p=i?i.toStringTag:void 0;function v(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":p&&p in Object(t)?function(t){var r=c.call(t,s),e=t[s];try{t[s]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(r?t[s]=e:delete t[s]),o}(t):function(t){return l.call(t)}(t)}var d,y,h=(d=Object.getPrototypeOf,y=Object,function(t){return d(y(t))});function g(t){return null!=t&&"object"==typeof t}var _=Function.prototype,b=Object.prototype,j=_.toString,m=b.hasOwnProperty,O=j.call(Object);function w(t){if(!g(t)||"[object Object]"!=v(t))return!1;var r=h(t);if(null===r)return!0;var e=m.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&j.call(e)==O}var S=i?i.prototype:void 0,P=S?S.toString:void 0;function N(t){if("string"==typeof t)return t;if(r(t))return function(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}(o,u),function(t,r){for(var e=t.length;e--&&E(r,t[e],0)>-1;);return e}(o,u)+1).join("")}var I=function(t,r){return!!t.filter((function(t){return t===r})).length},Q=function(t){return r(t)?t:[t]},L=function(t,r){void 0===r&&(r=!0);try{return JSON.parse(t)}catch(e){if(r)return t;throw new Error(e)}},V=function(t,r){try{var e=Object.keys(t);return I(e,r)}catch(t){return!1}},W=function(t){return L("string"==typeof t?t:JSON.stringify(t))},H=function(){return!1};function K(t,r){return t===r||t!=t&&r!=r}function Z(t,r){for(var e=t.length;e--;)if(K(t[e][0],r))return e;return-1}var X=Array.prototype.splice;function Y(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},Y.prototype.set=function(t,r){var e=this.__data__,n=Z(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};function rt(t){if(!tt(t))return!1;var r=v(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}var et,nt=u["__core-js_shared__"],ot=(et=/[^.]+$/.exec(nt&&nt.keys&&nt.keys.IE_PROTO||""))?"Symbol(src)_1."+et:"";var ut=Function.prototype.toString;var it=/^\[object .+?Constructor\]$/,at=Function.prototype,ct=Object.prototype,ft=at.toString,st=ct.hasOwnProperty,lt=RegExp("^"+ft.call(st).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function pt(t){return!(!tt(t)||function(t){return!!ot&&ot in t}(t))&&(rt(t)?lt:it).test(function(t){if(null!=t){try{return ut.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function vt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return pt(e)?e:void 0}var dt=vt(u,"Map"),yt=vt(Object,"create");var ht=Object.prototype.hasOwnProperty;var gt=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 $t(t){return null!=t&&Gt(t.length)&&!rt(t)}var It="object"==typeof t&&t&&!t.nodeType&&t,Qt=It&&"object"==typeof module&&module&&!module.nodeType&&module,Lt=Qt&&Qt.exports===It?u.Buffer:void 0,Vt=(Lt?Lt.isBuffer:void 0)||function(){return!1},Wt={};Wt["[object Float32Array]"]=Wt["[object Float64Array]"]=Wt["[object Int8Array]"]=Wt["[object Int16Array]"]=Wt["[object Int32Array]"]=Wt["[object Uint8Array]"]=Wt["[object Uint8ClampedArray]"]=Wt["[object Uint16Array]"]=Wt["[object Uint32Array]"]=!0,Wt["[object Arguments]"]=Wt["[object Array]"]=Wt["[object ArrayBuffer]"]=Wt["[object Boolean]"]=Wt["[object DataView]"]=Wt["[object Date]"]=Wt["[object Error]"]=Wt["[object Function]"]=Wt["[object Map]"]=Wt["[object Number]"]=Wt["[object Object]"]=Wt["[object RegExp]"]=Wt["[object Set]"]=Wt["[object String]"]=Wt["[object WeakMap]"]=!1;var Ht="object"==typeof t&&t&&!t.nodeType&&t,Kt=Ht&&"object"==typeof module&&module&&!module.nodeType&&module,Zt=Kt&&Kt.exports===Ht&&n.process,Xt=function(){try{var t=Kt&&Kt.require&&Kt.require("util").types;return t||Zt&&Zt.binding&&Zt.binding("util")}catch(t){}}(),Yt=Xt&&Xt.isTypedArray,tr=Yt?function(t){return function(r){return t(r)}}(Yt):function(t){return g(t)&&Gt(t.length)&&!!Wt[v(t)]};function rr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var er=Object.prototype.hasOwnProperty;function nr(t,r,e){var n=t[r];er.call(t,r)&&K(n,e)&&(void 0!==e||r in t)||wt(t,r,e)}var or=/^(?:0|[1-9]\d*)$/;function ur(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)}}(gr);function jr(t,r){return br(function(t,r,e){return r=hr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=hr(n.length-r,0),i=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=mr.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!tt(e))return!1;var n=typeof r;return!!("number"==n?$t(e)&&ur(r,e.length):"string"==n&&r in e)&&K(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++e0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,Q(t))}),Reflect.apply(t,null,e))}},t.chainProcessPromises=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return t.then((function(t){return r(t)}))}),Reflect.apply(t,null,e))}},t.chainPromises=function(t,r){return void 0===r&&(r=!1),t.reduce((function(t,e){return t.then((function(t){return e.then((function(e){return!1===r?t.concat([e]):Or(t,e)}))}))}),Promise.resolve(!1===r?[]:w(r)?r:{}))},t.createAcknowledgeMsg=function(t,r,e){return void 0===e&&(e=[]),Wr("acknowledge_reply",t,r,e)},t.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},t.createMutation=Ur,t.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(Ur(t,r,e,n))},t.createQuery=qr,t.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(qr(t,r,e))},t.createReplyMsg=function(t,r,e){return void 0===e&&(e=[]),Wr("emit_reply",t,r,e)},t.createWsReply=Wr,t.dasherize=function(t){return $(t).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},t.extractArgsFromPayload=function(t,r){switch(r){case"query":return t.args;case"mutation":return[t.payload,t.condition];default:throw new Ar("Unknown "+r+" to extract argument from!")}},t.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new Pr(e,r);return n}catch(t){throw new Pr(e,t)}},t.extractSocketPart=Tr,t.extractWsPayload=function(t,r){void 0===r&&(r=H);try{var e,n=W(t);if(!1!==(e=Hr(n)))return r("TS",n.TS),{data:W(e.__data__),resolverName:e.__event__,type:e.__reply__};throw new Ar("payload can not decoded",t)}catch(t){return r("error",t)}},t.formatPayload=Jr,t.freeze=function(t){return Object.freeze(t)},t.getCallMethod=function(t){switch(!0){case t===Sr[0]:return"query";case t===Sr[1]:return"mutation";default:return!1}},t.getConfigValue=function(t,r){return r&&w(r)&&t in r?r[t]:void 0},t.getLogger=function(t){var r=[t];return function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];try{window&&window.JSONQL_DEBUG&&Reflect.apply(console.info,console,r.concat(t))}catch(t){}}},t.getMutationFromArgs=Gr,t.getMutationFromPayload=function(t){var r=Dr(t,Gr);if(!1!==r)return r;throw new Nr("[getMutationArgs] Payload is malformed!",t)},t.getNamespace=Qr,t.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},t.getNspInfoByConfig=function(t){var r=t.contract,e=t.enableAuth,n=Qr(t),o=e?Ir(r):function(t,r){var e,n={};for(var o in t){var u=t[o];n[o]=u}return{size:1,nspGroup:(e={},e[r]=n,e),publicNamespace:r}}(r.socket,n[0]);return Object.assign(o,{namespaces:n})},t.getPrivateNamespace=function(t){return t.length>1&&t[0]},t.getQueryFromArgs=Br,t.getQueryFromPayload=function(t){var r=Dr(t,Br);if(!1!==r)return r;throw new Nr("[getQueryArgs] Payload is malformed!",t)},t.getRegex=function(t){switch(!0){case!0===Lr(t):return t;case!0===kr(t):return new RegExp(t);default:return!1}},t.getResolverFromPayload=Mr,t.groupByNamespace=Ir,t.inArray=I,t.injectToFn=function(t,r,e,n){void 0===n&&(n=!1);var o=wr(t,r);return!1===n&&void 0!==o||Object.defineProperty(t,r,{value:e,writable:n}),t},t.isContract=function(t){return!!function(t){return w(t)&&(V(t,"query")||V(t,"mutation")||V(t,"socket"))}(t)&&t},t.isFunc=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},t.isJsonqlErrorObj=$r,t.isNotEmpty=function(t){return void 0!==t&&!1!==t&&null!==t&&""!==$(t)},t.isObjectHasKey=V,t.isRegExp=Lr,t.isWsReply=Hr,t.logger=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];try{window&&window.DEBUG&&Reflect.apply(console.log,console,t)}catch(t){}},t.nil=H,t.objDefineProps=function(t,r,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,r)&&Object.defineProperty(t,r,{set:e,get:null===n?function(){return null}:n}),t},t.objHasProp=wr,t.packError=function(t,r,e,n){var o;void 0===r&&(r="JsonqlError"),void 0===e&&(e=0),void 0===n&&(n="");var u={detail:t,className:r,statusCode:e,message:n};return JSON.stringify(((o={}).error=$r(t)||u,o.TS=[Er()],o))},t.packResult=function(t,e){void 0===e&&(e=!1);var n={};return n.data=t,e&&r(e)&&(e.push(Er()),n.TS=e),JSON.stringify(n)},t.parseJson=L,t.resultHandler=function(t){return V(t,"data")&&!V(t,"error")?t.data:t},t.timestamp=Er,t.toArray=Q,t.toJson=W,t.toPayload=Fr,t.urlParams=zr,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).jsonqlUtils={})}(this,(function(t){"use strict";var r=Array.isArray,e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof e&&e&&e.Object===Object&&e,o="object"==typeof self&&self&&self.Object===Object&&self,u=n||o||Function("return this")(),a=u.Symbol,i=Object.prototype,c=i.hasOwnProperty,f=i.toString,s=a?a.toStringTag:void 0;var l=Object.prototype.toString;var p=a?a.toStringTag:void 0;function v(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":p&&p in Object(t)?function(t){var r=c.call(t,s),e=t[s];try{t[s]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(r?t[s]=e:delete t[s]),o}(t):function(t){return l.call(t)}(t)}var d,y,h=(d=Object.getPrototypeOf,y=Object,function(t){return d(y(t))});function g(t){return null!=t&&"object"==typeof t}var _=Function.prototype,b=Object.prototype,j=_.toString,m=b.hasOwnProperty,O=j.call(Object);function w(t){if(!g(t)||"[object Object]"!=v(t))return!1;var r=h(t);if(null===r)return!0;var e=m.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&j.call(e)==O}var S=a?a.prototype:void 0,P=S?S.toString:void 0;function N(t){if("string"==typeof t)return t;if(r(t))return function(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}(o,u),function(t,r){for(var e=t.length;e--&&E(r,t[e],0)>-1;);return e}(o,u)+1).join("")}var I=function(t,r){return!!t.filter((function(t){return t===r})).length},Q=function(t){return r(t)?t:[t]},L=function(t,r){void 0===r&&(r=!0);try{return JSON.parse(t)}catch(e){if(r)return t;throw new Error(e)}},V=function(t,r){try{var e=Object.keys(t);return I(e,r)}catch(t){return!1}},W=function(t){return L("string"==typeof t?t:JSON.stringify(t))},H=function(){return!1};function K(t,r){return t===r||t!=t&&r!=r}function Z(t,r){for(var e=t.length;e--;)if(K(t[e][0],r))return e;return-1}var X=Array.prototype.splice;function Y(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},Y.prototype.set=function(t,r){var e=this.__data__,n=Z(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};function rt(t){if(!tt(t))return!1;var r=v(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}var et,nt=u["__core-js_shared__"],ot=(et=/[^.]+$/.exec(nt&&nt.keys&&nt.keys.IE_PROTO||""))?"Symbol(src)_1."+et:"";var ut=Function.prototype.toString;var at=/^\[object .+?Constructor\]$/,it=Function.prototype,ct=Object.prototype,ft=it.toString,st=ct.hasOwnProperty,lt=RegExp("^"+ft.call(st).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function pt(t){return!(!tt(t)||function(t){return!!ot&&ot in t}(t))&&(rt(t)?lt:at).test(function(t){if(null!=t){try{return ut.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function vt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return pt(e)?e:void 0}var dt=vt(u,"Map"),yt=vt(Object,"create");var ht=Object.prototype.hasOwnProperty;var gt=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 $t(t){return null!=t&&Gt(t.length)&&!rt(t)}var It="object"==typeof t&&t&&!t.nodeType&&t,Qt=It&&"object"==typeof module&&module&&!module.nodeType&&module,Lt=Qt&&Qt.exports===It?u.Buffer:void 0,Vt=(Lt?Lt.isBuffer:void 0)||function(){return!1},Wt={};Wt["[object Float32Array]"]=Wt["[object Float64Array]"]=Wt["[object Int8Array]"]=Wt["[object Int16Array]"]=Wt["[object Int32Array]"]=Wt["[object Uint8Array]"]=Wt["[object Uint8ClampedArray]"]=Wt["[object Uint16Array]"]=Wt["[object Uint32Array]"]=!0,Wt["[object Arguments]"]=Wt["[object Array]"]=Wt["[object ArrayBuffer]"]=Wt["[object Boolean]"]=Wt["[object DataView]"]=Wt["[object Date]"]=Wt["[object Error]"]=Wt["[object Function]"]=Wt["[object Map]"]=Wt["[object Number]"]=Wt["[object Object]"]=Wt["[object RegExp]"]=Wt["[object Set]"]=Wt["[object String]"]=Wt["[object WeakMap]"]=!1;var Ht="object"==typeof t&&t&&!t.nodeType&&t,Kt=Ht&&"object"==typeof module&&module&&!module.nodeType&&module,Zt=Kt&&Kt.exports===Ht&&n.process,Xt=function(){try{var t=Kt&&Kt.require&&Kt.require("util").types;return t||Zt&&Zt.binding&&Zt.binding("util")}catch(t){}}(),Yt=Xt&&Xt.isTypedArray,tr=Yt?function(t){return function(r){return t(r)}}(Yt):function(t){return g(t)&&Gt(t.length)&&!!Wt[v(t)]};function rr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var er=Object.prototype.hasOwnProperty;function nr(t,r,e){var n=t[r];er.call(t,r)&&K(n,e)&&(void 0!==e||r in t)||wt(t,r,e)}var or=/^(?:0|[1-9]\d*)$/;function ur(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)}}(gr);function jr(t,r){return br(function(t,r,e){return r=hr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=hr(n.length-r,0),a=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=mr.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!tt(e))return!1;var n=typeof r;return!!("number"==n?$t(e)&&ur(r,e.length):"string"==n&&r in e)&&K(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++e0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,Q(t))}),Reflect.apply(t,null,e))}},t.chainProcessPromises=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return t.then((function(t){return r(t)}))}),Reflect.apply(t,null,e))}},t.chainPromises=function(t,r){return void 0===r&&(r=!1),t.reduce((function(t,e){return t.then((function(t){return e.then((function(e){return!1===r?t.concat([e]):Or(t,e)}))}))}),Promise.resolve(!1===r?[]:w(r)?r:{}))},t.createAcknowledgeMsg=function(t,r,e){return void 0===e&&(e=[]),Wr("emit_acknowledge",t,r,e)},t.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},t.createMutation=Ur,t.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(Ur(t,r,e,n))},t.createQuery=qr,t.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(qr(t,r,e))},t.createReplyMsg=function(t,r,e){return void 0===e&&(e=[]),Wr("emit_reply",t,r,e)},t.createSendPayload=function(t,e,n){if(void 0===n&&(n=!1),kr(t)&&r(e)){var o=Cr(t,Jr(e),{type:"emit_send"});return n?JSON.stringify(o):o}throw new Nr("utils:socket:createSendMsg",{resolverName:t,args:e,message:"expect resolverName to be string and args to be array!"})},t.createWsReply=Wr,t.dasherize=function(t){return $(t).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},t.extractArgsFromPayload=function(t,r){switch(r){case"query":return t.args;case"mutation":return[t.payload,t.condition];default:throw new Ar("Unknown "+r+" to extract argument from!")}},t.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new Pr(e,r);return n}catch(t){throw new Pr(e,t)}},t.extractSocketPart=Tr,t.extractWsPayload=function(t,r){void 0===r&&(r=H);try{var e,n=W(t);if(!1!==(e=Hr(n)))return r("TS",n.TS),{data:W(e.__data__),resolverName:e.__event__,type:e.__reply__};throw new Ar("payload can not decoded",t)}catch(t){return r("error",t)}},t.formatPayload=Jr,t.freeze=function(t){return Object.freeze(t)},t.getCallMethod=function(t){switch(!0){case t===Sr[0]:return"query";case t===Sr[1]:return"mutation";default:return!1}},t.getConfigValue=function(t,r){return r&&w(r)&&t in r?r[t]:void 0},t.getLogger=function(t){var r=[t];return function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];try{window&&window.JSONQL_DEBUG&&Reflect.apply(console.info,console,r.concat(t))}catch(t){}}},t.getMutationFromArgs=Gr,t.getMutationFromPayload=function(t){var r=Dr(t,Gr);if(!1!==r)return r;throw new Nr("[getMutationArgs] Payload is malformed!",t)},t.getNamespace=Qr,t.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},t.getNspInfoByConfig=function(t){var r=t.contract,e=t.enableAuth,n=Qr(t),o=e?Ir(r):function(t,r){var e,n={};for(var o in t){var u=t[o];n[o]=u}return{size:1,nspGroup:(e={},e[r]=n,e),publicNamespace:r}}(r.socket,n[0]);return Object.assign(o,{namespaces:n})},t.getPrivateNamespace=function(t){return t.length>1&&t[0]},t.getQueryFromArgs=Br,t.getQueryFromPayload=function(t){var r=Dr(t,Br);if(!1!==r)return r;throw new Nr("[getQueryArgs] Payload is malformed!",t)},t.getRegex=function(t){switch(!0){case!0===Lr(t):return t;case!0===kr(t):return new RegExp(t);default:return!1}},t.getResolverFromPayload=Mr,t.groupByNamespace=Ir,t.inArray=I,t.injectToFn=function(t,r,e,n){void 0===n&&(n=!1);var o=wr(t,r);return!1===n&&void 0!==o||Object.defineProperty(t,r,{value:e,writable:n}),t},t.isContract=function(t){return!!function(t){return w(t)&&(V(t,"query")||V(t,"mutation")||V(t,"socket"))}(t)&&t},t.isFunc=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},t.isJsonqlErrorObj=$r,t.isNotEmpty=function(t){return void 0!==t&&!1!==t&&null!==t&&""!==$(t)},t.isObjectHasKey=V,t.isRegExp=Lr,t.isWsReply=Hr,t.logger=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];try{window&&window.DEBUG&&Reflect.apply(console.log,console,t)}catch(t){}},t.nil=H,t.objDefineProps=function(t,r,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,r)&&Object.defineProperty(t,r,{set:e,get:null===n?function(){return null}:n}),t},t.objHasProp=wr,t.packError=function(t,r,e,n){var o;void 0===r&&(r="JsonqlError"),void 0===e&&(e=0),void 0===n&&(n="");var u={detail:t,className:r,statusCode:e,message:n};return JSON.stringify(((o={}).error=$r(t)||u,o.TS=[Er()],o))},t.packResult=function(t,e){void 0===e&&(e=!1);var n={};return n.data=t,e&&r(e)&&(e.push(Er()),n.TS=e),JSON.stringify(n)},t.parseJson=L,t.resultHandler=function(t){return V(t,"data")&&!V(t,"error")?t.data:t},t.timestamp=Er,t.toArray=Q,t.toJson=W,t.toPayload=Fr,t.urlParams=xr,Object.defineProperty(t,"__esModule",{value:!0})})); //# sourceMappingURL=browser.js.map diff --git a/packages/utils/index.js b/packages/utils/index.js index d1c3487ff40cd1c0525b2c63d280891ceee8be60..361251154e32bf642349e1f6835a99ce312cd1aa 100644 --- a/packages/utils/index.js +++ b/packages/utils/index.js @@ -67,7 +67,8 @@ import { createReplyMsg, createAcknowledgeMsg, isWsReply, - extractWsPayload + extractWsPayload, + createSendPayload } from './module' import { buff } from './src/jwt' // node import @@ -165,5 +166,6 @@ export { createReplyMsg, createAcknowledgeMsg, isWsReply, - extractWsPayload + extractWsPayload, + createSendPayload } diff --git a/packages/utils/main.js b/packages/utils/main.js index 2da973490d02259dac4d12fbc2e00a54e4e5b5bd..5d5be4139a55421109692ba05186def17210ef82 100644 --- a/packages/utils/main.js +++ b/packages/utils/main.js @@ -1,2 +1,2 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,r=(t=require("fs"))&&"object"==typeof t&&"default"in t?t.default:t,e=require("path"),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,u="object"==typeof self&&self&&self.Object===Object&&self,a=i||u||Function("return this")(),f=a.Symbol,s=Object.prototype,c=s.hasOwnProperty,h=s.toString,p=f?f.toStringTag:void 0;var l=Object.prototype.toString;var g=f?f.toStringTag:void 0;function y(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":g&&g in Object(t)?function(t){var r=c.call(t,p),e=t[p];try{t[p]=void 0;var n=!0}catch(t){}var o=h.call(t);return n&&(r?t[p]=e:delete t[p]),o}(t):function(t){return l.call(t)}(t)}var v,d,_=(v=Object.getPrototypeOf,d=Object,function(t){return v(d(t))});function b(t){return null!=t&&"object"==typeof t}var w=Function.prototype,m=Object.prototype,A=w.toString,E=m.hasOwnProperty,x=A.call(Object);function j(t){if(!b(t)||"[object Object]"!=y(t))return!1;var r=_(t);if(null===r)return!0;var e=E.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&A.call(e)==x}var P=f?f.prototype:void 0,R=P?P.toString:void 0;function O(t){if("string"==typeof t)return t;if(n(t))return function(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 i=Array(o);++n-1;);return e}(o,i),function(t,r){for(var e=t.length;e--&&U(r,t[e],0)>-1;);return e}(o,i)+1).join("")}var G=function(t,r){return!!t.filter((function(t){return t===r})).length},Q=function(t){return n(t)?t:[t]},V=function(t,r){void 0===r&&(r=!0);try{return JSON.parse(t)}catch(e){if(r)return t;throw new Error(e)}},H=function(t,r){try{var e=Object.keys(t);return G(e,r)}catch(t){return!1}},W=function(t){return V("string"==typeof t?t:JSON.stringify(t))},Z=function(){return!1};function K(t,r){return t===r||t!=t&&r!=r}function X(t,r){for(var e=t.length;e--;)if(K(t[e][0],r))return e;return-1}var tt=Array.prototype.splice;function rt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},rt.prototype.set=function(t,r){var e=this.__data__,n=X(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};function nt(t){if(!et(t))return!1;var r=y(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}var ot,it=a["__core-js_shared__"],ut=(ot=/[^.]+$/.exec(it&&it.keys&&it.keys.IE_PROTO||""))?"Symbol(src)_1."+ot:"";var at=Function.prototype.toString;var ft=/^\[object .+?Constructor\]$/,st=Function.prototype,ct=Object.prototype,ht=st.toString,pt=ct.hasOwnProperty,lt=RegExp("^"+ht.call(pt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function gt(t){return!(!et(t)||function(t){return!!ut&&ut in t}(t))&&(nt(t)?lt:ft).test(function(t){if(null!=t){try{return at.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function yt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return gt(e)?e:void 0}var vt=yt(a,"Map"),dt=yt(Object,"create");var _t=Object.prototype.hasOwnProperty;var bt=Object.prototype.hasOwnProperty;function wt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=9007199254740991}function $t(t){return null!=t&&Jt(t.length)&&!nt(t)}var Gt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Qt=Gt&&"object"==typeof module&&module&&!module.nodeType&&module,Vt=Qt&&Qt.exports===Gt?a.Buffer:void 0,Ht=(Vt?Vt.isBuffer:void 0)||function(){return!1},Wt={};Wt["[object Float32Array]"]=Wt["[object Float64Array]"]=Wt["[object Int8Array]"]=Wt["[object Int16Array]"]=Wt["[object Int32Array]"]=Wt["[object Uint8Array]"]=Wt["[object Uint8ClampedArray]"]=Wt["[object Uint16Array]"]=Wt["[object Uint32Array]"]=!0,Wt["[object Arguments]"]=Wt["[object Array]"]=Wt["[object ArrayBuffer]"]=Wt["[object Boolean]"]=Wt["[object DataView]"]=Wt["[object Date]"]=Wt["[object Error]"]=Wt["[object Function]"]=Wt["[object Map]"]=Wt["[object Number]"]=Wt["[object Object]"]=Wt["[object RegExp]"]=Wt["[object Set]"]=Wt["[object String]"]=Wt["[object WeakMap]"]=!1;var Zt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Kt=Zt&&"object"==typeof module&&module&&!module.nodeType&&module,Xt=Kt&&Kt.exports===Zt&&i.process,tr=function(){try{var t=Kt&&Kt.require&&Kt.require("util").types;return t||Xt&&Xt.binding&&Xt.binding("util")}catch(t){}}(),rr=tr&&tr.isTypedArray,er=rr?function(t){return function(r){return t(r)}}(rr):function(t){return b(t)&&Jt(t.length)&&!!Wt[y(t)]};function nr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var or=Object.prototype.hasOwnProperty;function ir(t,r,e){var n=t[r];or.call(t,r)&&K(n,e)&&(void 0!==e||r in t)||jt(t,r,e)}var ur=/^(?:0|[1-9]\d*)$/;function ar(t,r){var e=typeof t;return!!(r=null==r?9007199254740991:r)&&("number"==e||"symbol"!=e&&ur.test(t))&&t>-1&&t%1==0&&t0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(br);function Ar(t,r){return mr(function(t,r,e){return r=_r(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,i=_r(n.length-r,0),u=Array(i);++o1?r[n-1]:void 0,i=n>2?r[2]:void 0;for(o=Er.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,r,e){if(!et(e))return!1;var n=typeof r;return!!("number"==n?$t(e)&&ar(r,e.length):"string"==n&&r in e)&&K(e[r],t)}(r[0],r[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++e>18&63]+re[o>>12&63]+re[o>>6&63]+re[63&o]);return i.join("")}function ae(t){var r;oe||ie();for(var e=t.length,n=e%3,o="",i=[],u=0,a=e-n;ua?a:u+16383));return 1===n?(r=t[e-1],o+=re[r>>2],o+=re[r<<4&63],o+="=="):2===n&&(r=(t[e-2]<<8)+t[e-1],o+=re[r>>10],o+=re[r>>4&63],o+=re[r<<2&63],o+="="),i.push(o),i.join("")}function fe(t,r,e,n,o){var i,u,a=8*o-n-1,f=(1<>1,c=-7,h=e?o-1:0,p=e?-1:1,l=t[r+h];for(h+=p,i=l&(1<<-c)-1,l>>=-c,c+=a;c>0;i=256*i+t[r+h],h+=p,c-=8);for(u=i&(1<<-c)-1,i>>=-c,c+=n;c>0;u=256*u+t[r+h],h+=p,c-=8);if(0===i)i=1-s;else{if(i===f)return u?NaN:1/0*(l?-1:1);u+=Math.pow(2,n),i-=s}return(l?-1:1)*u*Math.pow(2,i-n)}function se(t,r,e,n,o,i){var u,a,f,s=8*i-o-1,c=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,l=n?0:i-1,g=n?1:-1,y=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(a=isNaN(r)?1:0,u=c):(u=Math.floor(Math.log(r)/Math.LN2),r*(f=Math.pow(2,-u))<1&&(u--,f*=2),(r+=u+h>=1?p/f:p*Math.pow(2,1-h))*f>=2&&(u++,f/=2),u+h>=c?(a=0,u=c):u+h>=1?(a=(r*f-1)*Math.pow(2,o),u+=h):(a=r*Math.pow(2,h-1)*Math.pow(2,o),u=0));o>=8;t[e+l]=255&a,l+=g,a/=256,o-=8);for(u=u<0;t[e+l]=255&u,l+=g,u/=256,s-=8);t[e+l-g]|=128*y}var ce={}.toString,he=Array.isArray||function(t){return"[object Array]"==ce.call(t)};function pe(){return ge.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function le(t,r){if(pe()=pe())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+pe().toString(16)+" bytes");return 0|t}function we(t){return!(null==t||!t._isBuffer)}function me(t,r){if(we(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var e=t.length;if(0===e)return 0;for(var n=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return Qe(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return Ve(t).length;default:if(n)return Qe(t).length;r=(""+r).toLowerCase(),n=!0}}function Ae(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return Ye(this,r,e);case"utf8":case"utf-8":return Ne(this,r,e);case"ascii":return Ie(this,r,e);case"latin1":case"binary":return Ce(this,r,e);case"base64":return Be(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Me(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function Ee(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function xe(t,r,e,n,o){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=o?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(o)return-1;e=t.length-1}else if(e<0){if(!o)return-1;e=0}if("string"==typeof r&&(r=ge.from(r,n)),we(r))return 0===r.length?-1:je(t,r,e,n,o);if("number"==typeof r)return r&=255,ge.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):je(t,[r],e,n,o);throw new TypeError("val must be string, number or Buffer")}function je(t,r,e,n,o){var i,u=1,a=t.length,f=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;u=2,a/=2,f/=2,e/=2}function s(t,r){return 1===u?t[r]:t.readUInt16BE(r*u)}if(o){var c=-1;for(i=e;ia&&(e=a-f),i=e;i>=0;i--){for(var h=!0,p=0;po&&(n=o):n=o;var i=r.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var u=0;u>8,o=e%256,i.push(o),i.push(n);return i}(r,t.length-e),t,e,n)}function Be(t,r,e){return 0===r&&e===t.length?ae(t):ae(t.slice(r,e))}function Ne(t,r,e){e=Math.min(t.length,e);for(var n=[],o=r;o239?4:s>223?3:s>191?2:1;if(o+h<=e)switch(h){case 1:s<128&&(c=s);break;case 2:128==(192&(i=t[o+1]))&&(f=(31&s)<<6|63&i)>127&&(c=f);break;case 3:i=t[o+1],u=t[o+2],128==(192&i)&&128==(192&u)&&(f=(15&s)<<12|(63&i)<<6|63&u)>2047&&(f<55296||f>57343)&&(c=f);break;case 4:i=t[o+1],u=t[o+2],a=t[o+3],128==(192&i)&&128==(192&u)&&128==(192&a)&&(f=(15&s)<<18|(63&i)<<12|(63&u)<<6|63&a)>65535&&f<1114112&&(c=f)}null===c?(c=65533,h=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),o+=h}return function(t){var r=t.length;if(r<=4096)return String.fromCharCode.apply(String,t);var e="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},ge.prototype.compare=function(t,r,e,n,o){if(!we(t))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),r<0||e>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=e)return 0;if(n>=o)return-1;if(r>=e)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),u=(e>>>=0)-(r>>>=0),a=Math.min(i,u),f=this.slice(n,o),s=t.slice(r,e),c=0;co)&&(e=o),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return Pe(this,t,r,e);case"utf8":case"utf-8":return Re(this,t,r,e);case"ascii":return Oe(this,t,r,e);case"latin1":case"binary":return Te(this,t,r,e);case"base64":return Se(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ue(this,t,r,e);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},ge.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ie(t,r,e){var n="";e=Math.min(t.length,e);for(var o=r;on)&&(e=n);for(var o="",i=r;ie)throw new RangeError("Trying to access beyond buffer length")}function De(t,r,e,n,o,i){if(!we(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>o||rt.length)throw new RangeError("Index out of range")}function ze(t,r,e,n){r<0&&(r=65535+r+1);for(var o=0,i=Math.min(t.length-e,2);o>>8*(n?o:1-o)}function Le(t,r,e,n){r<0&&(r=4294967295+r+1);for(var o=0,i=Math.min(t.length-e,4);o>>8*(n?o:3-o)&255}function Fe(t,r,e,n,o,i){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function qe(t,r,e,n,o){return o||Fe(t,0,e,4),se(t,r,e,n,23,4),e+4}function Je(t,r,e,n,o){return o||Fe(t,0,e,8),se(t,r,e,n,52,8),e+8}ge.prototype.slice=function(t,r){var e,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(r=void 0===r?n:~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),r0&&(o*=256);)n+=this[t+--r]*o;return n},ge.prototype.readUInt8=function(t,r){return r||ke(t,1,this.length),this[t]},ge.prototype.readUInt16LE=function(t,r){return r||ke(t,2,this.length),this[t]|this[t+1]<<8},ge.prototype.readUInt16BE=function(t,r){return r||ke(t,2,this.length),this[t]<<8|this[t+1]},ge.prototype.readUInt32LE=function(t,r){return r||ke(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},ge.prototype.readUInt32BE=function(t,r){return r||ke(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},ge.prototype.readIntLE=function(t,r,e){t|=0,r|=0,e||ke(t,r,this.length);for(var n=this[t],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*r)),n},ge.prototype.readIntBE=function(t,r,e){t|=0,r|=0,e||ke(t,r,this.length);for(var n=r,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*r)),i},ge.prototype.readInt8=function(t,r){return r||ke(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},ge.prototype.readInt16LE=function(t,r){r||ke(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},ge.prototype.readInt16BE=function(t,r){r||ke(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},ge.prototype.readInt32LE=function(t,r){return r||ke(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},ge.prototype.readInt32BE=function(t,r){return r||ke(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},ge.prototype.readFloatLE=function(t,r){return r||ke(t,4,this.length),fe(this,t,!0,23,4)},ge.prototype.readFloatBE=function(t,r){return r||ke(t,4,this.length),fe(this,t,!1,23,4)},ge.prototype.readDoubleLE=function(t,r){return r||ke(t,8,this.length),fe(this,t,!0,52,8)},ge.prototype.readDoubleBE=function(t,r){return r||ke(t,8,this.length),fe(this,t,!1,52,8)},ge.prototype.writeUIntLE=function(t,r,e,n){(t=+t,r|=0,e|=0,n)||De(this,t,r,e,Math.pow(2,8*e)-1,0);var o=1,i=0;for(this[r]=255&t;++i=0&&(i*=256);)this[r+o]=t/i&255;return r+e},ge.prototype.writeUInt8=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,1,255,0),ge.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[r]=255&t,r+1},ge.prototype.writeUInt16LE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,2,65535,0),ge.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):ze(this,t,r,!0),r+2},ge.prototype.writeUInt16BE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,2,65535,0),ge.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):ze(this,t,r,!1),r+2},ge.prototype.writeUInt32LE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,4,4294967295,0),ge.TYPED_ARRAY_SUPPORT?(this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t):Le(this,t,r,!0),r+4},ge.prototype.writeUInt32BE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,4,4294967295,0),ge.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):Le(this,t,r,!1),r+4},ge.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r|=0,!n){var o=Math.pow(2,8*e-1);De(this,t,r,e,o-1,-o)}var i=0,u=1,a=0;for(this[r]=255&t;++i>0)-a&255;return r+e},ge.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r|=0,!n){var o=Math.pow(2,8*e-1);De(this,t,r,e,o-1,-o)}var i=e-1,u=1,a=0;for(this[r+i]=255&t;--i>=0&&(u*=256);)t<0&&0===a&&0!==this[r+i+1]&&(a=1),this[r+i]=(t/u>>0)-a&255;return r+e},ge.prototype.writeInt8=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,1,127,-128),ge.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[r]=255&t,r+1},ge.prototype.writeInt16LE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,2,32767,-32768),ge.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):ze(this,t,r,!0),r+2},ge.prototype.writeInt16BE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,2,32767,-32768),ge.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):ze(this,t,r,!1),r+2},ge.prototype.writeInt32LE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,4,2147483647,-2147483648),ge.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24):Le(this,t,r,!0),r+4},ge.prototype.writeInt32BE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),ge.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):Le(this,t,r,!1),r+4},ge.prototype.writeFloatLE=function(t,r,e){return qe(this,t,r,!0,e)},ge.prototype.writeFloatBE=function(t,r,e){return qe(this,t,r,!1,e)},ge.prototype.writeDoubleLE=function(t,r,e){return Je(this,t,r,!0,e)},ge.prototype.writeDoubleBE=function(t,r,e){return Je(this,t,r,!1,e)},ge.prototype.copy=function(t,r,e,n){if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r=0;--o)t[o+r]=this[o+e];else if(i<1e3||!ge.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,e=void 0===e?this.length:e>>>0,t||(t=0),"number"==typeof t)for(i=r;i55295&&e<57344){if(!o){if(e>56319){(r-=3)>-1&&i.push(239,191,189);continue}if(u+1===n){(r-=3)>-1&&i.push(239,191,189);continue}o=e;continue}if(e<56320){(r-=3)>-1&&i.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(r-=3)>-1&&i.push(239,191,189);if(o=null,e<128){if((r-=1)<0)break;i.push(e)}else if(e<2048){if((r-=2)<0)break;i.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;i.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return i}function Ve(t){return function(t){var r,e,n,o,i,u;oe||ie();var a=t.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===t[a-2]?2:"="===t[a-1]?1:0,u=new ne(3*a/4-i),n=i>0?a-4:a;var f=0;for(r=0,e=0;r>16&255,u[f++]=o>>8&255,u[f++]=255&o;return 2===i?(o=ee[t.charCodeAt(r)]<<2|ee[t.charCodeAt(r+1)]>>4,u[f++]=255&o):1===i&&(o=ee[t.charCodeAt(r)]<<10|ee[t.charCodeAt(r+1)]<<4|ee[t.charCodeAt(r+2)]>>2,u[f++]=o>>8&255,u[f++]=255&o),u}(function(t){if((t=function(t){if(t.trim)return t.trim();return t.replace(/^\s+|\s+$/g,"")}(t).replace($e,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function He(t,r,e,n){for(var o=0;o=r.length||o>=t.length);++o)r[o+e]=t[o];return o}function We(t){return null!=t&&(!!t._isBuffer||Ze(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&Ze(t.slice(0,0))}(t))}function Ze(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}var Ke=function(t,r){if(r instanceof Error){var e={};return Object.getOwnPropertyNames(r).forEach((function(t){e[t]=r[t]})),e}return r};var Xe=function(t,r){try{var e=t.headers.accept.split(",");return r?e.filter((function(t){return t===r})):e}catch(t){return[]}},tn=function(t,r){return!!Xe(t,r).length},rn=function(t,r){return t.path===r.jsonqlPath};exports.VERSION="1.2.4",exports.assign=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return Reflect.apply(Object.assign,Object,t)},exports.buff=function(t,r){return void 0===r&&(r="base64"),We(t)?t:new ge.from(t,r)},exports.cacheBurst=Yr,exports.cacheBurstUrl=function(t){return Cr(t,Yr())},exports.chainFns=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,Q(t))}),Reflect.apply(t,null,e))}},exports.chainPromises=function(t,r){return void 0===r&&(r=!1),t.reduce((function(t,e){return t.then((function(t){return e.then((function(e){return!1===r?t.concat([e]):xr(t,e)}))}))}),Promise.resolve(!1===r?[]:j(r)?r:{}))},exports.createAcknowledgeMsg=function(t,r,e){return void 0===e&&(e=[]),Xr("acknowledge_reply",t,r,e)},exports.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},exports.createMutation=Jr,exports.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(Jr(t,r,e,n))},exports.createQuery=qr,exports.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(qr(t,r,e))},exports.createReplyMsg=function(t,r,e){return void 0===e&&(e=[]),Xr("emit_reply",t,r,e)},exports.createWsReply=Xr,exports.dasherize=Ir,exports.extractArgsFromPayload=function(t,r){switch(r){case"query":return t.args;case"mutation":return[t.payload,t.condition];default:throw new Ur("Unknown "+r+" to extract argument from!")}},exports.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new Tr(e,r);return n}catch(t){throw new Tr(e,t)}},exports.extractSocketPart=Br,exports.extractWsPayload=function(t,r){void 0===r&&(r=Z);try{var e,n=W(t);if(!1!==(e=te(n)))return r("TS",n.TS),{data:W(e.__data__),resolverName:e.__event__,type:e.__reply__};throw new Ur("payload can not decoded",t)}catch(t){return r("error",t)}},exports.findFromContract=function(t,e,n){return!!(n[t]&&n[t][e]&&n[t][e].file&&r.existsSync(n[t][e].file))&&n[t][e].file},exports.formatPayload=zr,exports.freeze=function(t){return Object.freeze(t)},exports.getCallMethod=function(t){switch(!0){case t===Rr[0]:return"query";case t===Rr[1]:return"mutation";default:return!1}},exports.getConfigValue=function(t,r){return r&&j(r)&&t in r?r[t]:void 0},exports.getDocLen=function(t){return ge.byteLength(t,"utf8")},exports.getMutationFromArgs=Qr,exports.getMutationFromPayload=function(t){var r=Gr(t,Qr);if(!1!==r)return r;throw new Sr("[getMutationArgs] Payload is malformed!",t)},exports.getNamespace=Wr,exports.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},exports.getNspInfoByConfig=function(t){var r=t.contract,e=t.enableAuth,n=Wr(t),o=e?Hr(r):function(t,r){var e,n={};for(var o in t){var i=t[o];n[o]=i}return{size:1,nspGroup:(e={},e[r]=n,e),publicNamespace:r}}(r.socket,n[0]);return Object.assign(o,{namespaces:n})},exports.getPathToFn=function(t,n,o){var i=o.resolverDir,u=Ir(t),a=[];o.contract&&o.contract[n]&&o.contract[n].path&&a.push(o.contract[n].path),a.push(e.join(i,n,u,[Or,Pr].join("."))),a.push(e.join(i,n,[u,Pr].join(".")));for(var f=a.length,s=0;s=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 i=Array(o);++n-1;);return e}(o,i),function(t,r){for(var e=t.length;e--&&U(r,t[e],0)>-1;);return e}(o,i)+1).join("")}var G=function(t,r){return!!t.filter((function(t){return t===r})).length},Q=function(t){return n(t)?t:[t]},V=function(t,r){void 0===r&&(r=!0);try{return JSON.parse(t)}catch(e){if(r)return t;throw new Error(e)}},H=function(t,r){try{var e=Object.keys(t);return G(e,r)}catch(t){return!1}},W=function(t){return V("string"==typeof t?t:JSON.stringify(t))},Z=function(){return!1};function K(t,r){return t===r||t!=t&&r!=r}function X(t,r){for(var e=t.length;e--;)if(K(t[e][0],r))return e;return-1}var tt=Array.prototype.splice;function rt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},rt.prototype.set=function(t,r){var e=this.__data__,n=X(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};function nt(t){if(!et(t))return!1;var r=y(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}var ot,it=a["__core-js_shared__"],ut=(ot=/[^.]+$/.exec(it&&it.keys&&it.keys.IE_PROTO||""))?"Symbol(src)_1."+ot:"";var at=Function.prototype.toString;var st=/^\[object .+?Constructor\]$/,ft=Function.prototype,ct=Object.prototype,ht=ft.toString,pt=ct.hasOwnProperty,lt=RegExp("^"+ht.call(pt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function gt(t){return!(!et(t)||function(t){return!!ut&&ut in t}(t))&&(nt(t)?lt:st).test(function(t){if(null!=t){try{return at.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function yt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return gt(e)?e:void 0}var vt=yt(a,"Map"),dt=yt(Object,"create");var _t=Object.prototype.hasOwnProperty;var bt=Object.prototype.hasOwnProperty;function wt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=9007199254740991}function $t(t){return null!=t&&Jt(t.length)&&!nt(t)}var Gt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Qt=Gt&&"object"==typeof module&&module&&!module.nodeType&&module,Vt=Qt&&Qt.exports===Gt?a.Buffer:void 0,Ht=(Vt?Vt.isBuffer:void 0)||function(){return!1},Wt={};Wt["[object Float32Array]"]=Wt["[object Float64Array]"]=Wt["[object Int8Array]"]=Wt["[object Int16Array]"]=Wt["[object Int32Array]"]=Wt["[object Uint8Array]"]=Wt["[object Uint8ClampedArray]"]=Wt["[object Uint16Array]"]=Wt["[object Uint32Array]"]=!0,Wt["[object Arguments]"]=Wt["[object Array]"]=Wt["[object ArrayBuffer]"]=Wt["[object Boolean]"]=Wt["[object DataView]"]=Wt["[object Date]"]=Wt["[object Error]"]=Wt["[object Function]"]=Wt["[object Map]"]=Wt["[object Number]"]=Wt["[object Object]"]=Wt["[object RegExp]"]=Wt["[object Set]"]=Wt["[object String]"]=Wt["[object WeakMap]"]=!1;var Zt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Kt=Zt&&"object"==typeof module&&module&&!module.nodeType&&module,Xt=Kt&&Kt.exports===Zt&&i.process,tr=function(){try{var t=Kt&&Kt.require&&Kt.require("util").types;return t||Xt&&Xt.binding&&Xt.binding("util")}catch(t){}}(),rr=tr&&tr.isTypedArray,er=rr?function(t){return function(r){return t(r)}}(rr):function(t){return b(t)&&Jt(t.length)&&!!Wt[y(t)]};function nr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var or=Object.prototype.hasOwnProperty;function ir(t,r,e){var n=t[r];or.call(t,r)&&K(n,e)&&(void 0!==e||r in t)||jt(t,r,e)}var ur=/^(?:0|[1-9]\d*)$/;function ar(t,r){var e=typeof t;return!!(r=null==r?9007199254740991:r)&&("number"==e||"symbol"!=e&&ur.test(t))&&t>-1&&t%1==0&&t0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(br);function Ar(t,r){return mr(function(t,r,e){return r=_r(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,i=_r(n.length-r,0),u=Array(i);++o1?r[n-1]:void 0,i=n>2?r[2]:void 0;for(o=Er.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,r,e){if(!et(e))return!1;var n=typeof r;return!!("number"==n?$t(e)&&ar(r,e.length):"string"==n&&r in e)&&K(e[r],t)}(r[0],r[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++e>18&63]+re[o>>12&63]+re[o>>6&63]+re[63&o]);return i.join("")}function ae(t){var r;oe||ie();for(var e=t.length,n=e%3,o="",i=[],u=0,a=e-n;ua?a:u+16383));return 1===n?(r=t[e-1],o+=re[r>>2],o+=re[r<<4&63],o+="=="):2===n&&(r=(t[e-2]<<8)+t[e-1],o+=re[r>>10],o+=re[r>>4&63],o+=re[r<<2&63],o+="="),i.push(o),i.join("")}function se(t,r,e,n,o){var i,u,a=8*o-n-1,s=(1<>1,c=-7,h=e?o-1:0,p=e?-1:1,l=t[r+h];for(h+=p,i=l&(1<<-c)-1,l>>=-c,c+=a;c>0;i=256*i+t[r+h],h+=p,c-=8);for(u=i&(1<<-c)-1,i>>=-c,c+=n;c>0;u=256*u+t[r+h],h+=p,c-=8);if(0===i)i=1-f;else{if(i===s)return u?NaN:1/0*(l?-1:1);u+=Math.pow(2,n),i-=f}return(l?-1:1)*u*Math.pow(2,i-n)}function fe(t,r,e,n,o,i){var u,a,s,f=8*i-o-1,c=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,l=n?0:i-1,g=n?1:-1,y=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(a=isNaN(r)?1:0,u=c):(u=Math.floor(Math.log(r)/Math.LN2),r*(s=Math.pow(2,-u))<1&&(u--,s*=2),(r+=u+h>=1?p/s:p*Math.pow(2,1-h))*s>=2&&(u++,s/=2),u+h>=c?(a=0,u=c):u+h>=1?(a=(r*s-1)*Math.pow(2,o),u+=h):(a=r*Math.pow(2,h-1)*Math.pow(2,o),u=0));o>=8;t[e+l]=255&a,l+=g,a/=256,o-=8);for(u=u<0;t[e+l]=255&u,l+=g,u/=256,f-=8);t[e+l-g]|=128*y}var ce={}.toString,he=Array.isArray||function(t){return"[object Array]"==ce.call(t)};function pe(){return ge.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function le(t,r){if(pe()=pe())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+pe().toString(16)+" bytes");return 0|t}function we(t){return!(null==t||!t._isBuffer)}function me(t,r){if(we(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var e=t.length;if(0===e)return 0;for(var n=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return Qe(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return Ve(t).length;default:if(n)return Qe(t).length;r=(""+r).toLowerCase(),n=!0}}function Ae(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return Me(this,r,e);case"utf8":case"utf-8":return Ne(this,r,e);case"ascii":return Ie(this,r,e);case"latin1":case"binary":return Ce(this,r,e);case"base64":return Be(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ye(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function Ee(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function xe(t,r,e,n,o){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=o?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(o)return-1;e=t.length-1}else if(e<0){if(!o)return-1;e=0}if("string"==typeof r&&(r=ge.from(r,n)),we(r))return 0===r.length?-1:je(t,r,e,n,o);if("number"==typeof r)return r&=255,ge.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):je(t,[r],e,n,o);throw new TypeError("val must be string, number or Buffer")}function je(t,r,e,n,o){var i,u=1,a=t.length,s=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;u=2,a/=2,s/=2,e/=2}function f(t,r){return 1===u?t[r]:t.readUInt16BE(r*u)}if(o){var c=-1;for(i=e;ia&&(e=a-s),i=e;i>=0;i--){for(var h=!0,p=0;po&&(n=o):n=o;var i=r.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var u=0;u>8,o=e%256,i.push(o),i.push(n);return i}(r,t.length-e),t,e,n)}function Be(t,r,e){return 0===r&&e===t.length?ae(t):ae(t.slice(r,e))}function Ne(t,r,e){e=Math.min(t.length,e);for(var n=[],o=r;o239?4:f>223?3:f>191?2:1;if(o+h<=e)switch(h){case 1:f<128&&(c=f);break;case 2:128==(192&(i=t[o+1]))&&(s=(31&f)<<6|63&i)>127&&(c=s);break;case 3:i=t[o+1],u=t[o+2],128==(192&i)&&128==(192&u)&&(s=(15&f)<<12|(63&i)<<6|63&u)>2047&&(s<55296||s>57343)&&(c=s);break;case 4:i=t[o+1],u=t[o+2],a=t[o+3],128==(192&i)&&128==(192&u)&&128==(192&a)&&(s=(15&f)<<18|(63&i)<<12|(63&u)<<6|63&a)>65535&&s<1114112&&(c=s)}null===c?(c=65533,h=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),o+=h}return function(t){var r=t.length;if(r<=4096)return String.fromCharCode.apply(String,t);var e="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},ge.prototype.compare=function(t,r,e,n,o){if(!we(t))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),r<0||e>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=e)return 0;if(n>=o)return-1;if(r>=e)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),u=(e>>>=0)-(r>>>=0),a=Math.min(i,u),s=this.slice(n,o),f=t.slice(r,e),c=0;co)&&(e=o),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return Pe(this,t,r,e);case"utf8":case"utf-8":return Oe(this,t,r,e);case"ascii":return Re(this,t,r,e);case"latin1":case"binary":return Se(this,t,r,e);case"base64":return Te(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ue(this,t,r,e);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},ge.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ie(t,r,e){var n="";e=Math.min(t.length,e);for(var o=r;on)&&(e=n);for(var o="",i=r;ie)throw new RangeError("Trying to access beyond buffer length")}function De(t,r,e,n,o,i){if(!we(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>o||rt.length)throw new RangeError("Index out of range")}function ze(t,r,e,n){r<0&&(r=65535+r+1);for(var o=0,i=Math.min(t.length-e,2);o>>8*(n?o:1-o)}function Le(t,r,e,n){r<0&&(r=4294967295+r+1);for(var o=0,i=Math.min(t.length-e,4);o>>8*(n?o:3-o)&255}function Fe(t,r,e,n,o,i){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function qe(t,r,e,n,o){return o||Fe(t,0,e,4),fe(t,r,e,n,23,4),e+4}function Je(t,r,e,n,o){return o||Fe(t,0,e,8),fe(t,r,e,n,52,8),e+8}ge.prototype.slice=function(t,r){var e,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(r=void 0===r?n:~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),r0&&(o*=256);)n+=this[t+--r]*o;return n},ge.prototype.readUInt8=function(t,r){return r||ke(t,1,this.length),this[t]},ge.prototype.readUInt16LE=function(t,r){return r||ke(t,2,this.length),this[t]|this[t+1]<<8},ge.prototype.readUInt16BE=function(t,r){return r||ke(t,2,this.length),this[t]<<8|this[t+1]},ge.prototype.readUInt32LE=function(t,r){return r||ke(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},ge.prototype.readUInt32BE=function(t,r){return r||ke(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},ge.prototype.readIntLE=function(t,r,e){t|=0,r|=0,e||ke(t,r,this.length);for(var n=this[t],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*r)),n},ge.prototype.readIntBE=function(t,r,e){t|=0,r|=0,e||ke(t,r,this.length);for(var n=r,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*r)),i},ge.prototype.readInt8=function(t,r){return r||ke(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},ge.prototype.readInt16LE=function(t,r){r||ke(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},ge.prototype.readInt16BE=function(t,r){r||ke(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},ge.prototype.readInt32LE=function(t,r){return r||ke(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},ge.prototype.readInt32BE=function(t,r){return r||ke(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},ge.prototype.readFloatLE=function(t,r){return r||ke(t,4,this.length),se(this,t,!0,23,4)},ge.prototype.readFloatBE=function(t,r){return r||ke(t,4,this.length),se(this,t,!1,23,4)},ge.prototype.readDoubleLE=function(t,r){return r||ke(t,8,this.length),se(this,t,!0,52,8)},ge.prototype.readDoubleBE=function(t,r){return r||ke(t,8,this.length),se(this,t,!1,52,8)},ge.prototype.writeUIntLE=function(t,r,e,n){(t=+t,r|=0,e|=0,n)||De(this,t,r,e,Math.pow(2,8*e)-1,0);var o=1,i=0;for(this[r]=255&t;++i=0&&(i*=256);)this[r+o]=t/i&255;return r+e},ge.prototype.writeUInt8=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,1,255,0),ge.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[r]=255&t,r+1},ge.prototype.writeUInt16LE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,2,65535,0),ge.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):ze(this,t,r,!0),r+2},ge.prototype.writeUInt16BE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,2,65535,0),ge.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):ze(this,t,r,!1),r+2},ge.prototype.writeUInt32LE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,4,4294967295,0),ge.TYPED_ARRAY_SUPPORT?(this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t):Le(this,t,r,!0),r+4},ge.prototype.writeUInt32BE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,4,4294967295,0),ge.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):Le(this,t,r,!1),r+4},ge.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r|=0,!n){var o=Math.pow(2,8*e-1);De(this,t,r,e,o-1,-o)}var i=0,u=1,a=0;for(this[r]=255&t;++i>0)-a&255;return r+e},ge.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r|=0,!n){var o=Math.pow(2,8*e-1);De(this,t,r,e,o-1,-o)}var i=e-1,u=1,a=0;for(this[r+i]=255&t;--i>=0&&(u*=256);)t<0&&0===a&&0!==this[r+i+1]&&(a=1),this[r+i]=(t/u>>0)-a&255;return r+e},ge.prototype.writeInt8=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,1,127,-128),ge.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[r]=255&t,r+1},ge.prototype.writeInt16LE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,2,32767,-32768),ge.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):ze(this,t,r,!0),r+2},ge.prototype.writeInt16BE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,2,32767,-32768),ge.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):ze(this,t,r,!1),r+2},ge.prototype.writeInt32LE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,4,2147483647,-2147483648),ge.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24):Le(this,t,r,!0),r+4},ge.prototype.writeInt32BE=function(t,r,e){return t=+t,r|=0,e||De(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),ge.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):Le(this,t,r,!1),r+4},ge.prototype.writeFloatLE=function(t,r,e){return qe(this,t,r,!0,e)},ge.prototype.writeFloatBE=function(t,r,e){return qe(this,t,r,!1,e)},ge.prototype.writeDoubleLE=function(t,r,e){return Je(this,t,r,!0,e)},ge.prototype.writeDoubleBE=function(t,r,e){return Je(this,t,r,!1,e)},ge.prototype.copy=function(t,r,e,n){if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r=0;--o)t[o+r]=this[o+e];else if(i<1e3||!ge.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,e=void 0===e?this.length:e>>>0,t||(t=0),"number"==typeof t)for(i=r;i55295&&e<57344){if(!o){if(e>56319){(r-=3)>-1&&i.push(239,191,189);continue}if(u+1===n){(r-=3)>-1&&i.push(239,191,189);continue}o=e;continue}if(e<56320){(r-=3)>-1&&i.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(r-=3)>-1&&i.push(239,191,189);if(o=null,e<128){if((r-=1)<0)break;i.push(e)}else if(e<2048){if((r-=2)<0)break;i.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;i.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return i}function Ve(t){return function(t){var r,e,n,o,i,u;oe||ie();var a=t.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===t[a-2]?2:"="===t[a-1]?1:0,u=new ne(3*a/4-i),n=i>0?a-4:a;var s=0;for(r=0,e=0;r>16&255,u[s++]=o>>8&255,u[s++]=255&o;return 2===i?(o=ee[t.charCodeAt(r)]<<2|ee[t.charCodeAt(r+1)]>>4,u[s++]=255&o):1===i&&(o=ee[t.charCodeAt(r)]<<10|ee[t.charCodeAt(r+1)]<<4|ee[t.charCodeAt(r+2)]>>2,u[s++]=o>>8&255,u[s++]=255&o),u}(function(t){if((t=function(t){if(t.trim)return t.trim();return t.replace(/^\s+|\s+$/g,"")}(t).replace($e,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function He(t,r,e,n){for(var o=0;o=r.length||o>=t.length);++o)r[o+e]=t[o];return o}function We(t){return null!=t&&(!!t._isBuffer||Ze(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&Ze(t.slice(0,0))}(t))}function Ze(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}var Ke=function(t,r){if(r instanceof Error){var e={};return Object.getOwnPropertyNames(r).forEach((function(t){e[t]=r[t]})),e}return r};var Xe=function(t,r){try{var e=t.headers.accept.split(",");return r?e.filter((function(t){return t===r})):e}catch(t){return[]}},tn=function(t,r){return!!Xe(t,r).length},rn=function(t,r){return t.path===r.jsonqlPath};exports.VERSION="1.2.5",exports.assign=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return Reflect.apply(Object.assign,Object,t)},exports.buff=function(t,r){return void 0===r&&(r="base64"),We(t)?t:new ge.from(t,r)},exports.cacheBurst=Mr,exports.cacheBurstUrl=function(t){return Cr(t,Mr())},exports.chainFns=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,Q(t))}),Reflect.apply(t,null,e))}},exports.chainPromises=function(t,r){return void 0===r&&(r=!1),t.reduce((function(t,e){return t.then((function(t){return e.then((function(e){return!1===r?t.concat([e]):xr(t,e)}))}))}),Promise.resolve(!1===r?[]:j(r)?r:{}))},exports.createAcknowledgeMsg=function(t,r,e){return void 0===e&&(e=[]),Xr("emit_acknowledge",t,r,e)},exports.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},exports.createMutation=Jr,exports.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(Jr(t,r,e,n))},exports.createQuery=qr,exports.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(qr(t,r,e))},exports.createReplyMsg=function(t,r,e){return void 0===e&&(e=[]),Xr("emit_reply",t,r,e)},exports.createSendPayload=function(t,r,e){if(void 0===e&&(e=!1),Yr(t)&&n(r)){var o=Fr(t,zr(r),{type:"emit_send"});return e?JSON.stringify(o):o}throw new Tr("utils:socket:createSendMsg",{resolverName:t,args:r,message:"expect resolverName to be string and args to be array!"})},exports.createWsReply=Xr,exports.dasherize=Ir,exports.extractArgsFromPayload=function(t,r){switch(r){case"query":return t.args;case"mutation":return[t.payload,t.condition];default:throw new Ur("Unknown "+r+" to extract argument from!")}},exports.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new Sr(e,r);return n}catch(t){throw new Sr(e,t)}},exports.extractSocketPart=Br,exports.extractWsPayload=function(t,r){void 0===r&&(r=Z);try{var e,n=W(t);if(!1!==(e=te(n)))return r("TS",n.TS),{data:W(e.__data__),resolverName:e.__event__,type:e.__reply__};throw new Ur("payload can not decoded",t)}catch(t){return r("error",t)}},exports.findFromContract=function(t,e,n){return!!(n[t]&&n[t][e]&&n[t][e].file&&r.existsSync(n[t][e].file))&&n[t][e].file},exports.formatPayload=zr,exports.freeze=function(t){return Object.freeze(t)},exports.getCallMethod=function(t){switch(!0){case t===Or[0]:return"query";case t===Or[1]:return"mutation";default:return!1}},exports.getConfigValue=function(t,r){return r&&j(r)&&t in r?r[t]:void 0},exports.getDocLen=function(t){return ge.byteLength(t,"utf8")},exports.getMutationFromArgs=Qr,exports.getMutationFromPayload=function(t){var r=Gr(t,Qr);if(!1!==r)return r;throw new Tr("[getMutationArgs] Payload is malformed!",t)},exports.getNamespace=Wr,exports.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},exports.getNspInfoByConfig=function(t){var r=t.contract,e=t.enableAuth,n=Wr(t),o=e?Hr(r):function(t,r){var e,n={};for(var o in t){var i=t[o];n[o]=i}return{size:1,nspGroup:(e={},e[r]=n,e),publicNamespace:r}}(r.socket,n[0]);return Object.assign(o,{namespaces:n})},exports.getPathToFn=function(t,n,o){var i=o.resolverDir,u=Ir(t),a=[];o.contract&&o.contract[n]&&o.contract[n].path&&a.push(o.contract[n].path),a.push(e.join(i,n,u,[Rr,Pr].join("."))),a.push(e.join(i,n,[u,Pr].join(".")));for(var s=a.length,f=0;f { + if (isString(resolverName) && isArray(args)) { + let payload = formatPayload(args) + // the different is we add a additonal type in the payload + const result = createDeliverable(resolverName, payload, {type: EMIT_SEND_TYPE}) + return str ? JSON.stringify(result) : result + } + throw new JsonqlValidationError(`utils:socket:createSendMsg`, { + resolverName, + args, + message: 'expect resolverName to be string and args to be array!' + }) +} + /** * The ws doesn't have a acknowledge callback like socket.io diff --git a/packages/utils/tests/socket.test.js b/packages/utils/tests/socket.test.js index 8938312e6d6ba21fcf051ba4234a03ee11cdd35a..caeef02998c694941f4cd59afbcc4fb324b8018a 100644 --- a/packages/utils/tests/socket.test.js +++ b/packages/utils/tests/socket.test.js @@ -1,8 +1,8 @@ // move the test from ws-server-core here // just testing the timestamp prop and see how we could develop it further const test = require('ava') -const { EMIT_REPLY_TYPE, TIMESTAMP_PARAM_NAME } = require('jsonql-constants') -const { toJson, createWsReply, extractWsPayload } = require('../main') +const { EMIT_REPLY_TYPE, EMIT_SEND_TYPE, TIMESTAMP_PARAM_NAME } = require('jsonql-constants') +const { toJson, createWsReply, extractWsPayload, createSendPayload } = require('../main') const debug = require('debug')('jsonql-utils:test:socket') @@ -46,5 +46,16 @@ test(`It should have a timestamp property as an array`, t => { debug('received payload again to test without a funciton', receivedAgain) }) +test(`test the new createSendPayload method for ws`, t => { + const result = createSendPayload('someResolver', ['a', 'b']) + + t.is(typeof result, 'object') + + t.is(result.type, EMIT_SEND_TYPE) + + const strResult = createSendPayload('someResolver', [1,2,3], true) + + t.is(typeof strResult, 'string') +}) diff --git a/packages/validator/dist/jsonql-params-validator.cjs.js b/packages/validator/dist/jsonql-params-validator.cjs.js index 198abf93c03d90310d2809afd19ab6e4ed68166d..a007199ffd40e0a1f867000584e7fbbe56beaed0 100644 --- a/packages/validator/dist/jsonql-params-validator.cjs.js +++ b/packages/validator/dist/jsonql-params-validator.cjs.js @@ -1,2 +1,2 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},r="object"==typeof t&&t&&t.Object===Object&&t,e="object"==typeof self&&self&&self.Object===Object&&self,n=r||e||Function("return this")(),o=n.Symbol;function u(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--&&m(r,t[e],0)>-1;);return e}(n,o)+1).join("")}var $=function(t){return!!i(t)||null!=t&&""!==M(t)};function D(t){return function(t){return"number"==typeof t||h(t)&&"[object Number]"==v(t)}(t)&&t!=+t}function B(t){return"string"==typeof t||!i(t)&&h(t)&&"[object String]"==v(t)}var V=function(t){return!B(t)&&!D(parseFloat(t))},I=function(t){return""!==M(t)&&B(t)},L=function(t){return null!=t&&"boolean"==typeof t},q=function(t,r){return void 0===r&&(r=!0),void 0!==t&&""!==t&&""!==M(t)&&(!1===r||!0===r&&null!==t)},U=function(t){switch(t){case"number":return V;case"string":return I;case"boolean":return L;default:return q}},J=function(t,r){return void 0===r&&(r=""),!!i(t)&&(""===r||""===M(r)||!(t.filter((function(t){return!U(r)(t)})).length>0))},W=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var r=t.replace("array.<","").replace(">","");return r.indexOf("|")?r.split("|"):[r]}return!1},G=function(t,r){var e=t.arg;return r.length>1?!e.filter((function(t){return!(r.length>r.filter((function(r){return!U(r)(t)})).length)})).length:r.length>r.filter((function(t){return!J(e,t)})).length};function H(t,r){return function(e){return t(r(e))}}var K=H(Object.getPrototypeOf,Object),Q=Function.prototype,Y=Object.prototype,X=Q.toString,Z=Y.hasOwnProperty,tt=X.call(Object);function rt(t){if(!h(t)||"[object Object]"!=v(t))return!1;var r=K(t);if(null===r)return!0;var e=Z.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&X.call(e)==tt}var et=function(t,r){if(void 0===r&&(r=null),rt(t)){if(!r)return!0;if(J(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=W(t))?!G({arg:e},r):!U(t)(e))})).length)})).length}return!1},nt=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),ot=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),ut=function(t,r){var e,n,o,u,i;switch(!0){case"object"===t:return o=(n=r).arg,u=n.param,i=[o],Array.isArray(u.keys)&&u.keys.length&&i.push(u.keys),!Reflect.apply(et,null,i);case"array"===t:return!J(r.arg);case!1!==(e=W(t)):return!G(r,e);default:return!U(t)(r.arg)}},it=function(t,r){return void 0!==t?t:!0===r.optional&&void 0!==r.defaultvalue?r.defaultvalue:null},at=function(t,r){if(!J(r))throw new nt("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===r.length)return[];if(!J(t))throw new nt("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==r.length:return t.map((function(t,e){return{arg:t,index:e,param:r[e]}}));case!0===r[0].variable:var e=r[0].type;return t.map((function(t,n){return{arg:t,index:n,param:r[n]||{type:e,name:"_"}}}));case t.lengthr.length:var n=r.length,o=["any"];return t.map((function(t,e){var u=e>=n||!!r[e].optional,i=r[e]||{type:o,name:"_"+e};return{arg:u?it(t,i):t,index:e,param:i,optional:u}}));default:throw new ot("Could not understand your arguments and parameter structure!",{args:t,params:r})}},ct=function(t,r,e){var n;void 0===e&&(e=!1);var o=at(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!!$(r)&&!(e.type.length>e.type.filter((function(r){return ut(r,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(r){return ut(r,t)})).length)}));return e?((n={}).error=u,n.data=o.map((function(t){return t.arg})),n):u},ft=function(t,r,e){return void 0===e&&(e=!1),new Promise((function(n,o){var u=ct(t,r,e);return e?u.error.length?o(u.error):n(u.data):u.length?o(u):n([])}))};function st(t,r){return t===r||t!=t&&r!=r}function lt(t,r){for(var e=t.length;e--;)if(st(t[e][0],r))return e;return-1}var pt=Array.prototype.splice;function vt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},vt.prototype.set=function(t,r){var e=this.__data__,n=lt(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};function yt(t){if(!ht(t))return!1;var r=v(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}var dt,bt=n["__core-js_shared__"],gt=(dt=/[^.]+$/.exec(bt&&bt.keys&&bt.keys.IE_PROTO||""))?"Symbol(src)_1."+dt:"";var _t=Function.prototype.toString;function jt(t){if(null!=t){try{return _t.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var mt=/^\[object .+?Constructor\]$/,Ot=Function.prototype,wt=Object.prototype,At=Ot.toString,xt=wt.hasOwnProperty,kt=RegExp("^"+At.call(xt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function St(t){return!(!ht(t)||(r=t,gt&> in r))&&(yt(t)?kt:mt).test(jt(t));var r}function Pt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return St(e)?e:void 0}var Et=Pt(n,"Map"),zt=Pt(Object,"create");var Tt=Object.prototype.hasOwnProperty;var Rt=Object.prototype.hasOwnProperty;function Ct(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=9007199254740991}function or(t){return null!=t&&nr(t.length)&&!yt(t)}var ur="object"==typeof exports&&exports&&!exports.nodeType&&exports,ir=ur&&"object"==typeof module&&module&&!module.nodeType&&module,ar=ir&&ir.exports===ur?n.Buffer:void 0,cr=(ar?ar.isBuffer:void 0)||function(){return!1},fr={};fr["[object Float32Array]"]=fr["[object Float64Array]"]=fr["[object Int8Array]"]=fr["[object Int16Array]"]=fr["[object Int32Array]"]=fr["[object Uint8Array]"]=fr["[object Uint8ClampedArray]"]=fr["[object Uint16Array]"]=fr["[object Uint32Array]"]=!0,fr["[object Arguments]"]=fr["[object Array]"]=fr["[object ArrayBuffer]"]=fr["[object Boolean]"]=fr["[object DataView]"]=fr["[object Date]"]=fr["[object Error]"]=fr["[object Function]"]=fr["[object Map]"]=fr["[object Number]"]=fr["[object Object]"]=fr["[object RegExp]"]=fr["[object Set]"]=fr["[object String]"]=fr["[object WeakMap]"]=!1;var sr,lr="object"==typeof exports&&exports&&!exports.nodeType&&exports,pr=lr&&"object"==typeof module&&module&&!module.nodeType&&module,vr=pr&&pr.exports===lr&&r.process,hr=function(){try{var t=pr&&pr.require&&pr.require("util").types;return t||vr&&vr.binding&&vr.binding("util")}catch(t){}}(),yr=hr&&hr.isTypedArray,dr=yr?(sr=yr,function(t){return sr(t)}):function(t){return h(t)&&nr(t.length)&&!!fr[v(t)]};function br(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var gr=Object.prototype.hasOwnProperty;function _r(t,r,e){var n=t[r];gr.call(t,r)&&st(n,e)&&(void 0!==e||r in t)||Dt(t,r,e)}var jr=/^(?:0|[1-9]\d*)$/;function mr(t,r){var e=typeof t;return!!(r=null==r?9007199254740991:r)&&("number"==e||"symbol"!=e&&jr.test(t))&&t>-1&&t%1==0&&t0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(Cr);function Mr(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),i=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(!ht(e))return!1;var n=typeof r;return!!("number"==n?or(e)&&mr(r,e.length):"string"==n&&r in e)&&st(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++ea))return!1;var f=u.get(t);if(f&&u.get(r))return f==r;var s=-1,l=!0,p=2&e?new qr:void 0;for(u.set(t,r),u.set(r,t);++s=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--&&m(r,t[e],0)>-1;);return e}(n,o)+1).join("")}var $=function(t){return!!i(t)||null!=t&&""!==M(t)};function D(t){return function(t){return"number"==typeof t||h(t)&&"[object Number]"==v(t)}(t)&&t!=+t}function B(t){return"string"==typeof t||!i(t)&&h(t)&&"[object String]"==v(t)}var V=function(t){return!B(t)&&!D(parseFloat(t))},I=function(t){return""!==M(t)&&B(t)},L=function(t){return null!=t&&"boolean"==typeof t},q=function(t,r){return void 0===r&&(r=!0),void 0!==t&&""!==t&&""!==M(t)&&(!1===r||!0===r&&null!==t)},U=function(t){switch(t){case"number":return V;case"string":return I;case"boolean":return L;default:return q}},J=function(t,r){return void 0===r&&(r=""),!!i(t)&&(""===r||""===M(r)||!(t.filter((function(t){return!U(r)(t)})).length>0))},W=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var r=t.replace("array.<","").replace(">","");return r.indexOf("|")?r.split("|"):[r]}return!1},G=function(t,r){var e=t.arg;return r.length>1?!e.filter((function(t){return!(r.length>r.filter((function(r){return!U(r)(t)})).length)})).length:r.length>r.filter((function(t){return!J(e,t)})).length};function H(t,r){return function(e){return t(r(e))}}var K=H(Object.getPrototypeOf,Object),Q=Function.prototype,Y=Object.prototype,X=Q.toString,Z=Y.hasOwnProperty,tt=X.call(Object);function rt(t){if(!h(t)||"[object Object]"!=v(t))return!1;var r=K(t);if(null===r)return!0;var e=Z.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&X.call(e)==tt}var et=function(t,r){if(void 0===r&&(r=null),rt(t)){if(!r)return!0;if(J(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=W(t))?!G({arg:e},r):!U(t)(e))})).length)})).length}return!1},nt=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),ot=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),ut=function(t,r){var e,n,o,u,i;switch(!0){case"object"===t:return o=(n=r).arg,u=n.param,i=[o],Array.isArray(u.keys)&&u.keys.length&&i.push(u.keys),!Reflect.apply(et,null,i);case"array"===t:return!J(r.arg);case!1!==(e=W(t)):return!G(r,e);default:return!U(t)(r.arg)}},it=function(t,r){return void 0!==t?t:!0===r.optional&&void 0!==r.defaultvalue?r.defaultvalue:null},at=function(t,r){if(!J(r))throw new nt("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===r.length)return[];if(!J(t))throw console.info(t),new nt("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==r.length:return t.map((function(t,e){return{arg:t,index:e,param:r[e]}}));case!0===r[0].variable:var e=r[0].type;return t.map((function(t,n){return{arg:t,index:n,param:r[n]||{type:e,name:"_"}}}));case t.lengthr.length:var n=r.length,o=["any"];return t.map((function(t,e){var u=e>=n||!!r[e].optional,i=r[e]||{type:o,name:"_"+e};return{arg:u?it(t,i):t,index:e,param:i,optional:u}}));default:throw new ot("Could not understand your arguments and parameter structure!",{args:t,params:r})}},ct=function(t,r,e){var n;void 0===e&&(e=!1);var o=at(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!!$(r)&&!(e.type.length>e.type.filter((function(r){return ut(r,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(r){return ut(r,t)})).length)}));return e?((n={}).error=u,n.data=o.map((function(t){return t.arg})),n):u},ft=function(t,r,e){return void 0===e&&(e=!1),new Promise((function(n,o){var u=ct(t,r,e);return e?u.error.length?o(u.error):n(u.data):u.length?o(u):n([])}))};function st(t,r){return t===r||t!=t&&r!=r}function lt(t,r){for(var e=t.length;e--;)if(st(t[e][0],r))return e;return-1}var pt=Array.prototype.splice;function vt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},vt.prototype.set=function(t,r){var e=this.__data__,n=lt(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};function yt(t){if(!ht(t))return!1;var r=v(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}var dt,gt=n["__core-js_shared__"],bt=(dt=/[^.]+$/.exec(gt&>.keys&>.keys.IE_PROTO||""))?"Symbol(src)_1."+dt:"";var _t=Function.prototype.toString;function jt(t){if(null!=t){try{return _t.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var mt=/^\[object .+?Constructor\]$/,Ot=Function.prototype,wt=Object.prototype,At=Ot.toString,xt=wt.hasOwnProperty,kt=RegExp("^"+At.call(xt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function St(t){return!(!ht(t)||(r=t,bt&&bt in r))&&(yt(t)?kt:mt).test(jt(t));var r}function Pt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return St(e)?e:void 0}var Et=Pt(n,"Map"),zt=Pt(Object,"create");var Tt=Object.prototype.hasOwnProperty;var Rt=Object.prototype.hasOwnProperty;function Ct(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=9007199254740991}function or(t){return null!=t&&nr(t.length)&&!yt(t)}var ur="object"==typeof exports&&exports&&!exports.nodeType&&exports,ir=ur&&"object"==typeof module&&module&&!module.nodeType&&module,ar=ir&&ir.exports===ur?n.Buffer:void 0,cr=(ar?ar.isBuffer:void 0)||function(){return!1},fr={};fr["[object Float32Array]"]=fr["[object Float64Array]"]=fr["[object Int8Array]"]=fr["[object Int16Array]"]=fr["[object Int32Array]"]=fr["[object Uint8Array]"]=fr["[object Uint8ClampedArray]"]=fr["[object Uint16Array]"]=fr["[object Uint32Array]"]=!0,fr["[object Arguments]"]=fr["[object Array]"]=fr["[object ArrayBuffer]"]=fr["[object Boolean]"]=fr["[object DataView]"]=fr["[object Date]"]=fr["[object Error]"]=fr["[object Function]"]=fr["[object Map]"]=fr["[object Number]"]=fr["[object Object]"]=fr["[object RegExp]"]=fr["[object Set]"]=fr["[object String]"]=fr["[object WeakMap]"]=!1;var sr,lr="object"==typeof exports&&exports&&!exports.nodeType&&exports,pr=lr&&"object"==typeof module&&module&&!module.nodeType&&module,vr=pr&&pr.exports===lr&&r.process,hr=function(){try{var t=pr&&pr.require&&pr.require("util").types;return t||vr&&vr.binding&&vr.binding("util")}catch(t){}}(),yr=hr&&hr.isTypedArray,dr=yr?(sr=yr,function(t){return sr(t)}):function(t){return h(t)&&nr(t.length)&&!!fr[v(t)]};function gr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var br=Object.prototype.hasOwnProperty;function _r(t,r,e){var n=t[r];br.call(t,r)&&st(n,e)&&(void 0!==e||r in t)||Dt(t,r,e)}var jr=/^(?:0|[1-9]\d*)$/;function mr(t,r){var e=typeof t;return!!(r=null==r?9007199254740991:r)&&("number"==e||"symbol"!=e&&jr.test(t))&&t>-1&&t%1==0&&t0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(Cr);function Mr(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),i=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(!ht(e))return!1;var n=typeof r;return!!("number"==n?or(e)&&mr(r,e.length):"string"==n&&r in e)&&st(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++ea))return!1;var f=u.get(t);if(f&&u.get(r))return f==r;var s=-1,l=!0,p=2&e?new qr:void 0;for(u.set(t,r),u.set(r,t);++s=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--&&O(r,t[e],0)>-1;);return e}(n,o)+1).join("")}var D=function(t){return!!a(t)||null!=t&&""!==$(t)};function V(t){return function(t){return"number"==typeof t||y(t)&&"[object Number]"==h(t)}(t)&&t!=+t}function B(t){return"string"==typeof t||!a(t)&&y(t)&&"[object String]"==h(t)}var q=function(t){return!B(t)&&!V(parseFloat(t))},I=function(t){return""!==$(t)&&B(t)},L=function(t){return null!=t&&"boolean"==typeof t},U=function(t,r){return void 0===r&&(r=!0),void 0!==t&&""!==t&&""!==$(t)&&(!1===r||!0===r&&null!==t)},J=function(t){switch(t){case"number":return q;case"string":return I;case"boolean":return L;default:return U}},W=function(t,r){return void 0===r&&(r=""),!!a(t)&&(""===r||""===$(r)||!(t.filter((function(t){return!J(r)(t)})).length>0))},G=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var r=t.replace("array.<","").replace(">","");return r.indexOf("|")?r.split("|"):[r]}return!1},H=function(t,r){var e=t.arg;return r.length>1?!e.filter((function(t){return!(r.length>r.filter((function(r){return!J(r)(t)})).length)})).length:r.length>r.filter((function(t){return!W(e,t)})).length};function K(t,r){return function(e){return t(r(e))}}var Q=K(Object.getPrototypeOf,Object),Y=Function.prototype,X=Object.prototype,Z=Y.toString,tt=X.hasOwnProperty,rt=Z.call(Object);function et(t){if(!y(t)||"[object Object]"!=h(t))return!1;var r=Q(t);if(null===r)return!0;var e=tt.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&Z.call(e)==rt}var nt=function(t,r){if(void 0===r&&(r=null),et(t)){if(!r)return!0;if(W(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=G(t))?!H({arg:e},r):!J(t)(e))})).length)})).length}return!1},ot=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),ut=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),it=function(t,r){var e,n,o,u,i;switch(!0){case"object"===t:return o=(n=r).arg,u=n.param,i=[o],Array.isArray(u.keys)&&u.keys.length&&i.push(u.keys),!Reflect.apply(nt,null,i);case"array"===t:return!W(r.arg);case!1!==(e=G(t)):return!H(r,e);default:return!J(t)(r.arg)}},at=function(t,r){return void 0!==t?t:!0===r.optional&&void 0!==r.defaultvalue?r.defaultvalue:null},ct=function(t,r){if(!W(r))throw new ot("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===r.length)return[];if(!W(t))throw new ot("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==r.length:return t.map((function(t,e){return{arg:t,index:e,param:r[e]}}));case!0===r[0].variable:var e=r[0].type;return t.map((function(t,n){return{arg:t,index:n,param:r[n]||{type:e,name:"_"}}}));case t.lengthr.length:var n=r.length,o=["any"];return t.map((function(t,e){var u=e>=n||!!r[e].optional,i=r[e]||{type:o,name:"_"+e};return{arg:u?at(t,i):t,index:e,param:i,optional:u}}));default:throw new ut("Could not understand your arguments and parameter structure!",{args:t,params:r})}},ft=function(t,r,e){var n;void 0===e&&(e=!1);var o=ct(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!!D(r)&&!(e.type.length>e.type.filter((function(r){return it(r,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(r){return it(r,t)})).length)}));return e?((n={}).error=u,n.data=o.map((function(t){return t.arg})),n):u},lt=function(t,r,e){return void 0===e&&(e=!1),new Promise((function(n,o){var u=ft(t,r,e);return e?u.error.length?o(u.error):n(u.data):u.length?o(u):n([])}))};function st(t,r){return t===r||t!=t&&r!=r}function pt(t,r){for(var e=t.length;e--;)if(st(t[e][0],r))return e;return-1}var vt=Array.prototype.splice;function ht(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},ht.prototype.set=function(t,r){var e=this.__data__,n=pt(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};function dt(t){if(!yt(t))return!1;var r=h(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}var bt,gt=o["__core-js_shared__"],_t=(bt=/[^.]+$/.exec(gt&>.keys&>.keys.IE_PROTO||""))?"Symbol(src)_1."+bt:"";var jt=Function.prototype.toString;function mt(t){if(null!=t){try{return jt.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Ot=/^\[object .+?Constructor\]$/,wt=Function.prototype,At=Object.prototype,kt=wt.toString,St=At.hasOwnProperty,Pt=RegExp("^"+kt.call(St).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Et(t){return!(!yt(t)||(r=t,_t&&_t in r))&&(dt(t)?Pt:Ot).test(mt(t));var r}function zt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return Et(e)?e:void 0}var Tt=zt(o,"Map"),xt=zt(Object,"create");var Rt=Object.prototype.hasOwnProperty;var Ct=Object.prototype.hasOwnProperty;function Nt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=9007199254740991}function ur(t){return null!=t&&or(t.length)&&!dt(t)}var ir="object"==typeof t&&t&&!t.nodeType&&t,ar=ir&&"object"==typeof module&&module&&!module.nodeType&&module,cr=ar&&ar.exports===ir?o.Buffer:void 0,fr=(cr?cr.isBuffer:void 0)||function(){return!1},lr={};lr["[object Float32Array]"]=lr["[object Float64Array]"]=lr["[object Int8Array]"]=lr["[object Int16Array]"]=lr["[object Int32Array]"]=lr["[object Uint8Array]"]=lr["[object Uint8ClampedArray]"]=lr["[object Uint16Array]"]=lr["[object Uint32Array]"]=!0,lr["[object Arguments]"]=lr["[object Array]"]=lr["[object ArrayBuffer]"]=lr["[object Boolean]"]=lr["[object DataView]"]=lr["[object Date]"]=lr["[object Error]"]=lr["[object Function]"]=lr["[object Map]"]=lr["[object Number]"]=lr["[object Object]"]=lr["[object RegExp]"]=lr["[object Set]"]=lr["[object String]"]=lr["[object WeakMap]"]=!1;var sr,pr="object"==typeof t&&t&&!t.nodeType&&t,vr=pr&&"object"==typeof module&&module&&!module.nodeType&&module,hr=vr&&vr.exports===pr&&e.process,yr=function(){try{var t=vr&&vr.require&&vr.require("util").types;return t||hr&&hr.binding&&hr.binding("util")}catch(t){}}(),dr=yr&&yr.isTypedArray,br=dr?(sr=dr,function(t){return sr(t)}):function(t){return y(t)&&or(t.length)&&!!lr[h(t)]};function gr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var _r=Object.prototype.hasOwnProperty;function jr(t,r,e){var n=t[r];_r.call(t,r)&&st(n,e)&&(void 0!==e||r in t)||Vt(t,r,e)}var mr=/^(?:0|[1-9]\d*)$/;function Or(t,r){var e=typeof t;return!!(r=null==r?9007199254740991:r)&&("number"==e||"symbol"!=e&&mr.test(t))&&t>-1&&t%1==0&&t0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(Nr);function $r(t,r){return Mr(function(t,r,e){return r=Cr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=Cr(n.length-r,0),i=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=Dr.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!yt(e))return!1;var n=typeof r;return!!("number"==n?ur(e)&&Or(r,e.length):"string"==n&&r in e)&&st(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++ea))return!1;var f=u.get(t);if(f&&u.get(r))return f==r;var l=-1,s=!0,p=2&e?new Ur:void 0;for(u.set(t,r),u.set(r,t);++l=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--&&O(r,t[e],0)>-1;);return e}(n,o)+1).join("")}var D=function(t){return!!a(t)||null!=t&&""!==$(t)};function V(t){return function(t){return"number"==typeof t||y(t)&&"[object Number]"==h(t)}(t)&&t!=+t}function B(t){return"string"==typeof t||!a(t)&&y(t)&&"[object String]"==h(t)}var q=function(t){return!B(t)&&!V(parseFloat(t))},I=function(t){return""!==$(t)&&B(t)},L=function(t){return null!=t&&"boolean"==typeof t},U=function(t,r){return void 0===r&&(r=!0),void 0!==t&&""!==t&&""!==$(t)&&(!1===r||!0===r&&null!==t)},J=function(t){switch(t){case"number":return q;case"string":return I;case"boolean":return L;default:return U}},W=function(t,r){return void 0===r&&(r=""),!!a(t)&&(""===r||""===$(r)||!(t.filter((function(t){return!J(r)(t)})).length>0))},G=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var r=t.replace("array.<","").replace(">","");return r.indexOf("|")?r.split("|"):[r]}return!1},H=function(t,r){var e=t.arg;return r.length>1?!e.filter((function(t){return!(r.length>r.filter((function(r){return!J(r)(t)})).length)})).length:r.length>r.filter((function(t){return!W(e,t)})).length};function K(t,r){return function(e){return t(r(e))}}var Q=K(Object.getPrototypeOf,Object),Y=Function.prototype,X=Object.prototype,Z=Y.toString,tt=X.hasOwnProperty,rt=Z.call(Object);function et(t){if(!y(t)||"[object Object]"!=h(t))return!1;var r=Q(t);if(null===r)return!0;var e=tt.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&Z.call(e)==rt}var nt=function(t,r){if(void 0===r&&(r=null),et(t)){if(!r)return!0;if(W(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=G(t))?!H({arg:e},r):!J(t)(e))})).length)})).length}return!1},ot=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),ut=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),it=function(t,r){var e,n,o,u,i;switch(!0){case"object"===t:return o=(n=r).arg,u=n.param,i=[o],Array.isArray(u.keys)&&u.keys.length&&i.push(u.keys),!Reflect.apply(nt,null,i);case"array"===t:return!W(r.arg);case!1!==(e=G(t)):return!H(r,e);default:return!J(t)(r.arg)}},at=function(t,r){return void 0!==t?t:!0===r.optional&&void 0!==r.defaultvalue?r.defaultvalue:null},ct=function(t,r){if(!W(r))throw new ot("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===r.length)return[];if(!W(t))throw console.info(t),new ot("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==r.length:return t.map((function(t,e){return{arg:t,index:e,param:r[e]}}));case!0===r[0].variable:var e=r[0].type;return t.map((function(t,n){return{arg:t,index:n,param:r[n]||{type:e,name:"_"}}}));case t.lengthr.length:var n=r.length,o=["any"];return t.map((function(t,e){var u=e>=n||!!r[e].optional,i=r[e]||{type:o,name:"_"+e};return{arg:u?at(t,i):t,index:e,param:i,optional:u}}));default:throw new ut("Could not understand your arguments and parameter structure!",{args:t,params:r})}},ft=function(t,r,e){var n;void 0===e&&(e=!1);var o=ct(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!!D(r)&&!(e.type.length>e.type.filter((function(r){return it(r,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(r){return it(r,t)})).length)}));return e?((n={}).error=u,n.data=o.map((function(t){return t.arg})),n):u},lt=function(t,r,e){return void 0===e&&(e=!1),new Promise((function(n,o){var u=ft(t,r,e);return e?u.error.length?o(u.error):n(u.data):u.length?o(u):n([])}))};function st(t,r){return t===r||t!=t&&r!=r}function pt(t,r){for(var e=t.length;e--;)if(st(t[e][0],r))return e;return-1}var vt=Array.prototype.splice;function ht(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},ht.prototype.set=function(t,r){var e=this.__data__,n=pt(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};function dt(t){if(!yt(t))return!1;var r=h(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}var bt,gt=o["__core-js_shared__"],_t=(bt=/[^.]+$/.exec(gt&>.keys&>.keys.IE_PROTO||""))?"Symbol(src)_1."+bt:"";var jt=Function.prototype.toString;function mt(t){if(null!=t){try{return jt.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Ot=/^\[object .+?Constructor\]$/,wt=Function.prototype,At=Object.prototype,kt=wt.toString,St=At.hasOwnProperty,Pt=RegExp("^"+kt.call(St).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Et(t){return!(!yt(t)||(r=t,_t&&_t in r))&&(dt(t)?Pt:Ot).test(mt(t));var r}function zt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return Et(e)?e:void 0}var Tt=zt(o,"Map"),xt=zt(Object,"create");var Rt=Object.prototype.hasOwnProperty;var Ct=Object.prototype.hasOwnProperty;function Nt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=9007199254740991}function ur(t){return null!=t&&or(t.length)&&!dt(t)}var ir="object"==typeof t&&t&&!t.nodeType&&t,ar=ir&&"object"==typeof module&&module&&!module.nodeType&&module,cr=ar&&ar.exports===ir?o.Buffer:void 0,fr=(cr?cr.isBuffer:void 0)||function(){return!1},lr={};lr["[object Float32Array]"]=lr["[object Float64Array]"]=lr["[object Int8Array]"]=lr["[object Int16Array]"]=lr["[object Int32Array]"]=lr["[object Uint8Array]"]=lr["[object Uint8ClampedArray]"]=lr["[object Uint16Array]"]=lr["[object Uint32Array]"]=!0,lr["[object Arguments]"]=lr["[object Array]"]=lr["[object ArrayBuffer]"]=lr["[object Boolean]"]=lr["[object DataView]"]=lr["[object Date]"]=lr["[object Error]"]=lr["[object Function]"]=lr["[object Map]"]=lr["[object Number]"]=lr["[object Object]"]=lr["[object RegExp]"]=lr["[object Set]"]=lr["[object String]"]=lr["[object WeakMap]"]=!1;var sr,pr="object"==typeof t&&t&&!t.nodeType&&t,vr=pr&&"object"==typeof module&&module&&!module.nodeType&&module,hr=vr&&vr.exports===pr&&e.process,yr=function(){try{var t=vr&&vr.require&&vr.require("util").types;return t||hr&&hr.binding&&hr.binding("util")}catch(t){}}(),dr=yr&&yr.isTypedArray,br=dr?(sr=dr,function(t){return sr(t)}):function(t){return y(t)&&or(t.length)&&!!lr[h(t)]};function gr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var _r=Object.prototype.hasOwnProperty;function jr(t,r,e){var n=t[r];_r.call(t,r)&&st(n,e)&&(void 0!==e||r in t)||Vt(t,r,e)}var mr=/^(?:0|[1-9]\d*)$/;function Or(t,r){var e=typeof t;return!!(r=null==r?9007199254740991:r)&&("number"==e||"symbol"!=e&&mr.test(t))&&t>-1&&t%1==0&&t0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(Nr);function $r(t,r){return Mr(function(t,r,e){return r=Cr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=Cr(n.length-r,0),i=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=Dr.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!yt(e))return!1;var n=typeof r;return!!("number"==n?ur(e)&&Or(r,e.length):"string"==n&&r in e)&&st(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++ea))return!1;var f=u.get(t);if(f&&u.get(r))return f==r;var l=-1,s=!0,p=2&e?new Ur:void 0;for(u.set(t,r),u.set(r,t);++l resolverName @@ -17,39 +21,61 @@ function getDefFromContract(resolverType, resolverName, contract) { return false } +/** + * then we package the result once again for easier to use + * @param {array} result the valdiation result + * @return {object} with DATA_KEY and ERROR_KEY + */ +function packageResult(result, args) { + let obj = {[DATA_KEY]: [], [ERROR_KEY]: []} + if (result.length) { + obj[ERROR_KEY] = result + } else { + obj[DATA_KEY] = args + } + return obj +} + + /** * Basically it's an alias to the validateSync - * @param {array} args the return result from resolver + * @param {array} value the raw return result from resolver * @param {array} params the `returns` part from the resolverName.returns + * @param {boolean} async or not + * @return {object} validation result */ -export function checkReturns(args, params) { - return validateSync(args, params) +export function checkReturns(value, params, async = false) { + const args = [value] + if (async) { + return validateAsync(args, params) + .then(result => packageResult(result, args)) + } + const result = validateSync(args, params) + return packageResult(result, args) } -/** - * Async version of checkReturns - * @param {array} args - * @param {array} params - */ -export function checkReturnsAsync(args, params) { - return validateAsync(args, params) -} +// just a wrapper method +export const checkReturnsAsync = (value, params) => checkReturns(value, params, true) /** * The combine method for use to check the resolver returns with contract * @param {string} resolverType type of resolver (query, mutation, socket, auth) * @param {string} resolverName name of the resolver * @param {object} contract the full contract json - * @param {array} args the return results + * @param {array} value the return results * @return {*} */ -export function checkResolverReturns(resolverType, resolverName, contract, args) { +export function checkResolverReturns(resolverType, resolverName, contract, value) { // console.info('checkResolverReturns -->', resolverType, resolverName, contract, args) const def = getDefFromContract(resolverType, resolverName, contract) if (def) { - return checkReturns(args, def[RETURNS_NAME]) + // format the value + return checkReturns(value, def[RETURNS_NAME]) } - throw new JsonqlValidationError('checkResolverReturns', `${resolverType}.${resolverName} ${RETURNS_NAME} not found`) + throw new JsonqlValidationError( + 'checkResolverReturns', + `${resolverType}.${resolverName} ${RETURNS_NAME} not found` + ) } /** @@ -57,16 +83,19 @@ export function checkResolverReturns(resolverType, resolverName, contract, args) * @param {string} resolverType type of resolver (query, mutation, socket, auth) * @param {string} resolverName name of the resolver * @param {object} contract the full contract json - * @param {array} args the return results + * @param {array} value the raw return results * @return {*} */ -export function checkResolverReturnsAsync(resolverType, resolverName, contract, args) { +export function checkResolverReturnsAsync(resolverType, resolverName, contract, value) { const def = getDefFromContract(resolverType, resolverName, contract) if (def) { - return checkReturnsAsync(args, def[RETURNS_NAME]) + return checkReturns(value, def[RETURNS_NAME], true) } return Promise.reject( - new JsonqlValidationError('checkResolverReturnsAsync', `${resolverType}.${resolverName} ${RETURNS_NAME} not found`) + new JsonqlValidationError( + 'checkResolverReturnsAsync', + `${resolverType}.${resolverName} ${RETURNS_NAME} not found` + ) ) } diff --git a/packages/validator/src/validator.js b/packages/validator/src/validator.js index 04eba0c607c625d7c354bc5d624b7a7b8f687206..8f0f15832d747459cca94b8d27f8d1217cdba5ff 100644 --- a/packages/validator/src/validator.js +++ b/packages/validator/src/validator.js @@ -101,6 +101,7 @@ export const normalizeArgs = function(args, params) { return [] } if (!checkIsArray(args)) { + console.info(args) throw new JsonqlValidationError(ARGS_NOT_ARRAY_ERR) } // debugFn(args, params); diff --git a/packages/validator/tests/complex-object.test.js b/packages/validator/tests/complex-object.test.js index b30a07ca69bb1394f5c4d65918d2be4533fef3fd..be5a2a539a4ce853918ddab03344c4a312390089 100644 --- a/packages/validator/tests/complex-object.test.js +++ b/packages/validator/tests/complex-object.test.js @@ -19,7 +19,7 @@ test('Test with a complex array type check', t => { t.true(checkIsArray(keys), 'Pass the keys for payload from contract.json') t.false(checkIsArray(contractJson.mutation.setDetailObj.params.keys), 'Pass the wrong keys and suppose to fail') -}); +}) test('Test with complex object type check', t => { t.true( diff --git a/packages/jwt/tests/fixtures/contract.json b/packages/validator/tests/fixtures/contract-copy.json similarity index 71% rename from packages/jwt/tests/fixtures/contract.json rename to packages/validator/tests/fixtures/contract-copy.json index 72510498a1edea8f1eb2f2f5ea6a9970c66d8ba6..3728746dba80315150bf4d5c1b555326f0e25c17 100644 --- a/packages/jwt/tests/fixtures/contract.json +++ b/packages/validator/tests/fixtures/contract-copy.json @@ -2,10 +2,9 @@ "query": {}, "mutation": {}, "auth": {}, - "timestamp": 1560348254, + "timestamp": 1560347818, "socket": { "continuous": { - "namespace": "jsonql/private", "file": "/home/joel/projects/open-source/jsonqltools/packages/ws-client/tests/fixtures/resolvers/socket/continuous.js", "description": false, "params": [ @@ -26,31 +25,7 @@ } ] }, - "pinging": { - "namespace": "jsonql/public", - "public": true, - "file": "/home/joel/projects/open-source/jsonqltools/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js", - "description": false, - "params": [ - { - "type": [ - "string" - ], - "name": "msg", - "description": "message" - } - ], - "returns": [ - { - "type": [ - "string" - ], - "description": "reply message based on your message" - } - ] - }, "sendExtraMsg": { - "namespace": "jsonql/private", "file": "/home/joel/projects/open-source/jsonqltools/packages/ws-client/tests/fixtures/resolvers/socket/send-extra-msg.js", "description": false, "params": [ @@ -72,7 +47,6 @@ ] }, "simple": { - "namespace": "jsonql/private", "file": "/home/joel/projects/open-source/jsonqltools/packages/ws-client/tests/fixtures/resolvers/socket/simple.js", "description": false, "params": [ @@ -94,7 +68,6 @@ ] }, "throwError": { - "namespace": "jsonql/private", "file": "/home/joel/projects/open-source/jsonqltools/packages/ws-client/tests/fixtures/resolvers/socket/throw-error.js", "description": "Testing the throw error", "params": [], diff --git a/packages/validator/tests/return.test.js b/packages/validator/tests/return.test.js new file mode 100644 index 0000000000000000000000000000000000000000..ca967ba570f698c6258b0d2f11ec625943ffcf64 --- /dev/null +++ b/packages/validator/tests/return.test.js @@ -0,0 +1,44 @@ +// testing and develop further for the return check methods +const test = require('ava') +const { join } = require('path') +const fsx = require('fs-extra') +const { + QUERY_NAME, + DATA_KEY, + ERROR_KEY +} = require('jsonql-constants') +const { + checkResolverReturns, + checkResolverReturnsAsync +} = require('../dist/jsonql-params-validator.cjs.js') +const debug = require('debug')('jsonql-params-validator:test:return') + +test.before(t => { + t.context.contract = fsx.readJsonSync(join(__dirname, 'fixtures', 'contract.json')) + +}) + + +test(`Test the checkResolverReturns`, t => { + + const value = 1 //'whatever' + + // debug('toArray', [...value]) + + const result = checkResolverReturns(QUERY_NAME, 'getAnything', t.context.contract, value) + + debug('result', result) + + t.truthy(result[ERROR_KEY].length) +}) + +test.cb(`test the checkResolverReturnsAsync`, t => { + const value = 'whatever' + t.plan(1) + checkResolverReturnsAsync(QUERY_NAME, 'getAnything', t.context.contract, value) + .then(result => { + t.truthy(result[DATA_KEY].length) + t.end() + }) +}) + diff --git a/packages/validator/tests/validate-result.test.js b/packages/validator/tests/validate-result.test.js index ba1d272236e3497fe8be3f77f91c1d53565c480a..4672e02f24ceb185cb71c36bcd6a54bf680c7b01 100644 --- a/packages/validator/tests/validate-result.test.js +++ b/packages/validator/tests/validate-result.test.js @@ -6,9 +6,7 @@ const { DATA_KEY, ERROR_KEY, HELLO } = require('jsonql-constants') const contract = fsx.readJsonSync(join(__dirname, 'fixtures', 'contract.json')) const { validateSync, - validateAsync, - checkResolverReturns, - checkResolverReturnsAsync + validateAsync } = require('../dist/jsonql-params-validator.cjs') const debug = require('debug')('jsonql-params-validator:test:validate-result') @@ -44,32 +42,3 @@ test.cb('It should able to do the same with validate async but just resolve the }) }) -// put the new checkReturns method test here @1.6.0 -test(`Should able to check the return result using checkResolverReturns`, t => { - - const result = checkResolverReturns('query', 'helloWorld', t.context.contract, [HELLO]) - // if there the array is empty that means it's pass - t.falsy(result.length) - - const resultFail = checkResolverReturns('query', 'helloWorld', t.context.contract, [1]) - - t.truthy(resultFail.length) - - debug('fail result', resultFail) - -}) - -test.cb(`Should able to check the return result using checkResolverReturnsAsync`, t => { - t.plan(2) - - checkResolverReturnsAsync('query', 'helloWorld', t.context.contract, [HELLO]) - .then(result => { - t.falsy(result.length) - }) - - checkResolverReturnsAsync('query', 'helloWorld', t.context.contract, [123]) - .catch(result => { - t.truthy(result.length) - t.end() - }) -}) diff --git a/packages/ws-server-core/package.json b/packages/ws-server-core/package.json index 8dafdea81cc3b5562e57d7e88c419e39c1042973..c2e071f7636f8c8f7599a6d8652cec042ec89a40 100644 --- a/packages/ws-server-core/package.json +++ b/packages/ws-server-core/package.json @@ -27,23 +27,23 @@ "author": "Joel Chu ", "license": "MIT", "dependencies": { - "@to1source/event": "^1.0.0", + "@to1source/event": "^1.1.1", "colors": "^1.4.0", "debug": "^4.1.1", "esm": "^3.2.25", "fs-extra": "^9.0.0", - "jsonql-constants": "^2.0.9", + "jsonql-constants": "^2.0.10", "jsonql-errors": "^1.2.1", "jsonql-jwt": "^1.3.10", - "jsonql-params-validator": "^1.6.1", - "jsonql-resolver": "^1.2.0", - "jsonql-utils": "^1.2.4", + "jsonql-params-validator": "^1.6.2", + "jsonql-resolver": "^1.2.1", + "jsonql-utils": "^1.2.5", "lodash": "^4.17.15", "nanoid": "^2.1.11", "node-cache": "^5.1.0" }, "devDependencies": { - "ava": "^3.5.0", + "ava": "^3.5.1", "jsonql-contract": "^1.9.1" }, "ava": { diff --git a/packages/ws-server/package.json b/packages/ws-server/package.json index 00b59a72c92fa700973ca6f673fc154fa8efd34e..f158232065f2af1d4207abd4273f4d37a46cba80 100755 --- a/packages/ws-server/package.json +++ b/packages/ws-server/package.json @@ -33,13 +33,13 @@ "dependencies": { "colors": "^1.4.0", "debug": "^4.1.1", - "jsonql-constants": "^2.0.9", + "jsonql-constants": "^2.0.10", "jsonql-utils": "^1.2.4", "jsonql-ws-server-core": "^0.8.0", "ws": "^7.2.3" }, "devDependencies": { - "ava": "^3.5.0", + "ava": "^3.5.1", "jsonql-contract": "^1.9.1", "open": "^7.0.3" },