From 6daed3f26ec5dade353898e849a92c916e7dac92 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 18:46:18 +0800 Subject: [PATCH 1/7] reexport the missing forbidden error --- packages/errors/index.js | 2 + packages/errors/package.json | 2 +- packages/errors/src/index.js | 27 +- packages/http-client/core.js | 2 +- packages/http-client/core.js.map | 2 +- .../http-client/dist/jsonql-client.static.js | 9650 ++++++++++++++++- .../dist/jsonql-client.static.js.map | 2 +- .../http-client/dist/jsonql-client.umd.js | 9635 +++++++++++++++- .../http-client/dist/jsonql-client.umd.js.map | 2 +- packages/http-client/package.json | 4 +- packages/http-client/src/base/http-cls.js | 32 +- .../http-client/src/core/methods-generator.js | 5 +- packages/http-client/static.js | 2 +- packages/http-client/static.js.map | 2 +- .../tests/qunit/tests/base-test.js | 1 + 15 files changed, 19345 insertions(+), 25 deletions(-) diff --git a/packages/errors/index.js b/packages/errors/index.js index b7e5f662..9cc10f84 100644 --- a/packages/errors/index.js +++ b/packages/errors/index.js @@ -11,6 +11,7 @@ const JSONQL_ERRORS_INFO = '__PLACEHOLDER__' import { Jsonql406Error, Jsonql500Error, + JsonqlForbiddenError, JsonqlAuthorisationError, JsonqlContractAuthError, JsonqlResolverAppError, @@ -35,6 +36,7 @@ export { Jsonql406Error, Jsonql500Error, + JsonqlForbiddenError, JsonqlAuthorisationError, JsonqlContractAuthError, JsonqlResolverAppError, diff --git a/packages/errors/package.json b/packages/errors/package.json index 8537c6d6..516e1978 100644 --- a/packages/errors/package.json +++ b/packages/errors/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-errors", - "version": "1.1.8", + "version": "1.1.9", "description": "Jsonql js error classes use across the projects", "main": "dist/jsonql-errors.cjs.js", "module": "index.js", diff --git a/packages/errors/src/index.js b/packages/errors/src/index.js index d8f6bbf5..48eb6134 100644 --- a/packages/errors/src/index.js +++ b/packages/errors/src/index.js @@ -1,24 +1,27 @@ // server side -import Jsonql406Error from './406-error'; -import Jsonql500Error from './500-error'; -import JsonqlAuthorisationError from './authorisation-error'; -import JsonqlContractAuthError from './contract-auth-error'; -import JsonqlResolverAppError from './resolver-app-error'; -import JsonqlResolverNotFoundError from './resolver-not-found-error'; +import Jsonql406Error from './406-error' +import Jsonql500Error from './500-error' + +import JsonqlForbiddenError from './forbidden-error' +import JsonqlAuthorisationError from './authorisation-error' +import JsonqlContractAuthError from './contract-auth-error' +import JsonqlResolverAppError from './resolver-app-error' +import JsonqlResolverNotFoundError from './resolver-not-found-error' // check options error -import JsonqlEnumError from './enum-error'; -import JsonqlTypeError from './type-error'; -import JsonqlCheckerError from './checker-error'; +import JsonqlEnumError from './enum-error' +import JsonqlTypeError from './type-error' +import JsonqlCheckerError from './checker-error' // share -import JsonqlValidationError from './validation-error'; -import JsonqlError from './error'; +import JsonqlValidationError from './validation-error' +import JsonqlError from './error' -import JsonqlServerError from './server-error'; +import JsonqlServerError from './server-error' export { Jsonql406Error, Jsonql500Error, + JsonqlForbiddenError, JsonqlAuthorisationError, JsonqlContractAuthError, JsonqlResolverAppError, diff --git a/packages/http-client/core.js b/packages/http-client/core.js index 1e62e9a5..7803868c 100644 --- a/packages/http-client/core.js +++ b/packages/http-client/core.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClient=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b=Array.isArray,_="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},m="object"==typeof _&&_&&_.Object===Object&&_,w="object"==typeof self&&self&&self.Object===Object&&self,j=m||w||Function("return this")(),S=j.Symbol,O=Object.prototype,k=O.hasOwnProperty,A=O.toString,E=S?S.toStringTag:void 0;var T=Object.prototype.toString;var x="[object Null]",P="[object Undefined]",q=S?S.toStringTag:void 0;function C(t){return null==t?void 0===t?P:x:q&&q in Object(t)?function(t){var e=k.call(t,E),r=t[E];try{t[E]=void 0;var n=!0}catch(t){}var o=A.call(t);return n&&(e?t[E]=r:delete t[E]),o}(t):function(t){return T.call(t)}(t)}function $(t,e){return function(r){return t(e(r))}}var z=$(Object.getPrototypeOf,Object);function N(t){return null!=t&&"object"==typeof t}var M="[object Object]",I=Function.prototype,R=Object.prototype,F=I.toString,J=R.hasOwnProperty,U=F.call(Object);function D(t){if(!N(t)||C(t)!=M)return!1;var e=z(t);if(null===e)return!0;var r=J.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&F.call(r)==U}var H=function(t){return b(t)?t:[t]},L=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},B=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),K=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),G=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),V=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),W=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),Y=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),Q=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),X=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),Z=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),rt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),nt=Object.freeze({__proto__:null,Jsonql406Error:B,Jsonql500Error:K,JsonqlAuthorisationError:G,JsonqlContractAuthError:V,JsonqlResolverAppError:W,JsonqlResolverNotFoundError:Y,JsonqlEnumError:Q,JsonqlTypeError:X,JsonqlCheckerError:Z,JsonqlValidationError:tt,JsonqlError:et,JsonqlServerError:rt}),ot=et,it=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function at(t){if(it(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&nt[o])throw new nt[r](i,a);throw new ot(i,a)}return t}function ut(t){if(Array.isArray(t))throw new tt("",t);var e=t.message||y,r=t.detail||t;switch(!0){case t instanceof B:throw new B(e,r);case t instanceof K:throw new K(e,r);case t instanceof G:throw new G(e,r);case t instanceof V:throw new V(e,r);case t instanceof W:throw new W(e,r);case t instanceof Y:throw new Y(e,r);case t instanceof Q:throw new Q(e,r);case t instanceof X:throw new X(e,r);case t instanceof Z:throw new Z(e,r);case t instanceof tt:throw new tt(e,r);case t instanceof rt:throw new rt(e,r);default:throw new et(e,r)}}function ct(t){return!!function(t){return D(t)&&(L(t,r)||L(t,n)||L(t,o))}(t)&&t}function st(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var ft=function(t,e){return void 0===e&&(e={}),ct(e)?Promise.resolve(e):t.getContract()},lt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function pt(t){this.message=t}pt.prototype=new Error,pt.prototype.name="InvalidCharacterError";var ht="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new pt("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=lt.indexOf(n);return a};var dt=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(ht(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return ht(e)}};function vt(t){this.message=t}vt.prototype=new Error,vt.prototype.name="InvalidTokenError";var gt=function(t,e){if("string"!=typeof t)throw new vt("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(dt(t.split(".")[r]))}catch(t){throw new vt("Invalid token specified: "+t.message)}},yt=vt;function bt(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&Et(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var Ht="[object String]";function Lt(t){return"string"==typeof t||!b(t)&&N(t)&&C(t)==Ht}var Bt=function(t){return""!==Dt(t)&&Lt(t)},Kt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Gt(t){if(Bt(t))return function(t){var e=t.iat||Kt(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new et("Token has expired on "+r,t)}return t}(gt(t));throw new et("Token must be a string!")}var Vt=function(t){return!!b(t)||null!=t&&""!==Dt(t)},Wt="[object Number]";function Yt(t){return function(t){return"number"==typeof t||N(t)&&C(t)==Wt}(t)&&t!=+t}var Qt=function(t){return!Lt(t)&&!Yt(parseFloat(t))},Xt=function(t){return null!=t&&"boolean"==typeof t},Zt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==Dt(t)&&(!1===e||!0===e&&null!==t)},te=s,ee=f,re=l,ne=p,oe=h,ie=d,ae="continue",ue=function(t){switch(t){case"number":return Qt;case"string":return Bt;case"boolean":return Xt;default:return Zt}},ce=function(t,e){return void 0===e&&(e=""),!!b(t)&&(""===e||""===Dt(e)||!(t.filter((function(t){return!ue(e)(t)})).length>0))},se=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},fe=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ue(e)(t)})).length)})).length:e.length>e.filter((function(t){return!ce(r,t)})).length};var le,pe=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[le?a:++n];if(!1===e(o[u],u,o))break}return t};var he="[object Arguments]";function de(t){return N(t)&&C(t)==he}var ve=Object.prototype,ge=ve.hasOwnProperty,ye=ve.propertyIsEnumerable,be=de(function(){return arguments}())?de:function(t){return N(t)&&ge.call(t,"callee")&&!ye.call(t,"callee")};var _e="object"==typeof exports&&exports&&!exports.nodeType&&exports,me=_e&&"object"==typeof module&&module&&!module.nodeType&&module,we=me&&me.exports===_e?j.Buffer:void 0,je=(we?we.isBuffer:void 0)||function(){return!1},Se=9007199254740991,Oe=/^(?:0|[1-9]\d*)$/;function ke(t,e){var r=typeof t;return!!(e=null==e?Se:e)&&("number"==r||"symbol"!=r&&Oe.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=Ae}var Te={};Te["[object Float32Array]"]=Te["[object Float64Array]"]=Te["[object Int8Array]"]=Te["[object Int16Array]"]=Te["[object Int32Array]"]=Te["[object Uint8Array]"]=Te["[object Uint8ClampedArray]"]=Te["[object Uint16Array]"]=Te["[object Uint32Array]"]=!0,Te["[object Arguments]"]=Te["[object Array]"]=Te["[object ArrayBuffer]"]=Te["[object Boolean]"]=Te["[object DataView]"]=Te["[object Date]"]=Te["[object Error]"]=Te["[object Function]"]=Te["[object Map]"]=Te["[object Number]"]=Te["[object Object]"]=Te["[object RegExp]"]=Te["[object Set]"]=Te["[object String]"]=Te["[object WeakMap]"]=!1;var xe,Pe="object"==typeof exports&&exports&&!exports.nodeType&&exports,qe=Pe&&"object"==typeof module&&module&&!module.nodeType&&module,Ce=qe&&qe.exports===Pe&&m.process,$e=function(){try{var t=qe&&qe.require&&qe.require("util").types;return t||Ce&&Ce.binding&&Ce.binding("util")}catch(t){}}(),ze=$e&&$e.isTypedArray,Ne=ze?(xe=ze,function(t){return xe(t)}):function(t){return N(t)&&Ee(t.length)&&!!Te[C(t)]},Me=Object.prototype.hasOwnProperty;function Ie(t,e){var r=b(t),n=!r&&be(t),o=!r&&!n&&je(t),i=!r&&!n&&!o&&Ne(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},tr.prototype.set=function(t,e){var r=this.__data__,n=Xe(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var er,rr=j["__core-js_shared__"],nr=(er=/[^.]+$/.exec(rr&&rr.keys&&rr.keys.IE_PROTO||""))?"Symbol(src)_1."+er:"";var or=Function.prototype.toString;function ir(t){if(null!=t){try{return or.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ar=/^\[object .+?Constructor\]$/,ur=Function.prototype,cr=Object.prototype,sr=ur.toString,fr=cr.hasOwnProperty,lr=RegExp("^"+sr.call(fr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function pr(t){return!(!De(t)||function(t){return!!nr&&nr in t}(t))&&(Ge(t)?lr:ar).test(ir(t))}function hr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return pr(r)?r:void 0}var dr=hr(j,"Map"),vr=hr(Object,"create");var gr="__lodash_hash_undefined__",yr=Object.prototype.hasOwnProperty;var br=Object.prototype.hasOwnProperty;var _r="__lodash_hash_undefined__";function mr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&xr?new Ar:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=se(t))?!fe({arg:r},e):!ue(t)(r))})).length)})).length}return!1},Yn=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Wn,null,a);case"array"===t:return!ce(e.arg);case!1!==(r=se(t)):return!fe(e,r);default:return!ue(t)(e.arg)}},Qn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Xn=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!ce(e))throw new et("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!ce(t))throw new et("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Qn(t,a):t,index:r,param:a,optional:i}}));default:throw new et("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Vt(e)&&!(r.type.length>r.type.filter((function(e){return Yn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Yn(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Zn=function(){try{var t=hr(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function to(t,e,r){"__proto__"==e&&Zn?Zn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function eo(t,e,r){(void 0===r||Qe(t[e],r))&&(void 0!==r||e in t)||to(t,e,r)}var ro="object"==typeof exports&&exports&&!exports.nodeType&&exports,no=ro&&"object"==typeof module&&module&&!module.nodeType&&module,oo=no&&no.exports===ro?j.Buffer:void 0,io=oo?oo.allocUnsafe:void 0;function ao(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new qr(n).set(new qr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var uo=Object.create,co=function(){function t(){}return function(e){if(!De(e))return{};if(uo)return uo(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function so(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var fo=Object.prototype.hasOwnProperty;function lo(t,e,r){var n=t[e];fo.call(t,e)&&Qe(n,r)&&(void 0!==r||e in t)||to(t,e,r)}var po=Object.prototype.hasOwnProperty;function ho(t){if(!De(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Fe(t),r=[];for(var n in t)("constructor"!=n||!e&&po.call(t,n))&&r.push(n);return r}function vo(t){return Ve(t)?Ie(t,!0):ho(t)}function go(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=jo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(wo);function Ao(t,e){return ko(function(t,e,r){return e=mo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=mo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Eo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!De(r))return!1;var n=typeof e;return!!("number"==n?Ve(r)&&ke(e,r.length):"string"==n&&e in r)&&Qe(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=0;e--){var r=qi().key(e);t(Ci(r),r)}},remove:function(t){return qi().removeItem(t)},clearAll:function(){return qi().clear()}};function qi(){return xi.localStorage}function Ci(t){return qi().getItem(t)}var $i=hi.trim,zi={name:"cookieStorage",read:function(t){if(!t||!Ri(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Ni.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Ni.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Mi,remove:Ii,clearAll:function(){Mi((function(t,e){Ii(e)}))}},Ni=hi.Global.document;function Mi(t){for(var e=Ni.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if($i(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Ii(t){t&&Ri(t)&&(Ni.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Ri(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Ni.cookie)}var Fi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Ji=hi.bind,Ui=hi.each,Di=hi.create,Hi=hi.slice,Li=function(){var t=Di(Bi,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Ji(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Ji(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),Ui(r,(function(e,r){t.fire(r,void 0,e)}))}}};var Bi={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Ji(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Hi(arguments,1);Ui(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},Ki=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),Gi=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=Ki.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=Ki.compress(this._serialize(r));t(e,n)}}};var Vi=[Pi,zi],Wi=[Fi,Li,Gi],Yi=Ai.createStore(Vi,Wi),Qi=hi.Global;function Xi(){return Qi.sessionStorage}function Zi(t){return Xi().getItem(t)}var ta=[{name:"sessionStorage",read:Zi,write:function(t,e){return Xi().setItem(t,e)},each:function(t){for(var e=Xi().length-1;e>=0;e--){var r=Xi().key(e);t(Zi(r),r)}},remove:function(t){return Xi().removeItem(t)},clearAll:function(){return Xi().clear()}},zi],ea=[Fi,Gi],ra=Ai.createStore(ta,ea),na=Yi,oa=ra,ia=function(t){var e;return(e={}).args=t,e};function aa(t,e){var r;return(r={})[t]=e,r[u]=[ui()],r}var ua=function(t){return L(t,"data")&&!L(t,"error")?t.data:t},ca=function(t){this.opts=t,this.instanceKey=st(this.opts.hostname)+"",this.localStore=na,this.sessionStore=oa},sa={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};ca.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?To({},o,e):e,r))},ca.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},ca.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},ca.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},sa.lset.set=function(t){return this.__setMethod("localStore",t)},sa.lget.get=function(){return this.__getMethod("localStore")},ca.prototype.ldel=function(t){return this.__delMethod("localStore",t)},ca.prototype.lclear=function(){return this.__clearMethod("localStore")},sa.sset.set=function(t){return this.__setMethod("sessionStore",t)},sa.sget.get=function(){return this.__getMethod("sessionStore")},ca.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},ca.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(ca.prototype,sa);var fa=c[0],la=c[1],pa=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];!0===this.opts.debugOn&&Reflect.apply(console.info,console,t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Gt)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(ni(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new tt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&ni(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!ct(t))throw new tt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=ct(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=To({},{_cb:ui()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=To({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=To({},{method:fa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return ua(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=ri(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ua(o)}),(function(t){throw e.cleanUp(),console.error(t),new rt("Server side error",t)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?To({},e,this.getAuthHeader(),this.extraHeader):To({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=To({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(at).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(t){throw console.error("getRemoteContract err",t),new rt("getRemoteContract",t)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Lt(t)&&b(e)){var n=ia(e);return!0===r?n:aa(t,n)}throw new tt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(at)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Lt(t))return aa(t,o);throw new tt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:la}).then(at)},Object.defineProperties(r.prototype,n),r}(ca)))),ha=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,H(t))}),Reflect.apply(t,null,r))}};function da(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function va(t,e,r,n){void 0===n&&(n=!1);var o=da(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var ga=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return oi(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch(ut)}},ya=function(t,e,r,n,o){var i={},a=function(t){i=va(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return oi(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch(ut)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},ba=function(t,e,r,n,o){var i={},a=function(t){i=va(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return oi(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch(ut)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},_a=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ga(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ga(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var ma=function(t,e,r,n){var o=function(t,e,r,n){return ha(ya,ba,_a)({},t,e,r,n)}(t,n,e,r);return e.enableAuth&&(o.userdata=function(){return t.jsonqlUserdata},o.getToken=function(e){return void 0===e&&(e=!1),t.rawAuthToken(e)},o.profileIndex=function(e){if(void 0===e&&(e=!1),!1===e)return t.profileIndex;t.profileIndex=e},o.getProfiles=function(e){return void 0===e&&(e=!1),t.getProfiles(e)}),e.exposeContract&&(o.getContract=function(){return t.getContract()}),e.exposeStore&&(o.tmpSave=function(t){},o.tmpGet=function(t){},o.tmpDel=function(t){},o.persistSave=function(t){},o.persistGet=function(t){},o.persistDel=function(t){}),o.eventEmitter=n,o.version="1.5.1",o.log=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return Reflect.apply(t.log,t,["[DEV DEBUG]"].concat(e))},o},wa={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},ja={hostname:ii(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:ii("jsonql",["string"]),loginHandlerName:ii("login",["string"]),logoutHandlerName:ii("logout",["string"]),enableJsonp:ii(!1,["boolean"]),enableAuth:ii(!1,["boolean"]),useJwt:ii(!0,["boolean"]),persistToken:ii(!1,["boolean","number"]),useLocalstorage:ii(!0,["boolean"]),storageKey:ii("jsonqlstore",["string"]),authKey:ii("jsonqlauthkey",["string"]),contractExpired:ii(0,["number"]),keepContract:ii(!0,["boolean"]),exposeContract:ii(!1,["boolean"]),exposeStore:ii(!1,["boolean"]),showContractDesc:ii(!1,["boolean"]),contractKey:ii(!1,["boolean"]),contractKeyName:ii("X-JSONQL-CV-KEY",["string"]),enableTimeout:ii(!1,["boolean"]),timeout:ii(5e3,["number"]),returnInstance:ii(!1,["boolean"]),allowReturnRawToken:ii(!1,["boolean"]),debugOn:ii(!1,["boolean"])};function Sa(t){return da(t,v)?Promise.resolve(t):function(t){var e=t.contract;return ai(t,ja,wa).then((function(t){return t.contract=e,t}))}(t)}var Oa=new WeakMap,ka=new WeakMap,Aa=function(){this.__suspend__=null,this.queueStore=new Set},Ea={$suspend:{configurable:!0},$queues:{configurable:!0}};Ea.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Aa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ea.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Aa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Aa.prototype,Ea);var Ta=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Oa.set(this,t)},r.normalStore.get=function(){return Oa.get(this)},r.lazyStore.set=function(t){ka.set(this,t)},r.lazyStore.get=function(){return ka.get(this)},e.prototype.hashFnToKey=function(t){return st(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Aa));return function(t,e){var r;return function(t,e,r){return void 0===e&&(e={}),Sa(e).then((function(t){return{baseClient:new pa(r,t),opts:t}})).then((function(e){var r=e.baseClient,n=e.opts;return ft(r,n.contract).then((function(e){return ma(r,n,e,t)}))}))}((r=e.debugOn,new Ta({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),e,t)}})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClient=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b=Array.isArray,_="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},m="object"==typeof _&&_&&_.Object===Object&&_,w="object"==typeof self&&self&&self.Object===Object&&self,j=m||w||Function("return this")(),S=j.Symbol,O=Object.prototype,k=O.hasOwnProperty,A=O.toString,E=S?S.toStringTag:void 0;var T=Object.prototype.toString;var x="[object Null]",P="[object Undefined]",q=S?S.toStringTag:void 0;function C(t){return null==t?void 0===t?P:x:q&&q in Object(t)?function(t){var e=k.call(t,E),r=t[E];try{t[E]=void 0;var n=!0}catch(t){}var o=A.call(t);return n&&(e?t[E]=r:delete t[E]),o}(t):function(t){return T.call(t)}(t)}function $(t,e){return function(r){return t(e(r))}}var z=$(Object.getPrototypeOf,Object);function N(t){return null!=t&&"object"==typeof t}var M="[object Object]",I=Function.prototype,R=Object.prototype,F=I.toString,J=R.hasOwnProperty,U=F.call(Object);function D(t){if(!N(t)||C(t)!=M)return!1;var e=z(t);if(null===e)return!0;var r=J.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&F.call(r)==U}function H(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&X(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var dt=function(t){return b(t)?t:[t]},vt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},gt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),yt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),bt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),_t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),mt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),Tt=Object.freeze({__proto__:null,Jsonql406Error:gt,Jsonql500Error:yt,JsonqlAuthorisationError:bt,JsonqlContractAuthError:_t,JsonqlResolverAppError:mt,JsonqlResolverNotFoundError:wt,JsonqlEnumError:jt,JsonqlTypeError:St,JsonqlCheckerError:Ot,JsonqlValidationError:kt,JsonqlError:At,JsonqlServerError:Et}),xt=At,Pt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function qt(t){if(Pt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&Tt[o])throw new Tt[r](i,a);throw new xt(i,a)}return t}function Ct(t){if(Array.isArray(t))throw new kt("",t);var e=t.message||y,r=t.detail||t;switch(!0){case t instanceof gt:throw new gt(e,r);case t instanceof yt:throw new yt(e,r);case t instanceof bt:throw new bt(e,r);case t instanceof _t:throw new _t(e,r);case t instanceof mt:throw new mt(e,r);case t instanceof wt:throw new wt(e,r);case t instanceof jt:throw new jt(e,r);case t instanceof St:throw new St(e,r);case t instanceof Ot:throw new Ot(e,r);case t instanceof kt:throw new kt(e,r);case t instanceof Et:throw new Et(e,r);default:throw new At(e,r)}}function $t(t){return!!function(t){return D(t)&&(vt(t,r)||vt(t,n)||vt(t,o))}(t)&&t}function zt(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var Nt=function(t,e){return void 0===e&&(e={}),$t(e)?Promise.resolve(e):t.getContract()},Mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function It(t){this.message=t}It.prototype=new Error,It.prototype.name="InvalidCharacterError";var Rt="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new It("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=Mt.indexOf(n);return a};var Ft=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Rt(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return Rt(e)}};function Jt(t){this.message=t}Jt.prototype=new Error,Jt.prototype.name="InvalidTokenError";var Ut=function(t,e){if("string"!=typeof t)throw new Jt("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(Ft(t.split(".")[r]))}catch(t){throw new Jt("Invalid token specified: "+t.message)}},Dt=Jt;Ut.InvalidTokenError=Dt;var Ht="[object String]";function Lt(t){return"string"==typeof t||!b(t)&&N(t)&&C(t)==Ht}var Bt=function(t){return""!==ht(t)&&Lt(t)},Kt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Gt(t){if(Bt(t))return function(t){var e=t.iat||Kt(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new At("Token has expired on "+r,t)}return t}(Ut(t));throw new At("Token must be a string!")}var Vt=function(t){return!!b(t)||null!=t&&""!==ht(t)},Wt="[object Number]";function Yt(t){return function(t){return"number"==typeof t||N(t)&&C(t)==Wt}(t)&&t!=+t}var Qt=function(t){return!Lt(t)&&!Yt(parseFloat(t))},Xt=function(t){return null!=t&&"boolean"==typeof t},Zt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==ht(t)&&(!1===e||!0===e&&null!==t)},te=s,ee=f,re=l,ne=p,oe=h,ie=d,ae="continue",ue=function(t){switch(t){case"number":return Qt;case"string":return Bt;case"boolean":return Xt;default:return Zt}},ce=function(t,e){return void 0===e&&(e=""),!!b(t)&&(""===e||""===ht(e)||!(t.filter((function(t){return!ue(e)(t)})).length>0))},se=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},fe=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ue(e)(t)})).length)})).length:e.length>e.filter((function(t){return!ce(r,t)})).length};var le,pe=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[le?a:++n];if(!1===e(o[u],u,o))break}return t};var he="[object Arguments]";function de(t){return N(t)&&C(t)==he}var ve=Object.prototype,ge=ve.hasOwnProperty,ye=ve.propertyIsEnumerable,be=de(function(){return arguments}())?de:function(t){return N(t)&&ge.call(t,"callee")&&!ye.call(t,"callee")};var _e="object"==typeof exports&&exports&&!exports.nodeType&&exports,me=_e&&"object"==typeof module&&module&&!module.nodeType&&module,we=me&&me.exports===_e?j.Buffer:void 0,je=(we?we.isBuffer:void 0)||function(){return!1},Se=9007199254740991,Oe=/^(?:0|[1-9]\d*)$/;function ke(t,e){var r=typeof t;return!!(e=null==e?Se:e)&&("number"==r||"symbol"!=r&&Oe.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=Ae}var Te={};Te["[object Float32Array]"]=Te["[object Float64Array]"]=Te["[object Int8Array]"]=Te["[object Int16Array]"]=Te["[object Int32Array]"]=Te["[object Uint8Array]"]=Te["[object Uint8ClampedArray]"]=Te["[object Uint16Array]"]=Te["[object Uint32Array]"]=!0,Te["[object Arguments]"]=Te["[object Array]"]=Te["[object ArrayBuffer]"]=Te["[object Boolean]"]=Te["[object DataView]"]=Te["[object Date]"]=Te["[object Error]"]=Te["[object Function]"]=Te["[object Map]"]=Te["[object Number]"]=Te["[object Object]"]=Te["[object RegExp]"]=Te["[object Set]"]=Te["[object String]"]=Te["[object WeakMap]"]=!1;var xe,Pe="object"==typeof exports&&exports&&!exports.nodeType&&exports,qe=Pe&&"object"==typeof module&&module&&!module.nodeType&&module,Ce=qe&&qe.exports===Pe&&m.process,$e=function(){try{var t=qe&&qe.require&&qe.require("util").types;return t||Ce&&Ce.binding&&Ce.binding("util")}catch(t){}}(),ze=$e&&$e.isTypedArray,Ne=ze?(xe=ze,function(t){return xe(t)}):function(t){return N(t)&&Ee(t.length)&&!!Te[C(t)]},Me=Object.prototype.hasOwnProperty;function Ie(t,e){var r=b(t),n=!r&&be(t),o=!r&&!n&&je(t),i=!r&&!n&&!o&&Ne(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},tr.prototype.set=function(t,e){var r=this.__data__,n=Xe(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var er,rr=j["__core-js_shared__"],nr=(er=/[^.]+$/.exec(rr&&rr.keys&&rr.keys.IE_PROTO||""))?"Symbol(src)_1."+er:"";var or=Function.prototype.toString;function ir(t){if(null!=t){try{return or.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ar=/^\[object .+?Constructor\]$/,ur=Function.prototype,cr=Object.prototype,sr=ur.toString,fr=cr.hasOwnProperty,lr=RegExp("^"+sr.call(fr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function pr(t){return!(!De(t)||function(t){return!!nr&&nr in t}(t))&&(Ge(t)?lr:ar).test(ir(t))}function hr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return pr(r)?r:void 0}var dr=hr(j,"Map"),vr=hr(Object,"create");var gr="__lodash_hash_undefined__",yr=Object.prototype.hasOwnProperty;var br=Object.prototype.hasOwnProperty;var _r="__lodash_hash_undefined__";function mr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&xr?new Ar:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=se(t))?!fe({arg:r},e):!ue(t)(r))})).length)})).length}return!1},Yn=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Wn,null,a);case"array"===t:return!ce(e.arg);case!1!==(r=se(t)):return!fe(e,r);default:return!ue(t)(e.arg)}},Qn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Xn=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!ce(e))throw new At("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!ce(t))throw new At("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Qn(t,a):t,index:r,param:a,optional:i}}));default:throw new At("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Vt(e)&&!(r.type.length>r.type.filter((function(e){return Yn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Yn(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Zn=function(){try{var t=hr(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function to(t,e,r){"__proto__"==e&&Zn?Zn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function eo(t,e,r){(void 0===r||Qe(t[e],r))&&(void 0!==r||e in t)||to(t,e,r)}var ro="object"==typeof exports&&exports&&!exports.nodeType&&exports,no=ro&&"object"==typeof module&&module&&!module.nodeType&&module,oo=no&&no.exports===ro?j.Buffer:void 0,io=oo?oo.allocUnsafe:void 0;function ao(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new qr(n).set(new qr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var uo=Object.create,co=function(){function t(){}return function(e){if(!De(e))return{};if(uo)return uo(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function so(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var fo=Object.prototype.hasOwnProperty;function lo(t,e,r){var n=t[e];fo.call(t,e)&&Qe(n,r)&&(void 0!==r||e in t)||to(t,e,r)}var po=Object.prototype.hasOwnProperty;function ho(t){if(!De(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Fe(t),r=[];for(var n in t)("constructor"!=n||!e&&po.call(t,n))&&r.push(n);return r}function vo(t){return Ve(t)?Ie(t,!0):ho(t)}function go(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=jo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(wo);function Ao(t,e){return ko(function(t,e,r){return e=mo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=mo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Eo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!De(r))return!1;var n=typeof e;return!!("number"==n?Ve(r)&&ke(e,r.length):"string"==n&&e in r)&&Qe(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=0;e--){var r=qi().key(e);t(Ci(r),r)}},remove:function(t){return qi().removeItem(t)},clearAll:function(){return qi().clear()}};function qi(){return xi.localStorage}function Ci(t){return qi().getItem(t)}var $i=hi.trim,zi={name:"cookieStorage",read:function(t){if(!t||!Ri(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Ni.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Ni.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Mi,remove:Ii,clearAll:function(){Mi((function(t,e){Ii(e)}))}},Ni=hi.Global.document;function Mi(t){for(var e=Ni.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if($i(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Ii(t){t&&Ri(t)&&(Ni.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Ri(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Ni.cookie)}var Fi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Ji=hi.bind,Ui=hi.each,Di=hi.create,Hi=hi.slice,Li=function(){var t=Di(Bi,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Ji(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Ji(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),Ui(r,(function(e,r){t.fire(r,void 0,e)}))}}};var Bi={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Ji(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Hi(arguments,1);Ui(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},Ki=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),Gi=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=Ki.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=Ki.compress(this._serialize(r));t(e,n)}}};var Vi=[Pi,zi],Wi=[Fi,Li,Gi],Yi=Ai.createStore(Vi,Wi),Qi=hi.Global;function Xi(){return Qi.sessionStorage}function Zi(t){return Xi().getItem(t)}var ta=[{name:"sessionStorage",read:Zi,write:function(t,e){return Xi().setItem(t,e)},each:function(t){for(var e=Xi().length-1;e>=0;e--){var r=Xi().key(e);t(Zi(r),r)}},remove:function(t){return Xi().removeItem(t)},clearAll:function(){return Xi().clear()}},zi],ea=[Fi,Gi],ra=Ai.createStore(ta,ea),na=Yi,oa=ra,ia=function(t){var e;return(e={}).args=t,e};function aa(t,e){var r;return(r={})[t]=e,r[u]=[ui()],r}var ua=function(t){return vt(t,"data")&&!vt(t,"error")?t.data:t},ca=function(t){this.opts=t,this.instanceKey=zt(this.opts.hostname)+"",this.localStore=na,this.sessionStore=oa},sa={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};ca.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?To({},o,e):e,r))},ca.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},ca.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},ca.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},sa.lset.set=function(t){return this.__setMethod("localStore",t)},sa.lget.get=function(){return this.__getMethod("localStore")},ca.prototype.ldel=function(t){return this.__delMethod("localStore",t)},ca.prototype.lclear=function(){return this.__clearMethod("localStore")},sa.sset.set=function(t){return this.__setMethod("sessionStore",t)},sa.sget.get=function(){return this.__getMethod("sessionStore")},ca.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},ca.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(ca.prototype,sa);var fa=c[0],la=c[1],pa=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];!0===this.opts.debugOn&&Reflect.apply(console.info,console,t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Gt)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(ni(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new kt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&ni(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!$t(t))throw new kt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=$t(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=To({},{_cb:ui()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=To({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=To({},{method:fa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return ua(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=ri(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ua(o)}),(function(t){throw e.cleanUp(),console.error(t),new Et("Server side error",t)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?To({},e,this.getAuthHeader(),this.extraHeader):To({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=To({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(qt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(t){throw console.error("getRemoteContract err",t),new Et("getRemoteContract",t)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Lt(t)&&b(e)){var n=ia(e);return!0===r?n:aa(t,n)}throw new kt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(qt)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Lt(t))return aa(t,o);throw new kt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:la}).then(qt)},Object.defineProperties(r.prototype,n),r}(ca)))),ha=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,dt(t))}),Reflect.apply(t,null,r))}};function da(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function va(t,e,r,n){void 0===n&&(n=!1);var o=da(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var ga=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return oi(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch(Ct)}},ya=function(t,e,r,n,o){var i={},a=function(t){i=va(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return oi(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch(Ct)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},ba=function(t,e,r,n,o){var i={},a=function(t){i=va(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return oi(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch(Ct)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},_a=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ga(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ga(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var ma=function(t,e,r,n){var o=function(t,e,r,n){return ha(ya,ba,_a)({},t,e,r,n)}(t,n,e,r);return e.enableAuth&&(o.userdata=function(){return t.jsonqlUserdata},o.getToken=function(e){return void 0===e&&(e=!1),t.rawAuthToken(e)},o.profileIndex=function(e){if(void 0===e&&(e=!1),!1===e)return t.profileIndex;t.profileIndex=e},o.getProfiles=function(e){return void 0===e&&(e=!1),t.getProfiles(e)}),e.exposeContract&&(o.getContract=function(){return t.getContract()}),e.exposeStore&&(o.tmpSave=function(t){},o.tmpGet=function(t){},o.tmpDel=function(t){},o.persistSave=function(t){},o.persistGet=function(t){},o.persistDel=function(t){}),o.eventEmitter=n,o.version="1.5.1",o.log=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return Reflect.apply(t.log,t,["[DEV DEBUG]"].concat(e))},o},wa={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},ja={hostname:ii(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:ii("jsonql",["string"]),loginHandlerName:ii("login",["string"]),logoutHandlerName:ii("logout",["string"]),enableJsonp:ii(!1,["boolean"]),enableAuth:ii(!1,["boolean"]),useJwt:ii(!0,["boolean"]),persistToken:ii(!1,["boolean","number"]),useLocalstorage:ii(!0,["boolean"]),storageKey:ii("jsonqlstore",["string"]),authKey:ii("jsonqlauthkey",["string"]),contractExpired:ii(0,["number"]),keepContract:ii(!0,["boolean"]),exposeContract:ii(!1,["boolean"]),exposeStore:ii(!1,["boolean"]),showContractDesc:ii(!1,["boolean"]),contractKey:ii(!1,["boolean"]),contractKeyName:ii("X-JSONQL-CV-KEY",["string"]),enableTimeout:ii(!1,["boolean"]),timeout:ii(5e3,["number"]),returnInstance:ii(!1,["boolean"]),allowReturnRawToken:ii(!1,["boolean"]),debugOn:ii(!1,["boolean"])};function Sa(t){return da(t,v)?Promise.resolve(t):function(t){var e=t.contract;return ai(t,ja,wa).then((function(t){return t.contract=e,t}))}(t)}var Oa=new WeakMap,ka=new WeakMap,Aa=function(){this.__suspend__=null,this.queueStore=new Set},Ea={$suspend:{configurable:!0},$queues:{configurable:!0}};Ea.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Aa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ea.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Aa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Aa.prototype,Ea);var Ta=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Oa.set(this,t)},r.normalStore.get=function(){return Oa.get(this)},r.lazyStore.set=function(t){ka.set(this,t)},r.lazyStore.get=function(){return ka.get(this)},e.prototype.hashFnToKey=function(t){return zt(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Aa));return function(t,e){var r;return function(t,e,r){return void 0===e&&(e={}),Sa(e).then((function(t){return{baseClient:new pa(r,t),opts:t}})).then((function(e){var r=e.baseClient,n=e.opts;return Nt(r,n.contract).then((function(e){return ma(r,n,e,t)}))}))}((r=e.debugOn,new Ta({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),e,t)}})); //# sourceMappingURL=core.js.map diff --git a/packages/http-client/core.js.map b/packages/http-client/core.js.map index 04ea2db5..d85cb822 100644 --- a/packages/http-client/core.js.map +++ b/packages/http-client/core.js.map @@ -1 +1 @@ -{"version":3,"file":"core.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"21vCAAA"} \ No newline at end of file +{"version":3,"file":"core.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"y2vCAAA"} \ No newline at end of file diff --git a/packages/http-client/dist/jsonql-client.static.js b/packages/http-client/dist/jsonql-client.static.js index 2a0a7ef7..3cb965c0 100644 --- a/packages/http-client/dist/jsonql-client.static.js +++ b/packages/http-client/dist/jsonql-client.static.js @@ -1,2 +1,9650 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClientStatic=e()}(this,(function(){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r,n=e((function(t,e){var r;r=function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=2)}([function(t,e,r){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};t.exports={type:function(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()},isObject:function(t,e){return e?"object"===this.type(t):t&&"object"===(void 0===t?"undefined":n(t))},isFormData:function(t){return"undefined"!=typeof FormData&&t instanceof FormData},trim:function(t){return t.replace(/(^\s*)|(\s*$)/g,"")},encode:function(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")},formatParams:function(t){var e="",r=!0,n=this;return this.isObject(t)?(function t(o,i){var a=n.encode,u=n.type(o);if("array"==u)o.forEach((function(e,r){n.isObject(e)||(r=""),t(e,i+"%5B"+r+"%5D")}));else if("object"==u)for(var c in o)t(o[c],i?i+"%5B"+a(c)+"%5D":a(c));else r||(e+="&"),r=!1,e+=i+"="+a(o)}(t,""),e):t},merge:function(t,e){for(var r in e)t.hasOwnProperty(r)?this.isObject(e[r],1)&&this.isObject(t[r],1)&&this.merge(t[r],e[r]):t[r]=e[r];return t}}},,function(t,e,r){var n=function(){function t(t,e){for(var r=0;r0&&(t+=(-1===t.indexOf("?")?"?":"&")+w.join("&")),a.open(r.method,t);try{a.withCredentials=!!r.withCredentials,a.timeout=r.timeout||0,"stream"!==y&&(a.responseType=y)}catch(t){}var j=r.headers[u]||r.headers[c],O="application/x-www-form-urlencoded";for(var S in o.trim((j||"").toLowerCase())===O?e=o.formatParams(e):o.isFormData(e)||-1===["object","array"].indexOf(o.type(e))||(O="application/json;charset=utf-8",e=JSON.stringify(e)),j||b||(r.headers[u]=O),r.headers)if(S===u&&o.isFormData(e))delete r.headers[S];else try{a.setRequestHeader(S,r.headers[S])}catch(t){}function k(t,e,n){v(l.p,(function(){if(t){n&&(e.request=r);var o=t.call(l,e,Promise);e=void 0===o?e:o}d(e)||(e=Promise[0===n?"resolve":"reject"](e)),e.then((function(t){s(t)})).catch((function(t){h(t)}))}))}function E(t){t.engine=a,k(l.onerror,t,-1)}function A(t,e){this.message=t,this.status=e}a.onload=function(){try{var t=a.response||a.responseText;t&&r.parseJson&&-1!==(a.getResponseHeader(u)||"").indexOf("json")&&!o.isObject(t)&&(t=JSON.parse(t));var e=a.responseHeaders;if(!e){e={};var n=(a.getAllResponseHeaders()||"").split("\r\n");n.pop(),n.forEach((function(t){if(t){var r=t.split(":")[0];e[r]=a.getResponseHeader(r)}}))}var i=a.status,c=a.statusText,s={data:t,headers:e,status:i,statusText:c};if(o.merge(s,a._response),i>=200&&i<300||304===i)s.engine=a,s.request=r,k(l.handler,s,0);else{var f=new A(c,i);f.response=s,E(f)}}catch(f){E(new A(f.msg,a.status))}},a.onerror=function(t){E(new A(t.msg||"Network Error",0))},a.ontimeout=function(){E(new A("timeout [ "+a.timeout+"ms ]",1))},a._options=r,setTimeout((function(){a.send(b?null:e)}),0)}(n):s(n)}),(function(t){h(t)}))}))}));return h.engine=a,h}},{key:"all",value:function(t){return Promise.all(t)}},{key:"spread",value:function(t){return function(e){return t.apply(null,e)}}}]),t}();a.default=a,["get","post","put","patch","head","delete"].forEach((function(t){a.prototype[t]=function(e,r,n){return this.request(e,r,o.merge({method:t},n))}})),["lock","unlock","clear"].forEach((function(t){a.prototype[t]=function(){this.interceptors.request[t]()}})),t.exports=a}])},t.exports=r()})),o=(r=n)&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r,i="application/vnd.api+json",a={Accept:i,"Content-Type":[i,"charset=utf-8"].join(";")},u="query",c="mutation",s="socket",f="payload",l="condition",p="TS",h=["POST","PUT"],d="type",v="optional",g="enumv",y="args",b="checker",m="alias",_="__checked__",w={desc:"y"},j="No message",O="onResult",S="onError",k=Array.isArray,E="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},A="object"==typeof E&&E&&E.Object===Object&&E,T="object"==typeof self&&self&&self.Object===Object&&self,x=A||T||Function("return this")(),P=x.Symbol,q=Object.prototype,C=q.hasOwnProperty,$=q.toString,z=P?P.toStringTag:void 0;var N=Object.prototype.toString;var R="[object Null]",M="[object Undefined]",F=P?P.toStringTag:void 0;function J(t){return null==t?void 0===t?M:R:F&&F in Object(t)?function(t){var e=C.call(t,z),r=t[z];try{t[z]=void 0;var n=!0}catch(t){}var o=$.call(t);return n&&(e?t[z]=r:delete t[z]),o}(t):function(t){return N.call(t)}(t)}function I(t,e){return function(r){return t(e(r))}}var U=I(Object.getPrototypeOf,Object);function D(t){return null!=t&&"object"==typeof t}var H="[object Object]",L=Function.prototype,B=Object.prototype,K=L.toString,G=B.hasOwnProperty,V=K.call(Object);function W(t){if(!D(t)||J(t)!=H)return!1;var e=U(t);if(null===e)return!0;var r=G.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&K.call(r)==V}var Y=function(t){return k(t)?t:[t]},Q=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},X=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},Z=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),rt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),nt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),it=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),at=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),ut=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),ct=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),st=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),ft=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),lt=Object.freeze({__proto__:null,Jsonql406Error:Z,Jsonql500Error:tt,JsonqlAuthorisationError:et,JsonqlContractAuthError:rt,JsonqlResolverAppError:nt,JsonqlResolverNotFoundError:ot,JsonqlEnumError:it,JsonqlTypeError:at,JsonqlCheckerError:ut,JsonqlValidationError:ct,JsonqlError:st,JsonqlServerError:ft}),pt=st,ht=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function dt(t){if(ht(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||j,a=e.detail||e;if(o&<[o])throw new lt[r](i,a);throw new pt(i,a)}return t}function vt(t){if(Array.isArray(t))throw new ct("",t);var e=t.message||j,r=t.detail||t;switch(!0){case t instanceof Z:throw new Z(e,r);case t instanceof tt:throw new tt(e,r);case t instanceof et:throw new et(e,r);case t instanceof rt:throw new rt(e,r);case t instanceof nt:throw new nt(e,r);case t instanceof ot:throw new ot(e,r);case t instanceof it:throw new it(e,r);case t instanceof at:throw new at(e,r);case t instanceof ut:throw new ut(e,r);case t instanceof ct:throw new ct(e,r);case t instanceof ft:throw new ft(e,r);default:throw new st(e,r)}}function gt(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&kt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var Ut=function(t){return!!k(t)||null!=t&&""!==It(t)},Dt="[object Number]";function Ht(t){return function(t){return"number"==typeof t||D(t)&&J(t)==Dt}(t)&&t!=+t}var Lt="[object String]";function Bt(t){return"string"==typeof t||!k(t)&&D(t)&&J(t)==Lt}var Kt=function(t){return!Bt(t)&&!Ht(parseFloat(t))},Gt=function(t){return""!==It(t)&&Bt(t)},Vt=function(t){return null!=t&&"boolean"==typeof t},Wt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==It(t)&&(!1===e||!0===e&&null!==t)},Yt=d,Qt=v,Xt=g,Zt=y,te=b,ee=m,re="continue",ne=function(t){switch(t){case"number":return Kt;case"string":return Gt;case"boolean":return Vt;default:return Wt}},oe=function(t,e){return void 0===e&&(e=""),!!k(t)&&(""===e||""===It(e)||!(t.filter((function(t){return!ne(e)(t)})).length>0))},ie=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ae=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ne(e)(t)})).length)})).length:e.length>e.filter((function(t){return!oe(r,t)})).length};var ue,ce=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[ue?a:++n];if(!1===e(o[u],u,o))break}return t};var se="[object Arguments]";function fe(t){return D(t)&&J(t)==se}var le=Object.prototype,pe=le.hasOwnProperty,he=le.propertyIsEnumerable,de=fe(function(){return arguments}())?fe:function(t){return D(t)&&pe.call(t,"callee")&&!he.call(t,"callee")};var ve="object"==typeof exports&&exports&&!exports.nodeType&&exports,ge=ve&&"object"==typeof module&&module&&!module.nodeType&&module,ye=ge&&ge.exports===ve?x.Buffer:void 0,be=(ye?ye.isBuffer:void 0)||function(){return!1},me=9007199254740991,_e=/^(?:0|[1-9]\d*)$/;function we(t,e){var r=typeof t;return!!(e=null==e?me:e)&&("number"==r||"symbol"!=r&&_e.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=je}var Se={};Se["[object Float32Array]"]=Se["[object Float64Array]"]=Se["[object Int8Array]"]=Se["[object Int16Array]"]=Se["[object Int32Array]"]=Se["[object Uint8Array]"]=Se["[object Uint8ClampedArray]"]=Se["[object Uint16Array]"]=Se["[object Uint32Array]"]=!0,Se["[object Arguments]"]=Se["[object Array]"]=Se["[object ArrayBuffer]"]=Se["[object Boolean]"]=Se["[object DataView]"]=Se["[object Date]"]=Se["[object Error]"]=Se["[object Function]"]=Se["[object Map]"]=Se["[object Number]"]=Se["[object Object]"]=Se["[object RegExp]"]=Se["[object Set]"]=Se["[object String]"]=Se["[object WeakMap]"]=!1;var ke,Ee="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ae=Ee&&"object"==typeof module&&module&&!module.nodeType&&module,Te=Ae&&Ae.exports===Ee&&A.process,xe=function(){try{var t=Ae&&Ae.require&&Ae.require("util").types;return t||Te&&Te.binding&&Te.binding("util")}catch(t){}}(),Pe=xe&&xe.isTypedArray,qe=Pe?(ke=Pe,function(t){return ke(t)}):function(t){return D(t)&&Oe(t.length)&&!!Se[J(t)]},Ce=Object.prototype.hasOwnProperty;function $e(t,e){var r=k(t),n=!r&&de(t),o=!r&&!n&&be(t),i=!r&&!n&&!o&&qe(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},Ye.prototype.set=function(t,e){var r=this.__data__,n=Ve(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var Qe,Xe=x["__core-js_shared__"],Ze=(Qe=/[^.]+$/.exec(Xe&&Xe.keys&&Xe.keys.IE_PROTO||""))?"Symbol(src)_1."+Qe:"";var tr=Function.prototype.toString;function er(t){if(null!=t){try{return tr.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var rr=/^\[object .+?Constructor\]$/,nr=Function.prototype,or=Object.prototype,ir=nr.toString,ar=or.hasOwnProperty,ur=RegExp("^"+ir.call(ar).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function cr(t){return!(!Fe(t)||function(t){return!!Ze&&Ze in t}(t))&&(He(t)?ur:rr).test(er(t))}function sr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return cr(r)?r:void 0}var fr=sr(x,"Map"),lr=sr(Object,"create");var pr="__lodash_hash_undefined__",hr=Object.prototype.hasOwnProperty;var dr=Object.prototype.hasOwnProperty;var vr="__lodash_hash_undefined__";function gr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&kr?new jr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=ie(t))?!ae({arg:r},e):!ne(t)(r))})).length)})).length}return!1},Kn=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Bn,null,a);case"array"===t:return!oe(e.arg);case!1!==(r=ie(t)):return!ae(e,r);default:return!ne(t)(e.arg)}},Gn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Vn=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!oe(e))throw new st("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!oe(t))throw new st("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Gn(t,a):t,index:r,param:a,optional:i}}));default:throw new st("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Ut(e)&&!(r.type.length>r.type.filter((function(e){return Kn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Kn(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Wn=function(){try{var t=sr(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function Yn(t,e,r){"__proto__"==e&&Wn?Wn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function Qn(t,e,r){(void 0===r||Ge(t[e],r))&&(void 0!==r||e in t)||Yn(t,e,r)}var Xn="object"==typeof exports&&exports&&!exports.nodeType&&exports,Zn=Xn&&"object"==typeof module&&module&&!module.nodeType&&module,to=Zn&&Zn.exports===Xn?x.Buffer:void 0,eo=to?to.allocUnsafe:void 0;function ro(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new Ar(n).set(new Ar(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var no=Object.create,oo=function(){function t(){}return function(e){if(!Fe(e))return{};if(no)return no(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function io(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ao=Object.prototype.hasOwnProperty;function uo(t,e,r){var n=t[e];ao.call(t,e)&&Ge(n,r)&&(void 0!==r||e in t)||Yn(t,e,r)}var co=Object.prototype.hasOwnProperty;function so(t){if(!Fe(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Ne(t),r=[];for(var n in t)("constructor"!=n||!e&&co.call(t,n))&&r.push(n);return r}function fo(t){return Le(t)?$e(t,!0):so(t)}function lo(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=bo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(yo);function jo(t,e){return wo(function(t,e,r){return e=go(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=go(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Oo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!Fe(r))return!1;var n=typeof e;return!!("number"==n?Le(r)&&we(e,r.length):"string"==n&&e in r)&&Ge(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,Y(t))}),Reflect.apply(t,null,r))}};function Vo(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function Wo(t,e,r,n){void 0===n&&(n=!1);var o=Vo(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var Yo=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return Lo(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch(vt)}},Qo=function(t,e,r,n,o){var i={},a=function(t){i=Wo(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return Lo(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch(vt)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},Xo=function(t,e,r,n,o){var i={},a=function(t){i=Wo(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return Lo(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch(vt)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Zo=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Yo(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Yo(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var ti=function(t,e){return function(r){for(var n=[],o=arguments.length-1;o-- >0;)n[o]=arguments[o+1];return new Promise((function(o,i){t.$only(X(e,r,O),o),t.$only(X(e,r,S),i),t.$trigger(e,{resolverName:r,args:n})}))}},ei=function(t,e,r){var n=t.$queues,o=r.debugOn;o&&console.info("(validateRegisteredEvents)","storedEvt",n),n.forEach((function(t){var r=t[0],n=t[1].resolverName;if(o&&console.info("(validateRegisteredEvents)",r,n),!e[r][n])throw new Error(r+"."+n+" not existed in contract!")}))};function ri(t,e,r,n){var o=function(t,e,r,n){return Go(Qo,Xo,Zo)({},t,e,r,n)}(t,e,r,n);ei(e,n,r);var i=function(t){e.$only(t,(function(r){var n=r.resolverName,i=r.args;o[t][n]?Reflect.apply(o[t][n],null,i).then((function(r){e.$trigger(X(t,n,O),r)})).catch((function(r){e.$trigger(X(t,n,S),r)})):console.error(n+" is not defined in the contract!")}))};for(var a in o)i(a);setTimeout((function(){e.$suspend=!1}),1)}var ni=function(t,e,r,n){n.$suspend=!0,r.then((function(r){ri(t,n,e,r)}));var o={query:ti(n,"query"),mutation:ti(n,"mutation"),auth:ti(n,"auth"),getToken:function(){return t.rawAuthToken}};return e.exposeContract&&(o.getContract=function(){return t.get()}),e.enableAuth&&(o.userdata=function(){return t.userdata}),o.version="1.5.1",o};function oi(t){return!!function(t){return W(t)&&(Q(t,u)||Q(t,c)||Q(t,s))}(t)&&t}function ii(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var ai=function(t,e){return void 0===e&&(e={}),oi(e)?Promise.resolve(e):t.getContract()},ui="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function ci(t){this.message=t}ci.prototype=new Error,ci.prototype.name="InvalidCharacterError";var si="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new ci("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=ui.indexOf(n);return a};var fi=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(si(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return si(e)}};function li(t){this.message=t}li.prototype=new Error,li.prototype.name="InvalidTokenError";var pi=function(t,e){if("string"!=typeof t)throw new li("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(fi(t.split(".")[r]))}catch(t){throw new li("Invalid token specified: "+t.message)}},hi=li;pi.InvalidTokenError=hi;var di,vi,gi,yi,bi,mi,_i,wi,ji,Oi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Si(t){if(Gt(t))return function(t){var e=t.iat||Oi(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new st("Token has expired on "+r,t)}return t}(pi(t));throw new st("Token must be a string!")}Bo("HS256",["string"]),Bo(!1,["boolean","number","string"],((di={})[m]="exp",di[v]=!0,di)),Bo(!1,["boolean","number","string"],((vi={})[m]="nbf",vi[v]=!0,vi)),Bo(!1,["boolean","string"],((gi={})[m]="iss",gi[v]=!0,gi)),Bo(!1,["boolean","string"],((yi={})[m]="sub",yi[v]=!0,yi)),Bo(!1,["boolean","string"],((bi={})[m]="iss",bi[v]=!0,bi)),Bo(!1,["boolean"],((mi={})[v]=!0,mi)),Bo(!1,["boolean","string"],((_i={})[v]=!0,_i)),Bo(!1,["boolean","string"],((wi={})[v]=!0,wi)),Bo(!1,["boolean"],((ji={})[v]=!0,ji));var ki=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},Ei=Object.assign?Object.assign:function(t,e,r,n){for(var o=arguments,i=1;i=0;e--){var r=Vi().key(e);t(Wi(r),r)}},remove:function(t){return Vi().removeItem(t)},clearAll:function(){return Vi().clear()}};function Vi(){return Ki.localStorage}function Wi(t){return Vi().getItem(t)}var Yi=Pi.trim,Qi={name:"cookieStorage",read:function(t){if(!t||!ea(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Xi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Xi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Zi,remove:ta,clearAll:function(){Zi((function(t,e){ta(e)}))}},Xi=Pi.Global.document;function Zi(t){for(var e=Xi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Yi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function ta(t){t&&ea(t)&&(Xi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function ea(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Xi.cookie)}var ra=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var na=Pi.bind,oa=Pi.each,ia=Pi.create,aa=Pi.slice,ua=function(){var t=ia(ca,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,na(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,na(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),oa(r,(function(e,r){t.fire(r,void 0,e)}))}}};var ca={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,na(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=aa(arguments,1);oa(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},sa=e((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),fa=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=sa.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=sa.compress(this._serialize(r));t(e,n)}}};var la=[Gi,Qi],pa=[ra,ua,fa],ha=Hi.createStore(la,pa),da=Pi.Global;function va(){return da.sessionStorage}function ga(t){return va().getItem(t)}var ya=[{name:"sessionStorage",read:ga,write:function(t,e){return va().setItem(t,e)},each:function(t){for(var e=va().length-1;e>=0;e--){var r=va().key(e);t(ga(r),r)}},remove:function(t){return va().removeItem(t)},clearAll:function(){return va().clear()}},Qi],ba=[ra,fa],ma=Hi.createStore(ya,ba),_a=ha,wa=ma,ja=function(t){var e;return(e={}).args=t,e};function Oa(t,e){var r;return(r={})[t]=e,r[p]=[ki()],r}var Sa=function(t){return Q(t,"data")&&!Q(t,"error")?t.data:t},ka=function(t){this.opts=t,this.instanceKey=ii(this.opts.hostname)+"",this.localStore=_a,this.sessionStore=wa},Ea={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};ka.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?So({},o,e):e,r))},ka.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},ka.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},ka.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},Ea.lset.set=function(t){return this.__setMethod("localStore",t)},Ea.lget.get=function(){return this.__getMethod("localStore")},ka.prototype.ldel=function(t){return this.__delMethod("localStore",t)},ka.prototype.lclear=function(){return this.__clearMethod("localStore")},Ea.sset.set=function(t){return this.__setMethod("sessionStore",t)},Ea.sget.get=function(){return this.__getMethod("sessionStore")},ka.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},ka.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(ka.prototype,Ea);var Aa=h[0],Ta=h[1],xa=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];!0===this.opts.debugOn&&Reflect.apply(console.info,console,t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Si)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(Ho(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new ct("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&Ho(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!oi(t))throw new ct("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=oi(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={headers:{configurable:!0}};return r.headers.set=function(t){this.extraHeader=t},e.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=So({},{_cb:ki()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=So({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=So({},{method:Aa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},e.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},e.prototype.processJsonp=function(t){return Sa(t)},e.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=Do(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):Sa(o)}),(function(t){throw e.cleanUp(),console.error(t),new ft("Server side error",t)}))},e.prototype.getHeaders=function(){return this.opts.enableAuth?So({},a,this.getAuthHeader(),this.extraHeader):So({},a,this.extraHeader)},e.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},e.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=So({},this.extraParams,w)),this.request({},{method:"GET"},this.contractHeader).then(dt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(t){throw console.error("getRemoteContract err",t),new ft("getRemoteContract",t)}))},e.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Bt(t)&&k(e)){var n=ja(e);return!0===r?n:Oa(t,n)}throw new ct("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(dt)},e.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[f]=e,o[l]=r,!0===n)return o;if(Bt(t))return Oa(t,o);throw new ct("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:Ta}).then(dt)},Object.defineProperties(e.prototype,r),e}(ka)))),Pa={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:i,BEARER:"Bearer",AUTH_HEADER:"Authorization"},qa={hostname:Bo(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:Bo("jsonql",["string"]),loginHandlerName:Bo("login",["string"]),logoutHandlerName:Bo("logout",["string"]),enableJsonp:Bo(!1,["boolean"]),enableAuth:Bo(!1,["boolean"]),useJwt:Bo(!0,["boolean"]),persistToken:Bo(!1,["boolean","number"]),useLocalstorage:Bo(!0,["boolean"]),storageKey:Bo("jsonqlstore",["string"]),authKey:Bo("jsonqlauthkey",["string"]),contractExpired:Bo(0,["number"]),keepContract:Bo(!0,["boolean"]),exposeContract:Bo(!1,["boolean"]),exposeStore:Bo(!1,["boolean"]),showContractDesc:Bo(!1,["boolean"]),contractKey:Bo(!1,["boolean"]),contractKeyName:Bo("X-JSONQL-CV-KEY",["string"]),enableTimeout:Bo(!1,["boolean"]),timeout:Bo(5e3,["number"]),returnInstance:Bo(!1,["boolean"]),allowReturnRawToken:Bo(!1,["boolean"]),debugOn:Bo(!1,["boolean"])};function Ca(t){return Vo(t,_)?t:function(t){return Ko(t,qa,Pa)}(t)}var $a=new WeakMap,za=new WeakMap,Na=function(){this.__suspend__=null,this.queueStore=new Set},Ra={$suspend:{configurable:!0},$queues:{configurable:!0}};Ra.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Na.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ra.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Na.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Na.prototype,Ra);var Ma=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){$a.set(this,t)},r.normalStore.get=function(){return $a.get(this)},r.lazyStore.set=function(t){za.set(this,t)},r.lazyStore.get=function(){return za.get(this)},e.prototype.hashFnToKey=function(t){return ii(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Na));function Fa(t,e){void 0===e&&(e={});var r,n=e.contract,o=Ca(e),i=new xa(t,o),a=ai(i,n),u=(r=o.debugOn,new Ma({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),c=ni(i,o,a,u);return c.eventEmitter=u,c}return function(t){return void 0===t&&(t={}),Fa(new o,t)}})); +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.jsonqlClientStatic = factory()); +}(this, (function () { 'use strict'; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var fly = createCommonjsModule(function (module, exports) { + (function webpackUniversalModuleDefinition(root, factory) { + { module.exports = factory(); } + })(commonjsGlobal, function() { + return /******/ (function(modules) { // webpackBootstrap + /******/ // The module cache + /******/ var installedModules = {}; + /******/ + /******/ // The require function + /******/ function __webpack_require__(moduleId) { + /******/ + /******/ // Check if module is in cache + /******/ if(installedModules[moduleId]) { + /******/ return installedModules[moduleId].exports; + /******/ } + /******/ // Create a new module (and put it into the cache) + /******/ var module = installedModules[moduleId] = { + /******/ i: moduleId, + /******/ l: false, + /******/ exports: {} + /******/ }; + /******/ + /******/ // Execute the module function + /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + /******/ + /******/ // Flag the module as loaded + /******/ module.l = true; + /******/ + /******/ // Return the exports of the module + /******/ return module.exports; + /******/ } + /******/ + /******/ + /******/ // expose the modules object (__webpack_modules__) + /******/ __webpack_require__.m = modules; + /******/ + /******/ // expose the module cache + /******/ __webpack_require__.c = installedModules; + /******/ + /******/ // identity function for calling harmony imports with the correct context + /******/ __webpack_require__.i = function(value) { return value; }; + /******/ + /******/ // define getter function for harmony exports + /******/ __webpack_require__.d = function(exports, name, getter) { + /******/ if(!__webpack_require__.o(exports, name)) { + /******/ Object.defineProperty(exports, name, { + /******/ configurable: false, + /******/ enumerable: true, + /******/ get: getter + /******/ }); + /******/ } + /******/ }; + /******/ + /******/ // getDefaultExport function for compatibility with non-harmony modules + /******/ __webpack_require__.n = function(module) { + /******/ var getter = module && module.__esModule ? + /******/ function getDefault() { return module['default']; } : + /******/ function getModuleExports() { return module; }; + /******/ __webpack_require__.d(getter, 'a', getter); + /******/ return getter; + /******/ }; + /******/ + /******/ // Object.prototype.hasOwnProperty.call + /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; + /******/ + /******/ // __webpack_public_path__ + /******/ __webpack_require__.p = ""; + /******/ + /******/ // Load entry module and return exports + /******/ return __webpack_require__(__webpack_require__.s = 2); + /******/ }) + /************************************************************************/ + /******/ ([ + /* 0 */ + /***/ (function(module, exports, __webpack_require__) { + + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + module.exports = { + type: function type(ob) { + return Object.prototype.toString.call(ob).slice(8, -1).toLowerCase(); + }, + isObject: function isObject(ob, real) { + if (real) { + return this.type(ob) === "object"; + } else { + return ob && (typeof ob === 'undefined' ? 'undefined' : _typeof(ob)) === 'object'; + } + }, + isFormData: function isFormData(val) { + return typeof FormData !== 'undefined' && val instanceof FormData; + }, + trim: function trim(str) { + return str.replace(/(^\s*)|(\s*$)/g, ''); + }, + encode: function encode(val) { + return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); + }, + formatParams: function formatParams(data) { + var str = ""; + var first = true; + var that = this; + if (!this.isObject(data)) { + return data; + } + + function _encode(sub, path) { + var encode = that.encode; + var type = that.type(sub); + if (type == "array") { + sub.forEach(function (e, i) { + if (!that.isObject(e)) { i = ""; } + _encode(e, path + ('%5B' + i + '%5D')); + }); + } else if (type == "object") { + for (var key in sub) { + if (path) { + _encode(sub[key], path + "%5B" + encode(key) + "%5D"); + } else { + _encode(sub[key], encode(key)); + } + } + } else { + if (!first) { + str += "&"; + } + first = false; + str += path + "=" + encode(sub); + } + } + + _encode(data, ""); + return str; + }, + + // Do not overwrite existing attributes + merge: function merge(a, b) { + for (var key in b) { + if (!a.hasOwnProperty(key)) { + a[key] = b[key]; + } else if (this.isObject(b[key], 1) && this.isObject(a[key], 1)) { + this.merge(a[key], b[key]); + } + } + return a; + } + }; + + /***/ }), + /* 1 */, + /* 2 */ + /***/ (function(module, exports, __webpack_require__) { + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var utils = __webpack_require__(0); + var isBrowser = typeof document !== "undefined"; + + var Fly = function () { + function Fly(engine) { + _classCallCheck(this, Fly); + + this.engine = engine || XMLHttpRequest; + + this.default = this; //For typeScript + + /** + * Add lock/unlock API for interceptor. + * + * Once an request/response interceptor is locked, the incoming request/response + * will be added to a queue before they enter the interceptor, they will not be + * continued until the interceptor is unlocked. + * + * @param [interceptor] either is interceptors.request or interceptors.response + */ + function wrap(interceptor) { + var resolve = void 0; + var reject = void 0; + + function _clear() { + interceptor.p = resolve = reject = null; + } + + utils.merge(interceptor, { + lock: function lock() { + if (!resolve) { + interceptor.p = new Promise(function (_resolve, _reject) { + resolve = _resolve; + reject = _reject; + }); + } + }, + unlock: function unlock() { + if (resolve) { + resolve(); + _clear(); + } + }, + clear: function clear() { + if (reject) { + reject("cancel"); + _clear(); + } + } + }); + } + + var interceptors = this.interceptors = { + response: { + use: function use(handler, onerror) { + this.handler = handler; + this.onerror = onerror; + } + }, + request: { + use: function use(handler) { + this.handler = handler; + } + } + }; + + var irq = interceptors.request; + var irp = interceptors.response; + wrap(irp); + wrap(irq); + + this.config = { + method: "GET", + baseURL: "", + headers: {}, + timeout: 0, + params: {}, // Default Url params + parseJson: true, // Convert response data to JSON object automatically. + withCredentials: false + }; + } + + _createClass(Fly, [{ + key: "request", + value: function request(url, data, options) { + var _this = this; + + var engine = new this.engine(); + var contentType = "Content-Type"; + var contentTypeLowerCase = contentType.toLowerCase(); + var interceptors = this.interceptors; + var requestInterceptor = interceptors.request; + var responseInterceptor = interceptors.response; + var requestInterceptorHandler = requestInterceptor.handler; + var promise = new Promise(function (resolve, reject) { + if (utils.isObject(url)) { + options = url; + url = options.url; + } + options = options || {}; + options.headers = options.headers || {}; + + function isPromise(p) { + // some polyfill implementation of Promise may be not standard, + // so, we test by duck-typing + return p && p.then && p.catch; + } + + /** + * If the request/response interceptor has been locked, + * the new request/response will enter a queue. otherwise, it will be performed directly. + * @param [promise] if the promise exist, means the interceptor is locked. + * @param [callback] + */ + function enqueueIfLocked(promise, callback) { + if (promise) { + promise.then(function () { + callback(); + }); + } else { + callback(); + } + } + + // make the http request + function makeRequest(options) { + data = options.body; + // Normalize the request url + url = utils.trim(options.url); + var baseUrl = utils.trim(options.baseURL || ""); + if (!url && isBrowser && !baseUrl) { url = location.href; } + if (url.indexOf("http") !== 0) { + var isAbsolute = url[0] === "/"; + if (!baseUrl && isBrowser) { + var arr = location.pathname.split("/"); + arr.pop(); + baseUrl = location.protocol + "//" + location.host + (isAbsolute ? "" : arr.join("/")); + } + if (baseUrl[baseUrl.length - 1] !== "/") { + baseUrl += "/"; + } + url = baseUrl + (isAbsolute ? url.substr(1) : url); + if (isBrowser) { + + // Normalize the url which contains the ".." or ".", such as + // "http://xx.com/aa/bb/../../xx" to "http://xx.com/xx" . + var t = document.createElement("a"); + t.href = url; + url = t.href; + } + } + + var responseType = utils.trim(options.responseType || ""); + var needQuery = ["GET", "HEAD", "DELETE", "OPTION"].indexOf(options.method) !== -1; + var dataType = utils.type(data); + var params = options.params || {}; + + // merge url params when the method is "GET" (data is object) + if (needQuery && dataType === "object") { + params = utils.merge(data, params); + } + // encode params to String + params = utils.formatParams(params); + + // save url params + var _params = []; + if (params) { + _params.push(params); + } + // Add data to url params when the method is "GET" (data is String) + if (needQuery && data && dataType === "string") { + _params.push(data); + } + + // make the final url + if (_params.length > 0) { + url += (url.indexOf("?") === -1 ? "?" : "&") + _params.join("&"); + } + + engine.open(options.method, url); + + // try catch for ie >=9 + try { + engine.withCredentials = !!options.withCredentials; + engine.timeout = options.timeout || 0; + if (responseType !== "stream") { + engine.responseType = responseType; + } + } catch (e) {} + + var customContentType = options.headers[contentType] || options.headers[contentTypeLowerCase]; + + // default content type + var _contentType = "application/x-www-form-urlencoded"; + // If the request data is json object, transforming it to json string, + // and set request content-type to "json". In browser, the data will + // be sent as RequestBody instead of FormData + if (utils.trim((customContentType || "").toLowerCase()) === _contentType) { + data = utils.formatParams(data); + } else if (!utils.isFormData(data) && ["object", "array"].indexOf(utils.type(data)) !== -1) { + _contentType = 'application/json;charset=utf-8'; + data = JSON.stringify(data); + } + //If user doesn't set content-type, set default. + if (!(customContentType || needQuery)) { + options.headers[contentType] = _contentType; + } + + for (var k in options.headers) { + if (k === contentType && utils.isFormData(data)) { + // Delete the content-type, Let the browser set it + delete options.headers[k]; + } else { + try { + // In browser environment, some header fields are readonly, + // write will cause the exception . + engine.setRequestHeader(k, options.headers[k]); + } catch (e) {} + } + } + + function onresult(handler, data, type) { + enqueueIfLocked(responseInterceptor.p, function () { + if (handler) { + //如果失败,添加请求信息 + if (type) { + data.request = options; + } + var ret = handler.call(responseInterceptor, data, Promise); + data = ret === undefined ? data : ret; + } + if (!isPromise(data)) { + data = Promise[type === 0 ? "resolve" : "reject"](data); + } + data.then(function (d) { + resolve(d); + }).catch(function (e) { + reject(e); + }); + }); + } + + function onerror(e) { + e.engine = engine; + onresult(responseInterceptor.onerror, e, -1); + } + + function Err(msg, status) { + this.message = msg; + this.status = status; + } + + engine.onload = function () { + try { + // The xhr of IE9 has not response field + var response = engine.response || engine.responseText; + if (response && options.parseJson && (engine.getResponseHeader(contentType) || "").indexOf("json") !== -1 + // Some third engine implementation may transform the response text to json object automatically, + // so we should test the type of response before transforming it + && !utils.isObject(response)) { + response = JSON.parse(response); + } + + var headers = engine.responseHeaders; + // In browser + if (!headers) { + headers = {}; + var items = (engine.getAllResponseHeaders() || "").split("\r\n"); + items.pop(); + items.forEach(function (e) { + if (!e) { return; } + var key = e.split(":")[0]; + headers[key] = engine.getResponseHeader(key); + }); + } + var status = engine.status; + var statusText = engine.statusText; + var _data = { data: response, headers: headers, status: status, statusText: statusText }; + // The _response filed of engine is set in adapter which be called in engine-wrapper.js + utils.merge(_data, engine._response); + if (status >= 200 && status < 300 || status === 304) { + _data.engine = engine; + _data.request = options; + onresult(responseInterceptor.handler, _data, 0); + } else { + var e = new Err(statusText, status); + e.response = _data; + onerror(e); + } + } catch (e) { + onerror(new Err(e.msg, engine.status)); + } + }; + + engine.onerror = function (e) { + onerror(new Err(e.msg || "Network Error", 0)); + }; + + engine.ontimeout = function () { + onerror(new Err("timeout [ " + engine.timeout + "ms ]", 1)); + }; + engine._options = options; + setTimeout(function () { + engine.send(needQuery ? null : data); + }, 0); + } + + enqueueIfLocked(requestInterceptor.p, function () { + utils.merge(options, JSON.parse(JSON.stringify(_this.config))); + var headers = options.headers; + headers[contentType] = headers[contentType] || headers[contentTypeLowerCase] || ""; + delete headers[contentTypeLowerCase]; + options.body = data || options.body; + url = utils.trim(url || ""); + options.method = options.method.toUpperCase(); + options.url = url; + var ret = options; + if (requestInterceptorHandler) { + ret = requestInterceptorHandler.call(requestInterceptor, options, Promise) || options; + } + if (!isPromise(ret)) { + ret = Promise.resolve(ret); + } + ret.then(function (d) { + //if options continue + if (d === options) { + makeRequest(d); + } else { + resolve(d); + } + }, function (err) { + reject(err); + }); + }); + }); + promise.engine = engine; + return promise; + } + }, { + key: "all", + value: function all(promises) { + return Promise.all(promises); + } + }, { + key: "spread", + value: function spread(callback) { + return function (arr) { + return callback.apply(null, arr); + }; + } + }]); + + return Fly; + }(); + + //For typeScript + + + Fly.default = Fly; + + ["get", "post", "put", "patch", "head", "delete"].forEach(function (e) { + Fly.prototype[e] = function (url, data, option) { + return this.request(url, data, utils.merge({ method: e }, option)); + }; + }); + ["lock", "unlock", "clear"].forEach(function (e) { + Fly.prototype[e] = function () { + this.interceptors.request[e](); + }; + }); + module.exports = Fly; + + /***/ }) + /******/ ]); + }); + }); + + var Fly = unwrapExports(fly); + + // the core stuff to id if it's calling with jsonql + var DATA_KEY = 'data'; + var ERROR_KEY = 'error'; + + var JSONQL_PATH = 'jsonql'; + // according to the json query spec + var CONTENT_TYPE = 'application/vnd.api+json'; + var CHARSET = 'charset=utf-8'; + var DEFAULT_HEADER = { + 'Accept': CONTENT_TYPE, + 'Content-Type': [ CONTENT_TYPE, CHARSET ].join(';') + }; + + // export const INDEX = 'index'; use INDEX_KEY instead + var DEFAULT_TYPE = 'any'; + + // @TODO remove this is not in use + // export const CLIENT_CONFIG_FILE = '.clients.json'; + // export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js'; + // type of resolvers + var QUERY_NAME = 'query'; + var MUTATION_NAME = 'mutation'; + var SOCKET_NAME = 'socket'; + // for calling the mutation + var PAYLOAD_PARAM_NAME = 'payload'; // @TODO shortern them + var CONDITION_PARAM_NAME = 'condition'; + var QUERY_ARG_NAME = 'args'; + var TIMESTAMP_PARAM_NAME = 'TS'; + // new jsonp + var JSONP_CALLBACK_NAME = 'jsonqlJsonpCallback'; + + // methods allow + var API_REQUEST_METHODS = ['POST', 'PUT']; + // for contract-cli + var KEY_WORD = 'continue'; + + var TYPE_KEY = 'type'; + var OPTIONAL_KEY = 'optional'; + var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word + var ARGS_KEY = 'args'; + var CHECKER_KEY = 'checker'; + var ALIAS_KEY = 'alias'; + var CHECKED_KEY = '__checked__'; + var LOGIN_NAME = 'login'; + var ISSUER_NAME = LOGIN_NAME; // legacy issue need to replace them later + var LOGOUT_NAME = 'logout'; + + var AUTH_HEADER = 'Authorization'; + var BEARER = 'Bearer'; + + // for client use @TODO need to clean this up some of them are not in use + var CREDENTIAL_STORAGE_KEY = 'jsonqlcredential'; + var CLIENT_STORAGE_KEY = 'jsonqlstore'; + var CLIENT_AUTH_KEY = 'jsonqlauthkey'; + // contract key + var CONTRACT_KEY_NAME = 'X-JSONQL-CV-KEY'; + var SHOW_CONTRACT_DESC_PARAM = {desc: 'y'}; + + var OR_SEPERATOR = '|'; + + var STRING_TYPE = 'string'; + var BOOLEAN_TYPE = 'boolean'; + var ARRAY_TYPE = 'array'; + var OBJECT_TYPE = 'object'; + + var NUMBER_TYPE = 'number'; + var ARRAY_TYPE_LFT = 'array.<'; + var ARRAY_TYPE_RGT = '>'; + + var NO_ERROR_MSG$1 = 'No message'; + var NO_STATUS_CODE = -1; + var ON_RESULT_PROP_NAME = 'onResult'; + var ON_ERROR_PROP_NAME = 'onError'; + var HSA_ALGO = 'HS256'; + + /** + * 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; + + 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$1 = root.Symbol; + + /** 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$1 ? Symbol$1.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$1 ? Symbol$1.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); + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** Built-in value references. */ + var getPrototype = overArg(Object.getPrototypeOf, Object); + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @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 objectTag = '[object Object]'; + + /** Used for built-in method references. */ + var funcProto = Function.prototype, + objectProto$2 = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty$1 = objectProto$2.hasOwnProperty; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty$1.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * 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; + } + + /** `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$1 ? Symbol$1.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(''); + } + + // bunch of generic helpers + + /** + * DIY in Array + * @param {array} arr to check from + * @param {*} value to check against + * @return {boolean} true on found + */ + var inArray = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; + + // quick and dirty to turn non array to array + var toArray = function (arg) { return isArray(arg) ? arg : [arg]; }; + + /** + * @param {object} obj for search + * @param {string} key target + * @return {boolean} true on success + */ + var isObjectHasKey = function(obj, key) { + try { + var keys = Object.keys(obj); + return inArray(keys, key) + } catch(e) { + // @BUG when the obj is not an OBJECT we got some weird output + return false; + /* + console.info('obj', obj) + console.error(e) + throw new Error(e) + */ + } + }; + + /** + * create a event name + * @param {string[]} args + * @return {string} event name for use + */ + var createEvt = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return args.join('_'); + }; + + // just a simple util method to return the error based on the status code + /** + * @param {number} statusCode to check + * @param {boolean} contract if this is a contract call or not + * @return {string} the error name + */ + function getErrorByStatus(statusCode, contract) { + if ( contract === void 0 ) contract = false; + + switch (statusCode) { + case 401: + return contract ? 'JsonqlContractAuthError' : 'JsonqlAuthorisationError'; + case 403: + return 'JsonqlForbiddenError'; + case 404: + return 'JsonqlResolverNotFoundError'; + case 406: + return 'Jsonql406Error'; + case 500: + return 'Jsonql500Error'; + default: + return 'JsonqlError'; + } + } + + /** + * This is a custom error to throw when server throw a 406 + * 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 Jsonql406Error = /*@__PURE__*/(function (Error) { + function Jsonql406Error() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + this.message = args[0]; + this.detail = args[1]; + // We can't access the static name from an instance + // but we can do it like this + this.className = Jsonql406Error.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Jsonql406Error); + } + } + + if ( Error ) Jsonql406Error.__proto__ = Error; + Jsonql406Error.prototype = Object.create( Error && Error.prototype ); + Jsonql406Error.prototype.constructor = Jsonql406Error; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 406; + }; + + staticAccessors.name.get = function () { + return 'Jsonql406Error'; + }; + + Object.defineProperties( Jsonql406Error, staticAccessors ); + + return Jsonql406Error; + }(Error)); + + /** + * This is a custom error to throw when server throw a 500 + * 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 Jsonql500Error = /*@__PURE__*/(function (Error) { + function Jsonql500Error() { + 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 = Jsonql500Error.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Jsonql500Error); + } + } + + if ( Error ) Jsonql500Error.__proto__ = Error; + Jsonql500Error.prototype = Object.create( Error && Error.prototype ); + Jsonql500Error.prototype.constructor = Jsonql500Error; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 500; + }; + + staticAccessors.name.get = function () { + return 'Jsonql500Error'; + }; + + Object.defineProperties( Jsonql500Error, staticAccessors ); + + return Jsonql500Error; + }(Error)); + + /** + * This is a custom error to throw when pass credential but fail + * 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 JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { + function JsonqlAuthorisationError() { + 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 = JsonqlAuthorisationError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlAuthorisationError); + } + } + + if ( Error ) JsonqlAuthorisationError.__proto__ = Error; + JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); + JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 401; + }; + + staticAccessors.name.get = function () { + return 'JsonqlAuthorisationError'; + }; + + Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); + + return JsonqlAuthorisationError; + }(Error)); + + /** + * This is a custom error when not supply the credential and try to get contract + * 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 JsonqlContractAuthError = /*@__PURE__*/(function (Error) { + function JsonqlContractAuthError() { + 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 = JsonqlContractAuthError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlContractAuthError); + } + } + + if ( Error ) JsonqlContractAuthError.__proto__ = Error; + JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); + JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 401; + }; + + staticAccessors.name.get = function () { + return 'JsonqlContractAuthError'; + }; + + Object.defineProperties( JsonqlContractAuthError, staticAccessors ); + + return JsonqlContractAuthError; + }(Error)); + + /** + * This is a custom error to throw when the resolver throw error and capture inside the middleware + * 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 JsonqlResolverAppError = /*@__PURE__*/(function (Error) { + function JsonqlResolverAppError() { + 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 = JsonqlResolverAppError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlResolverAppError); + } + } + + if ( Error ) JsonqlResolverAppError.__proto__ = Error; + JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); + JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 500; + }; + + staticAccessors.name.get = function () { + return 'JsonqlResolverAppError'; + }; + + Object.defineProperties( JsonqlResolverAppError, staticAccessors ); + + return JsonqlResolverAppError; + }(Error)); + + /** + * This is a custom error to throw when could not find the resolver + * 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 JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { + function JsonqlResolverNotFoundError() { + 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 = JsonqlResolverNotFoundError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlResolverNotFoundError); + } + } + + if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; + JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); + JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 404; + }; + + staticAccessors.name.get = function () { + return 'JsonqlResolverNotFoundError'; + }; + + Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); + + return JsonqlResolverNotFoundError; + }(Error)); + + // this get throw from within the checkOptions when run through the enum failed + var JsonqlEnumError = /*@__PURE__*/(function (Error) { + function JsonqlEnumError() { + 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 = JsonqlEnumError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlEnumError); + } + } + + if ( Error ) JsonqlEnumError.__proto__ = Error; + JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); + JsonqlEnumError.prototype.constructor = JsonqlEnumError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlEnumError'; + }; + + Object.defineProperties( JsonqlEnumError, staticAccessors ); + + return JsonqlEnumError; + }(Error)); + + // this will throw from inside the checkOptions + var JsonqlTypeError = /*@__PURE__*/(function (Error) { + function JsonqlTypeError() { + 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 = JsonqlTypeError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlTypeError); + } + } + + if ( Error ) JsonqlTypeError.__proto__ = Error; + JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); + JsonqlTypeError.prototype.constructor = JsonqlTypeError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlTypeError'; + }; + + Object.defineProperties( JsonqlTypeError, staticAccessors ); + + return JsonqlTypeError; + }(Error)); + + // allow supply a custom checker function + // if that failed then we throw this error + var JsonqlCheckerError = /*@__PURE__*/(function (Error) { + function JsonqlCheckerError() { + 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 = JsonqlCheckerError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlCheckerError); + } + } + + if ( Error ) JsonqlCheckerError.__proto__ = Error; + JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); + JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlCheckerError'; + }; + + Object.defineProperties( JsonqlCheckerError, staticAccessors ); + + return JsonqlCheckerError; + }(Error)); + + // custom validation error class + // when validaton failed + var JsonqlValidationError = /*@__PURE__*/(function (Error) { + function JsonqlValidationError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlValidationError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlValidationError); + } + } + + if ( Error ) JsonqlValidationError.__proto__ = Error; + JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); + JsonqlValidationError.prototype.constructor = JsonqlValidationError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlValidationError'; + }; + + Object.defineProperties( JsonqlValidationError, staticAccessors ); + + return JsonqlValidationError; + }(Error)); + + /** + * This is a custom error to throw whenever a error happen inside the jsonql + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ + var JsonqlError = /*@__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)); + + // this is from an example from Koa team to use for internal middleware ctx.throw + // but after the test the res.body part is unable to extract the required data + // I keep this one here for future reference + + var JsonqlServerError = /*@__PURE__*/(function (Error) { + function JsonqlServerError(statusCode, message) { + Error.call(this, message); + this.statusCode = statusCode; + this.className = JsonqlServerError.name; + } + + if ( Error ) JsonqlServerError.__proto__ = Error; + JsonqlServerError.prototype = Object.create( Error && Error.prototype ); + JsonqlServerError.prototype.constructor = JsonqlServerError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlServerError'; + }; + + Object.defineProperties( JsonqlServerError, staticAccessors ); + + return JsonqlServerError; + }(Error)); + + // server side + + var errors = /*#__PURE__*/Object.freeze({ + __proto__: null, + Jsonql406Error: Jsonql406Error, + Jsonql500Error: Jsonql500Error, + JsonqlAuthorisationError: JsonqlAuthorisationError, + JsonqlContractAuthError: JsonqlContractAuthError, + JsonqlResolverAppError: JsonqlResolverAppError, + JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, + JsonqlEnumError: JsonqlEnumError, + JsonqlTypeError: JsonqlTypeError, + JsonqlCheckerError: JsonqlCheckerError, + JsonqlValidationError: JsonqlValidationError, + JsonqlError: JsonqlError, + JsonqlServerError: JsonqlServerError + }); + + // this will add directly to the then call in each http call + var JsonqlError$1 = JsonqlError; + + /** + * We can not just check something like result.data what if the result if false? + * @param {object} obj the result object + * @param {string} key we want to check if its exist or not + * @return {boolean} true on found + */ + var isObjectHasKey$1 = function (obj, key) { + var keys = Object.keys(obj); + return !!keys.filter(function (k) { return key === k; }).length; + }; + + /** + * It will ONLY have our own jsonql specific implement check + * @param {object} result the server return result + * @return {object} this will just throw error + */ + function clientErrorsHandler(result) { + if (isObjectHasKey$1(result, 'error')) { + var error = result.error; + var className = error.className; + var name = error.name; + var errorName = className || name; + // just throw the whole thing back + var msg = error.message || NO_ERROR_MSG$1; + var detail = error.detail || error; + if (errorName && errors[errorName]) { + throw new errors[className](msg, detail) + } + throw new JsonqlError$1(msg, detail) + } + // pass through to the next + return result; + } + + // get error name by instance + var UNKNOWN_ERROR = 'unknown'; + + /** + * @param {array} errs list of errors to compare from + * @param {object} e the error captured + * @return {array} filtered with name as value + */ + function mapErrToName(errs, e) { + return errs.filter(function (err) { return e instanceof err; }) + .map(function (err) { return err.name; }) + } + + /** + * @param {array} errs list of errors to compare from + * @param {object} e the error captured + * @return {string} name of the error object + */ + function getErrorNameByInstance(errs, e) { + var error = mapErrToName(errs, e); + return error.length ? error[0] : UNKNOWN_ERROR + } + + /** + * the same as above with a default JsonqlError as default + * @param {array} errs same + * @param {object} e error itself + * @return {string} the name of the error + */ + function getErrorNameByInstanceWithDefault(errs, e) { + var name = getErrorNameByInstance(errs, e); + return name === UNKNOWN_ERROR ? 'JsonqlError' : name; + } + + /** + * this will put into generator call at the very end and catch + * the error throw from inside then throw again + * this is necessary because we split calls inside and the throw + * will not reach the actual client unless we do it this way + * @param {object} e Error + * @return {void} just throw + */ + function finalCatch(e) { + // this is a hack to get around the validateAsync not actually throw error + // instead it just rejected it with the array of failed parameters + if (Array.isArray(e)) { + // if we want the message then I will have to create yet another function + // to wrap this function to provide the name prop + throw new JsonqlValidationError('', e) + } + var msg = e.message || NO_ERROR_MSG$1; + var detail = e.detail || e; + switch (true) { + case e instanceof Jsonql406Error: + throw new Jsonql406Error(msg, detail) + case e instanceof Jsonql500Error: + throw new Jsonql500Error(msg, detail) + case e instanceof JsonqlAuthorisationError: + throw new JsonqlAuthorisationError(msg, detail) + case e instanceof JsonqlContractAuthError: + throw new JsonqlContractAuthError(msg, detail) + case e instanceof JsonqlResolverAppError: + throw new JsonqlResolverAppError(msg, detail) + case e instanceof JsonqlResolverNotFoundError: + throw new JsonqlResolverNotFoundError(msg, detail) + case e instanceof JsonqlEnumError: + throw new JsonqlEnumError(msg, detail) + case e instanceof JsonqlTypeError: + throw new JsonqlTypeError(msg, detail) + case e instanceof JsonqlCheckerError: + throw new JsonqlCheckerError(msg, detail) + case e instanceof JsonqlValidationError: + throw new JsonqlValidationError(msg, detail) + case e instanceof JsonqlServerError: + throw new JsonqlServerError(msg, detail) + default: + throw new JsonqlError(msg, detail) + } + } + + // jsonql-errors main interface + var JSONQL_ERRORS_INFO = '__PLACEHOLDER__'; + + var errors$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + JSONQL_ERRORS_INFO: JSONQL_ERRORS_INFO, + UNKNOWN_ERROR: UNKNOWN_ERROR, + getErrorByStatus: getErrorByStatus, + clientErrorsHandler: clientErrorsHandler, + finalCatch: finalCatch, + getErrorNameByInstance: getErrorNameByInstance, + getErrorNameByInstanceWithDefault: getErrorNameByInstanceWithDefault, + Jsonql406Error: Jsonql406Error, + Jsonql500Error: Jsonql500Error, + JsonqlAuthorisationError: JsonqlAuthorisationError, + JsonqlContractAuthError: JsonqlContractAuthError, + JsonqlResolverAppError: JsonqlResolverAppError, + JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, + JsonqlEnumError: JsonqlEnumError, + JsonqlTypeError: JsonqlTypeError, + JsonqlCheckerError: JsonqlCheckerError, + JsonqlValidationError: JsonqlValidationError, + JsonqlError: JsonqlError, + JsonqlServerError: JsonqlServerError + }); + + /** + * Check several parameter that there is something in the param + * @param {*} param input + * @return {boolean} + */ + var isNotEmpty = function (a) { + if (isArray(a)) { + return true; + } + return a !== undefined && a !== null && trim(a) !== ''; + }; + + /** `Object#toString` result references. */ + var numberTag = '[object Number]'; + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** `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); + } + + // validator numbers + /** + * @2015-05-04 found a problem if the value is a number like string + * it will pass, so add a chck if it's string before we pass to next + * @param {number} value expected value + * @return {boolean} true if OK + */ + var checkIsNumber = function(value) { + return isString(value) ? false : !isNaN( parseFloat(value) ) + }; + + // validate string type + /** + * @param {string} value expected value + * @return {boolean} true if OK + */ + var checkIsString = function(value) { + return (trim(value) !== '') ? isString(value) : false; + }; + + // check for boolean + + /** + * @param {boolean} value expected + * @return {boolean} true if OK + */ + var checkIsBoolean = function(value) { + return value !== null && value !== undefined && typeof value === 'boolean' + }; + + // validate any thing only check if there is something + + /** + * @param {*} value the value + * @param {boolean} [checkNull=true] strict check if there is null value + * @return {boolean} true is OK + */ + var checkIsAny = function(value, checkNull) { + if ( checkNull === void 0 ) checkNull = true; + + if (value !== undefined && value !== '' && trim(value) !== '') { + if (checkNull === false || (checkNull === true && value !== null)) { + return true; + } + } + return false; + }; + + // Good practice rule - No magic number + + var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; + var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; + var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; + // @TODO the jsdoc return array. and we should also allow array syntax + var DEFAULT_TYPE$1 = DEFAULT_TYPE; + var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; + var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; + + var TYPE_KEY$1 = TYPE_KEY; + var OPTIONAL_KEY$1 = OPTIONAL_KEY; + var ENUM_KEY$1 = ENUM_KEY; + var ARGS_KEY$1 = ARGS_KEY; + var CHECKER_KEY$1 = CHECKER_KEY; + var ALIAS_KEY$1 = ALIAS_KEY; + + var ARRAY_TYPE$1 = ARRAY_TYPE; + var OBJECT_TYPE$1 = OBJECT_TYPE; + var STRING_TYPE$1 = STRING_TYPE; + var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; + var NUMBER_TYPE$1 = NUMBER_TYPE; + var KEY_WORD$1 = KEY_WORD; + var OR_SEPERATOR$1 = OR_SEPERATOR; + + // not actually in use + // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; + + // primitive types + + /** + * this is a wrapper method to call different one based on their type + * @param {string} type to check + * @return {function} a function to handle the type + */ + var combineFn = function(type) { + switch (type) { + case NUMBER_TYPE$1: + return checkIsNumber; + case STRING_TYPE$1: + return checkIsString; + case BOOLEAN_TYPE$1: + return checkIsBoolean; + default: + return checkIsAny; + } + }; + + // validate array type + + /** + * @param {array} value expected + * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well + * @return {boolean} true if OK + */ + var checkIsArray = function(value, type) { + if ( type === void 0 ) type=''; + + if (isArray(value)) { + if (type === '' || trim(type)==='') { + return true; + } + // we test it in reverse + // @TODO if the type is an array (OR) then what? + // we need to take into account this could be an array + var c = value.filter(function (v) { return !combineFn(type)(v); }); + return !(c.length > 0) + } + return false; + }; + + /** + * check if it matches the array. pattern + * @param {string} type + * @return {boolean|array} false means NO, always return array + */ + var isArrayLike = function(type) { + // @TODO could that have something like array<> instead of array.<>? missing the dot? + // because type script is Array without the dot + if (type.indexOf(ARRAY_TYPE_LFT$1) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { + var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); + if (_type.indexOf(OR_SEPERATOR$1)) { + return _type.split(OR_SEPERATOR$1) + } + return [_type] + } + return false; + }; + + /** + * we might encounter something like array. then we need to take it apart + * @param {object} p the prepared object for processing + * @param {string|array} type the type came from + * @return {boolean} for the filter to operate on + */ + var arrayTypeHandler = function(p, type) { + var arg = p.arg; + // need a special case to handle the OR type + // we need to test the args instead of the type(s) + if (type.length > 1) { + return !arg.filter(function (v) { return ( + !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) + ); }).length; + } + // type is array so this will be or! + return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length; + }; + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]'; + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** Used for built-in method references. */ + var objectProto$3 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$2 = objectProto$3.hasOwnProperty; + + /** Built-in value references. */ + var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + function stubFalse() { + return false; + } + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Built-in value references. */ + var Buffer = moduleExports ? root.Buffer : undefined; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER = 9007199254740991; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER$1 = 9007199254740991; + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; + } + + /** `Object#toString` result references. */ + var argsTag$1 = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag$1 = '[object Number]', + objectTag$1 = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag$1 = '[object String]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag$1] = + typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag$1] = + typedArrayTags[weakMapTag] = false; + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** Detect free variable `exports`. */ + var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports$1 && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** Used for built-in method references. */ + var objectProto$4 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$3 = objectProto$4.hasOwnProperty; + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$3.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** Used for built-in method references. */ + var objectProto$5 = Object.prototype; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; + + return value === proto; + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeKeys = overArg(Object.keys, Object); + + /** Used for built-in method references. */ + var objectProto$6 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$4 = objectProto$6.hasOwnProperty; + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$4.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** `Object#toString` result references. */ + var asyncTag = '[object AsyncFunction]', + funcTag$1 = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike$1(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** Used for built-in method references. */ + var arrayProto = Array.prototype; + + /** Built-in value references. */ + var splice = arrayProto.splice; + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** Used to detect overreaching core-js shims. */ + var coreJsData = root['__core-js_shared__']; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** Used for built-in method references. */ + var funcProto$1 = Function.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString$1 = funcProto$1.toString; + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString$1.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used for built-in method references. */ + var funcProto$2 = Function.prototype, + objectProto$7 = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString$2 = funcProto$2.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty$5 = objectProto$7.hasOwnProperty; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString$2.call(hasOwnProperty$5).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /* Built-in method references that are verified to be native. */ + var Map$1 = getNative(root, 'Map'); + + /* Built-in method references that are verified to be native. */ + var nativeCreate = getNative(Object, 'create'); + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used for built-in method references. */ + var objectProto$8 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$6 = objectProto$8.hasOwnProperty; + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty$6.call(data, key) ? data[key] : undefined; + } + + /** Used for built-in method references. */ + var objectProto$9 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$7 = objectProto$9.hasOwnProperty; + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key); + } + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; + return this; + } + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map$1 || ListCache), + 'string': new Hash + }; + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED$2); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** Built-in value references. */ + var Uint8Array$1 = root.Uint8Array; + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$1 = 1, + COMPARE_UNORDERED_FLAG$1 = 2; + + /** `Object#toString` result references. */ + var boolTag$1 = '[object Boolean]', + dateTag$1 = '[object Date]', + errorTag$1 = '[object Error]', + mapTag$1 = '[object Map]', + numberTag$2 = '[object Number]', + regexpTag$1 = '[object RegExp]', + setTag$1 = '[object Set]', + stringTag$2 = '[object String]', + symbolTag$1 = '[object Symbol]'; + + var arrayBufferTag$1 = '[object ArrayBuffer]', + dataViewTag$1 = '[object DataView]'; + + /** Used to convert symbols to primitives and strings. */ + var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined, + symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag$1: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag$1: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array$1(object), new Uint8Array$1(other))) { + return false; + } + return true; + + case boolTag$1: + case dateTag$1: + case numberTag$2: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag$1: + return object.name == other.name && object.message == other.message; + + case regexpTag$1: + case stringTag$2: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag$1: + var convert = mapToArray; + + case setTag$1: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG$1; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag$1: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + function stubArray() { + return []; + } + + /** Used for built-in method references. */ + var objectProto$a = Object.prototype; + + /** Built-in value references. */ + var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols = Object.getOwnPropertySymbols; + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable$1.call(object, symbol); + }); + }; + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$2 = 1; + + /** Used for built-in method references. */ + var objectProto$b = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$8 = objectProto$b.hasOwnProperty; + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(root, 'DataView'); + + /* Built-in method references that are verified to be native. */ + var Promise$1 = getNative(root, 'Promise'); + + /* Built-in method references that are verified to be native. */ + var Set$1 = getNative(root, 'Set'); + + /* Built-in method references that are verified to be native. */ + var WeakMap$1 = getNative(root, 'WeakMap'); + + /** `Object#toString` result references. */ + var mapTag$2 = '[object Map]', + objectTag$2 = '[object Object]', + promiseTag = '[object Promise]', + setTag$2 = '[object Set]', + weakMapTag$1 = '[object WeakMap]'; + + var dataViewTag$2 = '[object DataView]'; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map$1), + promiseCtorString = toSource(Promise$1), + setCtorString = toSource(Set$1), + weakMapCtorString = toSource(WeakMap$1); + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$2) || + (Map$1 && getTag(new Map$1) != mapTag$2) || + (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || + (Set$1 && getTag(new Set$1) != setTag$2) || + (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag$2 ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag$2; + case mapCtorString: return mapTag$2; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag$2; + case weakMapCtorString: return weakMapTag$1; + } + } + return result; + }; + } + + var getTag$1 = getTag; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$3 = 1; + + /** `Object#toString` result references. */ + var argsTag$2 = '[object Arguments]', + arrayTag$1 = '[object Array]', + objectTag$3 = '[object Object]'; + + /** Used for built-in method references. */ + var objectProto$c = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$9 = objectProto$c.hasOwnProperty; + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag$1 : getTag$1(object), + othTag = othIsArr ? arrayTag$1 : getTag$1(other); + + objTag = objTag == argsTag$2 ? objectTag$3 : objTag; + othTag = othTag == argsTag$2 ? objectTag$3 : othTag; + + var objIsObj = objTag == objectTag$3, + othIsObj = othTag == objectTag$3, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { + var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$4 = 1, + COMPARE_UNORDERED_FLAG$2 = 2; + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** Error message constants. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** Used to match property names within property paths. */ + var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** Used as references for various `Number` constants. */ + var INFINITY$1 = 1 / 0; + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$5 = 1, + COMPARE_UNORDERED_FLAG$3 = 2; + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); + }; + } + + /** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + function identity(value) { + return value; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ + function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + // validate object type + /** + * @TODO if provide with the keys then we need to check if the key:value type as well + * @param {object} value expected + * @param {array} [keys=null] if it has the keys array to compare as well + * @return {boolean} true if OK + */ + var checkIsObject = function(value, keys) { + if ( keys === void 0 ) keys=null; + + if (isPlainObject(value)) { + if (!keys) { + return true; + } + if (checkIsArray(keys)) { + // please note we DON'T care if some is optional + // plese refer to the contract.json for the keys + return !keys.filter(function (key) { + var _value = value[key.name]; + return !(key.type.length > key.type.filter(function (type) { + var tmp; + if (_value !== undefined) { + if ((tmp = isArrayLike(type)) !== false) { + return !arrayTypeHandler({arg: _value}, tmp) + // return tmp.filter(t => !checkIsArray(_value, t)).length; + // @TODO there might be an object within an object with keys as well :S + } + return !combineFn(type)(_value) + } + return true; + }).length) + }).length; + } + } + return false; + }; + + /** + * fold this into it's own function to handler different object type + * @param {object} p the prepared object for process + * @return {boolean} + */ + var objectTypeHandler = function(p) { + var arg = p.arg; + var param = p.param; + var _args = [arg]; + if (Array.isArray(param.keys) && param.keys.length) { + _args.push(param.keys); + } + // just simple check + return Reflect.apply(checkIsObject, null, _args) + }; + + // move the index.js code here that make more sense to find where things are + // import debug from 'debug' + // const debugFn = debug('jsonql-params-validator:validator') + // also export this for use in other places + + /** + * We need to handle those optional parameter without a default value + * @param {object} params from contract.json + * @return {boolean} for filter operation false is actually OK + */ + var optionalHandler = function( params ) { + var arg = params.arg; + var param = params.param; + if (isNotEmpty(arg)) { + // debug('call optional handler', arg, params); + // loop through the type in param + return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } + ).length) + } + return false; + }; + + /** + * actually picking the validator + * @param {*} type for checking + * @param {*} value for checking + * @return {boolean} true on OK + */ + var validateHandler = function(type, value) { + var tmp; + switch (true) { + case type === OBJECT_TYPE$1: + // debugFn('call OBJECT_TYPE') + return !objectTypeHandler(value) + case type === ARRAY_TYPE$1: + // debugFn('call ARRAY_TYPE') + return !checkIsArray(value.arg) + // @TODO when the type is not present, it always fall through here + // so we need to find a way to actually pre-check the type first + // AKA check the contract.json map before running here + case (tmp = isArrayLike(type)) !== false: + // debugFn('call ARRAY_LIKE: %O', value) + return !arrayTypeHandler(value, tmp) + default: + return !combineFn(type)(value.arg) + } + }; + + /** + * it get too longer to fit in one line so break it out from the fn below + * @param {*} arg value + * @param {object} param config + * @return {*} value or apply default value + */ + var getOptionalValue = function(arg, param) { + if (arg !== undefined) { + return arg; + } + return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null) + }; + + /** + * padding the arguments with defaultValue if the arguments did not provide the value + * this will be the name export + * @param {array} args normalized arguments + * @param {array} params from contract.json + * @return {array} merge the two together + */ + var normalizeArgs = function(args, params) { + // first we should check if this call require a validation at all + // there will be situation where the function doesn't need args and params + if (!checkIsArray(params)) { + // debugFn('params value', params) + throw new JsonqlError(PARAMS_NOT_ARRAY_ERR) + } + if (params.length === 0) { + return []; + } + if (!checkIsArray(args)) { + throw new JsonqlError(ARGS_NOT_ARRAY_ERR) + } + // debugFn(args, params); + // fall through switch + switch(true) { + case args.length == params.length: // standard + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, + param: params[i] + } + ); }) + case params[0].variable === true: // using spread syntax + var type = params[0].type; + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, // keep the index for reference + param: params[i] || { type: type, name: '_' } + } + ); }) + // with optional defaultValue parameters + case args.length < params.length: + return params.map(function (param, i) { return ( + { + param: param, + index: i, + arg: getOptionalValue(args[i], param), + optional: param.optional || false + } + ); }) + // this one pass more than it should have anything after the args.length will be cast as any type + case args.length > params.length: + var ctn = params.length; + // this happens when we have those array. type + var _type = [ DEFAULT_TYPE$1 ]; + // we only looking at the first one, this might be a @BUG + /* + if ((tmp = isArrayLike(params[0].type[0])) !== false) { + _type = tmp; + } */ + // if we use the params as guide then the rest will get throw out + // which is not what we want, instead, anything without the param + // will get a any type and optional flag + return args.map(function (arg, i) { + var optional = i >= ctn ? true : !!params[i].optional; + var param = params[i] || { type: _type, name: ("_" + i) }; + return { + arg: optional ? getOptionalValue(arg, param) : arg, + index: i, + param: param, + optional: optional + } + }) + // @TODO find out if there is more cases not cover + default: // this should never happen + // debugFn('args', args) + // debugFn('params', params) + // this is unknown therefore we just throw it! + throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) + } + }; + + // what we want is after the validaton we also get the normalized result + // which is with the optional property if the argument didn't provide it + /** + * process the array of params back to their arguments + * @param {array} result the params result + * @return {array} arguments + */ + var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; + + /** + * validator main interface + * @param {array} args the arguments pass to the method call + * @param {array} params from the contract for that method + * @param {boolean} [withResul=false] if true then this will return the normalize result as well + * @return {array} empty array on success, or failed parameter and reasons + */ + var validateSync = function(args, params, withResult) { + var obj; + + if ( withResult === void 0 ) withResult = false; + var cleanArgs = normalizeArgs(args, params); + var checkResult = cleanArgs.filter(function (p) { + // v1.4.4 this fixed the problem, the root level optional is from the last fn + if (p.optional === true || p.param.optional === true) { + return optionalHandler(p) + } + // because array of types means OR so if one pass means pass + return !(p.param.type.length > p.param.type.filter( + function (type) { return validateHandler(type, p); } + ).length) + }); + // using the same convention we been using all this time + return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) + }; + + /** + * A wrapper method that return promise + * @param {array} args arguments + * @param {array} params from contract.json + * @param {boolean} [withResul=false] if true then this will return the normalize result as well + * @return {object} promise.then or catch + */ + var validateAsync = function(args, params, withResult) { + if ( withResult === void 0 ) withResult = false; + + return new Promise(function (resolver, rejecter) { + var result = validateSync(args, params, withResult); + if (withResult) { + return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) + : resolver(result[DATA_KEY]) + } + // the different is just in the then or catch phrase + return result.length ? rejecter(result) : resolver([]) + }) + }; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** Detect free variable `exports`. */ + var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; + + /** Built-in value references. */ + var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, + allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** Built-in value references. */ + var objectCreate = Object.create; + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike$1(value); + } + + /** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; + } + + /** Used for built-in method references. */ + var objectProto$d = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$a = objectProto$d.hasOwnProperty; + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty$a.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** Used for built-in method references. */ + var objectProto$e = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$b = objectProto$e.hasOwnProperty; + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty$b.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike$1(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeMax = Math.max; + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ + function constant(value) { + return function() { + return value; + }; + } + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeNow = Date.now; + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike$1(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** Error message constants. */ + var FUNC_ERROR_TEXT$1 = 'Expected a function'; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$1); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols$1 = Object.getOwnPropertySymbols; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = baseIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(baseIteratee(predicate))); + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate), baseForOwn); + } + + /** + * @param {array} arr Array for check + * @param {*} value target + * @return {boolean} true on successs + */ + var isInArray = function(arr, value) { + return !!arr.filter(function (a) { return a === value; }).length; + }; + + var isObjectHasKey$2 = function(obj, key) { + var keys = Object.keys(obj); + return isInArray(keys, key) + }; + + // just not to make my head hurt + var isEmpty = function (value) { return !isNotEmpty(value); }; + + /** + * Map the alias to their key then grab their value over + * @param {object} config the user supplied config + * @param {object} appProps the default option map + * @return {object} the config keys replaced with the appProps key by the ALIAS + */ + function mapAliasConfigKeys(config, appProps) { + // need to do two steps + // 1. take key with alias key + var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$1]; } ); + if (isEqual(aliasMap, {})) { + return config; + } + return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) + } + + /** + * We only want to run the valdiation against the config (user supplied) value + * but keep the defaultOptions untouch + * @param {object} config configuraton supplied by user + * @param {object} appProps the default options map + * @return {object} the pristine values that will add back to the final output + */ + function preservePristineValues(config, appProps) { + // @BUG this will filter out those that is alias key + // we need to first map the alias keys back to their full key + var _config = mapAliasConfigKeys(config, appProps); + // take the default value out + var pristineValues = mapValues( + omitBy(appProps, function (value, key) { return isObjectHasKey$2(_config, key); }), + function (value) { return value.args; } + ); + // for testing the value + var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !isObjectHasKey$2(_config, key); }); + // output + return { + pristineValues: pristineValues, + checkAgainstAppProps: checkAgainstAppProps, + config: _config // passing this correct values back + } + } + + /** + * This will take the value that is ONLY need to check + * @param {object} config that one + * @param {object} props map for creating checking + * @return {object} put that arg into the args + */ + function processConfigAction(config, props) { + // debugFn('processConfigAction', props) + // v.1.2.0 add checking if its mark optional and the value is empty then pass + return mapValues(props, function (value, key) { + var obj, obj$1; + + return ( + config[key] === undefined || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) + ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) + : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) + ); + } + ) + } + + /** + * Quick transform + * @TODO we should only validate those that is pass from the config + * and pass through those values that is from the defaultOptions + * @param {object} opts that one + * @param {object} appProps mutation configuration options + * @return {object} put that arg into the args + */ + function prepareArgsForValidation(opts, appProps) { + var ref = preservePristineValues(opts, appProps); + var config = ref.config; + var pristineValues = ref.pristineValues; + var checkAgainstAppProps = ref.checkAgainstAppProps; + // output + return [ + processConfigAction(config, checkAgainstAppProps), + pristineValues + ] + } + + // breaking the whole thing up to see what cause the multiple calls issue + + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:options:validation') + + /** + * just make sure it returns an array to use + * @param {*} arg input + * @return {array} output + */ + var toArray$1 = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; + + /** + * DIY in array + * @param {array} arr to check against + * @param {*} value to check + * @return {boolean} true on OK + */ + var inArray$1 = function (arr, value) { return ( + !!arr.filter(function (v) { return v === value; }).length + ); }; + + /** + * break out to make the code easier to read + * @param {object} value to process + * @param {function} cb the validateSync + * @return {array} empty on success + */ + function validateHandler$1(value, cb) { + var obj; + + // cb is the validateSync methods + var args = [ + [ value[ARGS_KEY$1] ], + [( obj = {}, obj[TYPE_KEY$1] = toArray$1(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] + ]; + // debugFn('validateHandler', args) + return Reflect.apply(cb, null, args) + } + + /** + * Check against the enum value if it's provided + * @param {*} value to check + * @param {*} enumv to check against if it's not false + * @return {boolean} true on OK + */ + var enumHandler = function (value, enumv) { + if (checkIsArray(enumv)) { + return inArray$1(enumv, value) + } + return true; + }; + + /** + * Allow passing a function to check the value + * There might be a problem here if the function is incorrect + * and that will makes it hard to debug what is going on inside + * @TODO there could be a few feature add to this one under different circumstance + * @param {*} value to check + * @param {function} checker for checking + */ + var checkerHandler = function (value, checker) { + try { + return isFunction(checker) ? checker.apply(null, [value]) : false; + } catch (e) { + return false; + } + }; + + /** + * Taken out from the runValidaton this only validate the required values + * @param {array} args from the config2argsAction + * @param {function} cb validateSync + * @return {array} of configuration values + */ + function runValidationAction(cb) { + return function (value, key) { + // debugFn('runValidationAction', key, value) + if (value[KEY_WORD$1]) { + return value[ARGS_KEY$1] + } + var check = validateHandler$1(value, cb); + if (check.length) { + // log('runValidationAction', key, value) + throw new JsonqlTypeError(key, check) + } + if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { + // log(ENUM_KEY, value[ENUM_KEY]) + throw new JsonqlEnumError(key) + } + if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { + // log(CHECKER_KEY, value[CHECKER_KEY]) + throw new JsonqlCheckerError(key) + } + return value[ARGS_KEY$1] + } + } + + /** + * @param {object} args from the config2argsAction + * @param {function} cb validateSync + * @return {object} of configuration values + */ + function runValidation(args, cb) { + var argsForValidate = args[0]; + var pristineValues = args[1]; + // turn the thing into an array and see what happen here + // debugFn('_args', argsForValidate) + var result = mapValues(argsForValidate, runValidationAction(cb)); + return merge(result, pristineValues) + } + + // this is port back from the client to share across all projects + + /** + * @param {object} config user provide configuration option + * @param {object} appProps mutation configuration options + * @param {object} constProps the immutable configuration options + * @param {function} cb the validateSync method + * @return {object} Promise resolve merge config object + */ + function checkOptionsSync(config, appProps, constProps, cb) { + if ( config === void 0 ) config = {}; + + return merge( + runValidation( + prepareArgsForValidation(config, appProps), + cb + ), + constProps + ) + } + + // create function to construct the config entry so we don't need to keep building object + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:construct-config'); + /** + * @param {*} args value + * @param {string} type for value + * @param {boolean} [optional=false] + * @param {boolean|array} [enumv=false] + * @param {boolean|function} [checker=false] + * @return {object} config entry + */ + function constructConfig(args, type, optional, enumv, checker, alias) { + if ( optional === void 0 ) optional=false; + if ( enumv === void 0 ) enumv=false; + if ( checker === void 0 ) checker=false; + if ( alias === void 0 ) alias=false; + + var base = {}; + base[ARGS_KEY] = args; + base[TYPE_KEY] = type; + if (optional === true) { + base[OPTIONAL_KEY] = true; + } + if (checkIsArray(enumv)) { + base[ENUM_KEY] = enumv; + } + if (isFunction(checker)) { + base[CHECKER_KEY] = checker; + } + if (isString(alias)) { + base[ALIAS_KEY] = alias; + } + return base; + } + + // export also create wrapper methods + + /** + * This has a different interface + * @param {*} value to supply + * @param {string|array} type for checking + * @param {object} params to map against the config check + * @param {array} params.enumv NOT enum + * @param {boolean} params.optional false then nothing + * @param {function} params.checker need more work on this one later + * @param {string} params.alias mostly for cmd + */ + var createConfig = function (value, type, params) { + if ( params === void 0 ) params = {}; + + // Note the enumv not ENUM + // const { enumv, optional, checker, alias } = params; + // let args = [value, type, optional, enumv, checker, alias]; + var o = params[OPTIONAL_KEY]; + var e = params[ENUM_KEY]; + var c = params[CHECKER_KEY]; + var a = params[ALIAS_KEY]; + return constructConfig.apply(null, [value, type, o, e, c, a]) + }; + + // copy of above but it's sync + var checkConfig = function(validateSync) { + return function(config, appProps, constantProps) { + if ( constantProps === void 0 ) constantProps = {}; + + return checkOptionsSync(config, appProps, constantProps, validateSync) + } + }; + + // export + var isString$1 = checkIsString; + var isNumber$1 = checkIsNumber; + var validateAsync$1 = validateAsync; + + var createConfig$1 = createConfig; + var checkConfig$1 = checkConfig(validateSync); + + /** + * using just the map reduce to chain multiple functions together + * @param {function} mainFn the init function + * @param {array} moreFns as many as you want to take the last value and return a new one + * @return {function} accept value for the mainFn + */ + var chainFns = function (mainFn) { + var moreFns = [], len = arguments.length - 1; + while ( len-- > 0 ) moreFns[ len ] = arguments[ len + 1 ]; + + return ( + function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return ( + moreFns.reduce(function (value, nextFn) { return ( + // change here to check if the return value is array then we spread it + Reflect.apply(nextFn, null, toArray(value)) + ); }, Reflect.apply(mainFn, null, args)) + ); + } + ); + }; + + /** + * check if the object has name property + * @param {object} obj the object to check + * @param {string} name the prop name + * @return {*} the value or undefined + */ + function objHasProp(obj, name) { + var prop = Object.getOwnPropertyDescriptor(obj, name); + return prop !== undefined && prop.value ? prop.value : prop; + } + + /** + * 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 {string} name the name of the object to get inject also for checking + * @param {object} data to inject into the function static interface + * @param {boolean} [overwrite=false] if we want to overwrite the existing data + * @return {function} added property resolver + */ + function injectToFn(resolver, name, data, overwrite) { + if ( overwrite === void 0 ) overwrite = false; + + var check = objHasProp(resolver, name); + if (overwrite === false && check !== undefined) { + // console.info(`NOT INJECTED`) + return resolver; + } + /* this will throw error! + if (overwrite === true && check !== undefined) { + delete resolver[name] // delete this property + } + */ + // console.info(`INJECTED`) + Object.defineProperty(resolver, name, { + value: data, + writable: overwrite // if its set to true then we should able to overwrite it + }); + + return resolver; + } + + // breaking out the inner methods generator in here + + /** + * generate authorisation specific methods + * @param {object} jsonqlInstance instance of this + * @param {string} name of method + * @param {object} opts configuration + * @param {object} contract to match + * @return {function} for use + */ + var authMethodGenerator = function (jsonqlInstance, name, opts, contract) { + return function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var params = contract.auth[name].params; + var values = params.map(function (p, i) { return args[i]; }); + var header = args[params.length] || {}; + return validateAsync$1(args, params) + .then(function () { return jsonqlInstance + .query + .apply(jsonqlInstance, [name, values, header]); } + ) + .catch(finalCatch) + } + }; + + /** + * Break up the different type each - create query methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createQueryMethods = function (obj, jsonqlInstance, ee, config, contract) { + var query = {}; + var loop = function ( queryFn ) { + // to keep it clean we use a param to id the auth method + // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; + // generate the query method + query = injectToFn(query, queryFn, function queryFnHandler() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var params = contract.query[queryFn].params; + var _args = params.map(function (param, i) { return args[i]; }); + // debug('query', queryFn, _params); + // @TODO this need to change to a different way to add an extra header + var header = {}; + // @TODO validate against the type + return validateAsync$1(_args, params) + .then(function () { return jsonqlInstance + .query + .apply(jsonqlInstance, [queryFn, _args, header]); } + ) + .catch(finalCatch) + }); + }; + + for (var queryFn in contract.query) loop( queryFn ); + obj.query = query; + // create an alias to the helloWorld method + obj.helloWorld = query.helloWorld; + return [ obj, jsonqlInstance, ee, config, contract ] + }; + + /** + * create mutation methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createMutationMethods = function (obj, jsonqlInstance, ee, config, contract) { + var mutation = {}; + // process the mutation, the reason the mutation has a fixed number of parameters + // there is only the payload, and conditions parameters + // plus a header at the end + var loop = function ( mutationFn ) { + mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header) { + if ( header === void 0 ) header = {}; + + var args = [payload, conditions]; + var params = contract.mutation[mutationFn].params; + return validateAsync$1(args, params) + .then(function () { return jsonqlInstance + .mutation + .apply(jsonqlInstance, [mutationFn, payload, conditions, header]); } + ) + .catch(function (e) { + console.error('--- mutation fn catch ---', e); + return finalCatch(e) + }) + }); + }; + + for (var mutationFn in contract.mutation) loop( mutationFn ); + obj.mutation = mutation; + return [ obj, jsonqlInstance, ee, config, contract ] + }; + + /** + * create auth methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createAuthMethods = function (obj, jsonqlInstance, ee, config, contract) { + if (config.enableAuth && contract.auth) { + var auth = {}; // v1.3.1 add back the auth prop name in contract + var loginHandlerName = config.loginHandlerName; + var logoutHandlerName = config.logoutHandlerName; + if (contract.auth[loginHandlerName]) { + // changing to the name the config specify + auth[loginHandlerName] = function loginHandlerFn() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract); + return fn.apply(null, args) + .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance)) + .then(function (token) { + ee.$trigger(LOGIN_NAME, token); + return token; + }) + }; + } + // @TODO allow to logout one particular profile or all of them + if (contract.auth[logoutHandlerName]) { + auth[logoutHandlerName] = function logoutHandlerFn() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract); + return fn.apply(null, args) + .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance)) + .then(function (r) { + ee.$trigger(LOGOUT_NAME, r); + return r; + }) + }; + } else { + auth[logoutHandlerName] = function logoutHandlerFn() { + jsonqlInstance.postLogoutAction(KEY_WORD); + ee.$trigger(LOGOUT_NAME, KEY_WORD); + }; + } + obj.auth = auth; + } + + return obj; + }; + + /** + * Here just generate the methods calls + * @param {object} jsonqlInstance what it said + * @param {object} ee event emitter + * @param {object} config configuration + * @param {object} contract the map + * @return {object} with mapped methods + */ + function methodsGenerator(jsonqlInstance, ee, config, contract) { + var obj = {}; + var executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods); + return executor(obj, jsonqlInstance, ee, config, contract) + } + + // This generator will use the old style + + /** + * Group all the same methods together + * @param {object} ee event emitters + * @param {string} type query, mutation or auth + * @param {string} resolverName use as the guide + * @param {array} args from the call + * @return {function} the handler itself + */ + var handler = function (ee, type) { + // we don't run validate here because we want until the contract is ready + return function (resolverName) { + var args = [], len = arguments.length - 1; + while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; + + return ( + new Promise(function (resolver, rejecter) { + // this are the callbacks + ee.$only(createEvt(type, resolverName, ON_RESULT_PROP_NAME), resolver); + ee.$only(createEvt(type, resolverName, ON_ERROR_PROP_NAME), rejecter); + // this is the main call + ee.$trigger(type, { resolverName: resolverName, args: args }); + }) + ); + } + }; + + /** + * @param {object} ee eventEmitter + * @param {object} contract the map + * @param {object} config configuration + */ + var validateRegisteredEvents = function (ee, contract, config) { + var storedEvt = ee.$queues; + var debug = config.debugOn; + if (debug) { + console.info('(validateRegisteredEvents)', 'storedEvt', storedEvt); + } + storedEvt.forEach(function (args) { + var type = args[0]; + var payload = args[1]; + var resolverName = payload.resolverName; + if (debug) { + console.info('(validateRegisteredEvents)', type, resolverName); + } + if (!contract[type][resolverName]) { + throw new Error((type + "." + resolverName + " not existed in contract!")) + } + }); + }; + + /** + * set up all the event handlers once the contract is ready + * @param {object} jsonqlInstance what the name said + * @param {object} ee event emitter + * @param {object} config the configuration + * @param {object} contract the map + * @return {void} nothing + */ + function setupEventHandlers(jsonqlInstance, ee, config, contract) { + var methods = methodsGenerator(jsonqlInstance, ee, config, contract); + validateRegisteredEvents(ee, contract, config); + // create handler + var loop = function ( type ) { + // setup event listeners - only one listener per type + ee.$only(type, function(ref) { + var resolverName = ref.resolverName; + var args = ref.args; + + if (methods[type][resolverName]) { + Reflect.apply(methods[type][resolverName], null, args) + .then(function (result) { + ee.$trigger(createEvt(type, resolverName, ON_RESULT_PROP_NAME), result); + }) + .catch(function (err) { + ee.$trigger(createEvt(type, resolverName, ON_ERROR_PROP_NAME), err); + }); + } else { + console.error((resolverName + " is not defined in the contract!")); + } + }); + }; + + for (var type in methods) loop( type ); + // all done now release the queue if any + setTimeout(function () { + ee.$suspend = false; + }, 1); + } + + /** + * @param {object} jsonqlInstance jsonql class instance + * @param {object} config options + * @param {object} contractPromise an unresolve promise + * @param {object} ee eventEmitter + * @return {object} constructed functions call + */ + var generator = function (jsonqlInstance, config, contractPromise, ee) { + ee.$suspend = true; // hold all the calls + // wait for the promise to resolve + contractPromise.then(function (contract) { + setupEventHandlers(jsonqlInstance, ee, config, contract); + }); + // construct the api + var obj = { + query: handler(ee, 'query'), + mutation: handler(ee, 'mutation'), + auth: handler(ee, 'auth') + }; + // allow getting the token for valdiate agains the socket + obj.getToken = function () { return jsonqlInstance.rawAuthToken; }; + // this will pass to the ws-client if needed + // obj.eventEmitter = ee; + // this will require a param + if (config.exposeContract) { + obj.getContract = function () { return jsonqlInstance.get(); }; + } + if (config.enableAuth) { + obj.userdata = function () { return jsonqlInstance.userdata; }; + } + obj.version = '1.5.1'; + // output + return obj; + }; + + // split the contract into the node side and the generic side + /** + * Check if the json is a contract file or not + * @param {object} contract json object + * @return {boolean} true + */ + function checkIsContract(contract) { + return isPlainObject(contract) + && ( + isObjectHasKey(contract, QUERY_NAME) + || isObjectHasKey(contract, MUTATION_NAME) + || isObjectHasKey(contract, SOCKET_NAME) + ) + } + + /** + * Wrapper method that check if it's contract then return the contract or false + * @param {object} contract the object to check + * @return {boolean | object} false when it's not + */ + function isContract(contract) { + return checkIsContract(contract) ? contract : false; + } + + /** + * generate a 32bit hash based on the function.toString() + * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery + * @param {string} s the converted to string function + * @return {string} the hashed function string + */ + function hashCode(s) { + return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) + } + + // take only the module part which is what we use here + /** + * @param {object} jsonqlInstance the init instance of jsonql client + * @param {object} contract the static contract + * @return {object} contract may be from server + */ + var getContractFromConfig = function(jsonqlInstance, contract) { + if ( contract === void 0 ) contract = {}; + + if (isContract(contract)) { + return Promise.resolve(contract) + } + return jsonqlInstance.getContract() + }; + // wrapper method to make sure it's a string + var hashCode$1 = function (str) { return hashCode(str) + ''; }; + var USERDATA_TABLE = 'userdata'; + var CLS_LOCAL_STORE_NAME = 'localStore'; + var CLS_SESS_STORE_NAME = 'sessionStore'; + var CLS_CONTRACT_NAME = 'contract'; + var CLS_PROFILE_IDX = 'prof_idx'; + var ZERO_IDX = 0; + + /** + * The code was extracted from: + * https://github.com/davidchambers/Base64.js + */ + + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + + function InvalidCharacterError(message) { + this.message = message; + } + + InvalidCharacterError.prototype = new Error(); + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + + function polyfill (input) { + var str = String(input).replace(/=+$/, ''); + if (str.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); + } + for ( + // initialize result and counters + var bc = 0, bs, buffer, idx = 0, output = ''; + // get next character + buffer = str.charAt(idx++); + // character found in table? initialize bit storage and add its ascii value; + ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, + // and if not first of each 4 characters, + // convert the first 8 bits to one ascii character + bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 + ) { + // try to find character in table (0-63, not found => -1) + buffer = chars.indexOf(buffer); + } + return output; + } + + + var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; + + function b64DecodeUnicode(str) { + return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { + var code = p.charCodeAt(0).toString(16).toUpperCase(); + if (code.length < 2) { + code = '0' + code; + } + return '%' + code; + })); + } + + var base64_url_decode = function(str) { + var output = str.replace(/-/g, "+").replace(/_/g, "/"); + switch (output.length % 4) { + case 0: + break; + case 2: + output += "=="; + break; + case 3: + output += "="; + break; + default: + throw "Illegal base64url string!"; + } + + try{ + return b64DecodeUnicode(output); + } catch (err) { + return atob(output); + } + }; + + function InvalidTokenError(message) { + this.message = message; + } + + InvalidTokenError.prototype = new Error(); + InvalidTokenError.prototype.name = 'InvalidTokenError'; + + var lib = function (token,options) { + if (typeof token !== 'string') { + throw new InvalidTokenError('Invalid token specified'); + } + + options = options || {}; + var pos = options.header === true ? 0 : 1; + try { + return JSON.parse(base64_url_decode(token.split('.')[pos])); + } catch (e) { + throw new InvalidTokenError('Invalid token specified: ' + e.message); + } + }; + + var InvalidTokenError_1 = InvalidTokenError; + lib.InvalidTokenError = InvalidTokenError_1; + + // when the user is login with the jwt + + 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 = lib(token); + return validate(t) + } + throw new JsonqlError('Token must be a string!') + } + + var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; + + var appProps = { + algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), + expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), + notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), + audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), + subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), + issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), + noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), + header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), + keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), + mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) + }; + + /** + * @param {boolean} sec return in second or not + * @return {number} timestamp + */ + var timestamp$1 = function (sec) { + if ( sec === void 0 ) sec = false; + + var time = Date.now(); + return sec ? Math.floor( time / 1000 ) : time; + }; + + var assign = make_assign(); + var create = make_create(); + var trim$1 = make_trim(); + var Global = (typeof window !== 'undefined' ? window : commonjsGlobal); + + var util = { + assign: assign, + create: create, + trim: trim$1, + bind: bind, + slice: slice, + each: each, + map: map, + pluck: pluck, + isList: isList, + isFunction: isFunction$1, + isObject: isObject$1, + Global: Global + }; + + function make_assign() { + if (Object.assign) { + return Object.assign + } else { + return function shimAssign(obj, props1, props2, etc) { + var arguments$1 = arguments; + + for (var i = 1; i < arguments.length; i++) { + each(Object(arguments$1[i]), function(val, key) { + obj[key] = val; + }); + } + return obj + } + } + } + + function make_create() { + if (Object.create) { + return function create(obj, assignProps1, assignProps2, etc) { + var assignArgsList = slice(arguments, 1); + return assign.apply(this, [Object.create(obj)].concat(assignArgsList)) + } + } else { + function F() {} // eslint-disable-line no-inner-declarations + return function create(obj, assignProps1, assignProps2, etc) { + var assignArgsList = slice(arguments, 1); + F.prototype = obj; + return assign.apply(this, [new F()].concat(assignArgsList)) + } + } + } + + function make_trim() { + if (String.prototype.trim) { + return function trim(str) { + return String.prototype.trim.call(str) + } + } else { + return function trim(str) { + return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '') + } + } + } + + function bind(obj, fn) { + return function() { + return fn.apply(obj, Array.prototype.slice.call(arguments, 0)) + } + } + + function slice(arr, index) { + return Array.prototype.slice.call(arr, index || 0) + } + + function each(obj, fn) { + pluck(obj, function(val, key) { + fn(val, key); + return false + }); + } + + function map(obj, fn) { + var res = (isList(obj) ? [] : {}); + pluck(obj, function(v, k) { + res[k] = fn(v, k); + return false + }); + return res + } + + function pluck(obj, fn) { + if (isList(obj)) { + for (var i=0; i= 0; i--) { + var key = localStorage().key(i); + fn(read(key), key); + } + } + + function remove(key) { + return localStorage().removeItem(key) + } + + function clearAll() { + return localStorage().clear() + } + + // cookieStorage is useful Safari private browser mode, where localStorage + // doesn't work but cookies do. This implementation is adopted from + // https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage + + + var Global$2 = util.Global; + var trim$2 = util.trim; + + var cookieStorage = { + name: 'cookieStorage', + read: read$1, + write: write$1, + each: each$3, + remove: remove$1, + clearAll: clearAll$1, + }; + + var doc = Global$2.document; + + function read$1(key) { + if (!key || !_has(key)) { return null } + var regexpStr = "(?:^|.*;\\s*)" + + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"; + return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")) + } + + function each$3(callback) { + var cookies = doc.cookie.split(/; ?/g); + for (var i = cookies.length - 1; i >= 0; i--) { + if (!trim$2(cookies[i])) { + continue + } + var kvp = cookies[i].split('='); + var key = unescape(kvp[0]); + var val = unescape(kvp[1]); + callback(val, key); + } + } + + function write$1(key, data) { + if(!key) { return } + doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; + } + + function remove$1(key) { + if (!key || !_has(key)) { + return + } + doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; + } + + function clearAll$1() { + each$3(function(_, key) { + remove$1(key); + }); + } + + function _has(key) { + return (new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie) + } + + var defaults = defaultsPlugin; + + function defaultsPlugin() { + var defaultValues = {}; + + return { + defaults: defaults, + get: get + } + + function defaults(_, values) { + defaultValues = values; + } + + function get(super_fn, key) { + var val = super_fn(); + return (val !== undefined ? val : defaultValues[key]) + } + } + + var bind$2 = util.bind; + var each$4 = util.each; + var create$2 = util.create; + var slice$2 = util.slice; + + var events = eventsPlugin; + + function eventsPlugin() { + var pubsub = _newPubSub(); + + return { + watch: watch, + unwatch: unwatch, + once: once, + + set: set, + remove: remove, + clearAll: clearAll + } + + // new pubsub functions + function watch(_, key, listener) { + return pubsub.on(key, bind$2(this, listener)) + } + function unwatch(_, subId) { + pubsub.off(subId); + } + function once(_, key, listener) { + pubsub.once(key, bind$2(this, listener)); + } + + // overwrite function to fire when appropriate + function set(super_fn, key, val) { + var oldVal = this.get(key); + super_fn(); + pubsub.fire(key, val, oldVal); + } + function remove(super_fn, key) { + var oldVal = this.get(key); + super_fn(); + pubsub.fire(key, undefined, oldVal); + } + function clearAll(super_fn) { + var oldVals = {}; + this.each(function(val, key) { + oldVals[key] = val; + }); + super_fn(); + each$4(oldVals, function(oldVal, key) { + pubsub.fire(key, undefined, oldVal); + }); + } + } + + + function _newPubSub() { + return create$2(_pubSubBase, { + _id: 0, + _subSignals: {}, + _subCallbacks: {} + }) + } + + var _pubSubBase = { + _id: null, + _subCallbacks: null, + _subSignals: null, + on: function(signal, callback) { + if (!this._subCallbacks[signal]) { + this._subCallbacks[signal] = {}; + } + this._id += 1; + this._subCallbacks[signal][this._id] = callback; + this._subSignals[this._id] = signal; + return this._id + }, + off: function(subId) { + var signal = this._subSignals[subId]; + delete this._subCallbacks[signal][subId]; + delete this._subSignals[subId]; + }, + once: function(signal, callback) { + var subId = this.on(signal, bind$2(this, function() { + callback.apply(this, arguments); + this.off(subId); + })); + }, + fire: function(signal) { + var args = slice$2(arguments, 1); + each$4(this._subCallbacks[signal], function(callback) { + callback.apply(this, args); + }); + } + }; + + var lzString = createCommonjsModule(function (module) { + /* eslint-disable */ + // Copyright (c) 2013 Pieroxy + // This work is free. You can redistribute it and/or modify it + // under the terms of the WTFPL, Version 2 + // For more information see LICENSE.txt or http://www.wtfpl.net/ + // + // For more information, the home page: + // http://pieroxy.net/blog/pages/lz-string/testing.html + // + // LZ-based compression algorithm, version 1.4.4 + var LZString = (function() { + + // private property + var f = String.fromCharCode; + var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; + var baseReverseDic = {}; + + function getBaseValue(alphabet, character) { + if (!baseReverseDic[alphabet]) { + baseReverseDic[alphabet] = {}; + for (var i=0 ; i>> 8; + buf[i*2+1] = current_value % 256; + } + return buf; + }, + + //decompress from uint8array (UCS-2 big endian format) + decompressFromUint8Array:function (compressed) { + if (compressed===null || compressed===undefined){ + return LZString.decompress(compressed); + } else { + var buf=new Array(compressed.length/2); // 2 bytes per character + for (var i=0, TotalLen=buf.length; i> 1; + } + } else { + value = 1; + for (i=0 ; i> 1; + } + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + delete context_dictionaryToCreate[context_w]; + } else { + value = context_dictionary[context_w]; + for (i=0 ; i> 1; + } + + + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + // Add wc to the dictionary. + context_dictionary[context_wc] = context_dictSize++; + context_w = String(context_c); + } + } + + // Output the code for w. + if (context_w !== "") { + if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) { + if (context_w.charCodeAt(0)<256) { + for (i=0 ; i> 1; + } + } else { + value = 1; + for (i=0 ; i> 1; + } + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + delete context_dictionaryToCreate[context_w]; + } else { + value = context_dictionary[context_w]; + for (i=0 ; i> 1; + } + + + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + } + + // Mark the end of the stream + value = 2; + for (i=0 ; i> 1; + } + + // Flush the last char + while (true) { + context_data_val = (context_data_val << 1); + if (context_data_position == bitsPerChar-1) { + context_data.push(getCharFromInt(context_data_val)); + break; + } + else { context_data_position++; } + } + return context_data.join(''); + }, + + decompress: function (compressed) { + if (compressed == null) { return ""; } + if (compressed == "") { return null; } + return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); }); + }, + + _decompress: function (length, resetValue, getNextValue) { + var dictionary = [], + next, + enlargeIn = 4, + dictSize = 4, + numBits = 3, + entry = "", + result = [], + i, + w, + bits, resb, maxpower, power, + c, + data = {val:getNextValue(0), position:resetValue, index:1}; + + for (i = 0; i < 3; i += 1) { + dictionary[i] = i; + } + + bits = 0; + maxpower = Math.pow(2,2); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + switch (next = bits) { + case 0: + bits = 0; + maxpower = Math.pow(2,8); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + c = f(bits); + break; + case 1: + bits = 0; + maxpower = Math.pow(2,16); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + c = f(bits); + break; + case 2: + return ""; + } + dictionary[3] = c; + w = c; + result.push(c); + while (true) { + if (data.index > length) { + return ""; + } + + bits = 0; + maxpower = Math.pow(2,numBits); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + switch (c = bits) { + case 0: + bits = 0; + maxpower = Math.pow(2,8); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + dictionary[dictSize++] = f(bits); + c = dictSize-1; + enlargeIn--; + break; + case 1: + bits = 0; + maxpower = Math.pow(2,16); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + dictionary[dictSize++] = f(bits); + c = dictSize-1; + enlargeIn--; + break; + case 2: + return result.join(''); + } + + if (enlargeIn == 0) { + enlargeIn = Math.pow(2, numBits); + numBits++; + } + + if (dictionary[c]) { + entry = dictionary[c]; + } else { + if (c === dictSize) { + entry = w + w.charAt(0); + } else { + return null; + } + } + result.push(entry); + + // Add w+entry[0] to the dictionary. + dictionary[dictSize++] = w + entry.charAt(0); + enlargeIn--; + + w = entry; + + if (enlargeIn == 0) { + enlargeIn = Math.pow(2, numBits); + numBits++; + } + + } + } + }; + return LZString; + })(); + + if( module != null ) { + module.exports = LZString; + } + }); + + var compression = compressionPlugin; + + function compressionPlugin() { + return { + get: get, + set: set, + } + + function get(super_fn, key) { + var val = super_fn(key); + if (!val) { return val } + var decompressed = lzString.decompress(val); + // fallback to existing values that are not compressed + return (decompressed == null) ? val : this._deserialize(decompressed) + } + + function set(super_fn, key, val) { + var compressed = lzString.compress(this._serialize(val)); + super_fn(key, compressed); + } + } + + // sort of persist on the user side + + var storages = [localStorage_1, cookieStorage]; + var plugins = [defaults, events, compression]; + + var localStore = storeEngine.createStore(storages, plugins); + + var Global$3 = util.Global; + + var sessionStorage_1 = { + name: 'sessionStorage', + read: read$2, + write: write$2, + each: each$5, + remove: remove$2, + clearAll: clearAll$2 + }; + + function sessionStorage() { + return Global$3.sessionStorage + } + + function read$2(key) { + return sessionStorage().getItem(key) + } + + function write$2(key, data) { + return sessionStorage().setItem(key, data) + } + + function each$5(fn) { + for (var i = sessionStorage().length - 1; i >= 0; i--) { + var key = sessionStorage().key(i); + fn(read$2(key), key); + } + } + + function remove$2(key) { + return sessionStorage().removeItem(key) + } + + function clearAll$2() { + return sessionStorage().clear() + } + + // session store with watch + // @1.5.0 stop using the expired plugin and deal it ourself + // import expiredPlugin from 'store/plugins/expire' + + var storages$1 = [sessionStorage_1, cookieStorage]; + var plugins$1 = [defaults, compression]; + + var sessionStore = storeEngine.createStore(storages$1, plugins$1); + + // export store interface + + // export back the raw version for development purposes + var localStore$1 = localStore; + var sessionStore$1 = sessionStore; + + // ported from jsonql-params-validator + + /** + * @param {*} args arguments to send + *@return {object} formatted payload + */ + var formatPayload = function (args) { + var obj; + + return ( + ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) + ); + }; + + /** + * Get name from the payload (ported back from jsonql-koa) + * @param {*} payload to extract from + * @return {string} name + */ + function getNameFromPayload(payload) { + return Object.keys(payload)[0] + } + + /** + * wrapper method to add the timestamp as well + * @param {string} resolverName + * @param {*} payload + * @return {object} delierable + */ + function createDeliverable(resolverName, payload) { + var obj; + + return ( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME] = [ timestamp$1() ], obj ) + } + + /** + * @param {string} resolverName name of function + * @param {array} [args=[]] from the ...args + * @param {boolean} [jsonp = false] add v1.3.0 to koa + * @return {object} formatted argument + */ + function createQuery(resolverName, args, jsonp) { + if ( args === void 0 ) args = []; + if ( jsonp === void 0 ) jsonp = false; + + if (isString(resolverName) && isArray(args)) { + var payload = formatPayload(args); + if (jsonp === true) { + return payload; + } + return createDeliverable(resolverName, payload) + } + throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) + } + + /** + * @param {string} resolverName name of function + * @param {*} payload to send + * @param {object} [condition={}] for what + * @param {boolean} [jsonp = false] add v1.3.0 to koa + * @return {object} formatted argument + */ + function createMutation(resolverName, payload, condition, jsonp) { + if ( condition === void 0 ) condition = {}; + if ( jsonp === void 0 ) jsonp = false; + + var _payload = {}; + _payload[PAYLOAD_PARAM_NAME] = payload; + _payload[CONDITION_PARAM_NAME] = condition; + if (jsonp === true) { + return _payload; + } + if (isString(resolverName)) { + return createDeliverable(resolverName, _payload) + } + throw new JsonqlValidationError("[createMutation] expect resolverName to be string!", { resolverName: resolverName, payload: payload, condition: condition }) + } + + /** + * @return {object} _cb as key with timestamp + */ + var cacheBurst = function () { return ({ _cb: timestamp$1() }); }; + + // break up from node-middleware + + // ported from http-client + + /** + * handle the return data + * @TODO how to handle the return timestamp and calculate the diff? + * @param {object} result return from server + * @return {object} strip the data part out, or if the error is presented + */ + var resultHandler = function (result) { return ( + (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result + ); }; + + // new 1.5.0 + + // this becomes the base class instead of the HttpCls + var StoreClass = function StoreClass(opts) { + this.opts = opts; + // make it a string + this.instanceKey = hashCode$1(this.opts.hostname); + // pass this store for use later + this.localStore = localStore$1; + this.sessionStore = sessionStore$1; + /* + if (this.opts.debugOn) { // reuse this to clear out the data + this.log('clear all stores') + localStore.clearAll() + sessionStore.clearAll() + + localStore.set('TEST', Date.now()) + sessionStore.set('TEST', Date.now()) + } + */ + }; + + var prototypeAccessors = { lset: { configurable: true },lget: { configurable: true },sset: { configurable: true },sget: { configurable: true } }; + // store in local storage id by the instanceKey + // values should be an object so with key so we just merge + // into the existing store without going through the keys + StoreClass.prototype.__setMethod = function __setMethod (storeType, values) { + var obj; + + var store = this[storeType]; + var data = this.__getMethod(storeType); + var skey = this.opts.storageKey; + var ikey = this.instanceKey; + store.set(skey, ( obj = {}, obj[ikey] = data ? merge({}, data, values) : values, obj )); + }; + // return the data id by the instaceKey + StoreClass.prototype.__getMethod = function __getMethod (storeType) { + var store = this[storeType]; + var data = store.get(this.opts.storageKey); + return data ? data[this.instanceKey] : false + }; + // remove from local store id by instanceKey + StoreClass.prototype.__delMethod = function __delMethod (storeType, key) { + var data = this.__getMethod(storeType); + if (data) { + var store = {}; + for (var k in data) { + if (k !== key) { + store[k] = data[k]; + } + } + this.__setMethod(storeType, store); + } + }; + // clear everything by this instanceKey + StoreClass.prototype.__clearMethod = function __clearMethod (storeKey) { + var skey = this.opts.storageKey; + var store = this[storeKey]; + var data = store.get(skey); + if (data) { + var _store = {}; + for (var k in data) { + if (k !== this.instanceKey) { + _store[k] = data[k]; + } + } + store.set(skey, _store); + } + }; + // Alias for different store + prototypeAccessors.lset.set = function (values) { + return this.__setMethod(CLS_LOCAL_STORE_NAME, values) + }; + + prototypeAccessors.lget.get = function () { + return this.__getMethod(CLS_LOCAL_STORE_NAME) + }; + + StoreClass.prototype.ldel = function ldel (key) { + return this.__delMethod(CLS_LOCAL_STORE_NAME, key) + }; + + StoreClass.prototype.lclear = function lclear () { + return this.__clearMethod(CLS_LOCAL_STORE_NAME) + }; + + // store in session store id by the instanceKey + prototypeAccessors.sset.set = function (values) { + // this.log('--- sset ---', values) + return this.__setMethod(CLS_SESS_STORE_NAME, values) + }; + + prototypeAccessors.sget.get = function () { + return this.__getMethod(CLS_SESS_STORE_NAME) + }; + + StoreClass.prototype.sdel = function sdel (key) { + return this.__delMethod(CLS_SESS_STORE_NAME, key) + }; + + StoreClass.prototype.sclear = function sclear () { + return this.__clearMethod(CLS_SESS_STORE_NAME) + }; + + Object.defineProperties( StoreClass.prototype, prototypeAccessors ); + + // base HttpClass + /** + * It will ONLY have our own jsonql specific implement check + * @param {object} result the server return result + * @return {object} this will just throw error + */ + function clientErrorsHandler$1(result) { + if (isObjectHasKey(result, 'error')) { + var error = result.error; + var className = error.className; + var name = error.name; + var errorName = className || name; + // just throw the whole thing back + var msg = error.message || NO_ERROR_MSG; + var detail = error.detail || error; + console.info('--- errorName ---', errorName, errors$1); + + if (errorName && errors$1[errorName]) { + throw new errors$1[className](msg, detail) + } + throw new JsonqlError(msg, detail) + } + // pass through to the next + return result; + } + + + + // extract the one we need + var POST = API_REQUEST_METHODS[0]; + var PUT = API_REQUEST_METHODS[1]; + + var HttpClass = /*@__PURE__*/(function (StoreClass) { + function HttpClass(opts) { + StoreClass.call(this, opts); + // change the way how we init Fly + // flyio now become external depedencies and it makes it easier to switch + // @BUG should we run test to check if we have the windows object? + // this.log(opts) + // this.fly = opts.Fly ? new opts.Fly() : new Fly() + // to a different environment like WeChat mini app + + this.extraHeader = {}; + // @1.2.1 for adding query to the call on the fly + this.extraParams = {}; + // this.log('start up opts', opts); + this.reqInterceptor(); + this.resInterceptor(); + } + + if ( StoreClass ) HttpClass.__proto__ = StoreClass; + HttpClass.prototype = Object.create( StoreClass && StoreClass.prototype ); + HttpClass.prototype.constructor = HttpClass; + + var prototypeAccessors = { headers: { configurable: true } }; + + // set headers for that one call + prototypeAccessors.headers.set = function (header) { + this.extraHeader = header; + }; + + /** + * Create the reusage request method + * @param {object} payload jsonql payload + * @param {object} options extra options add the request + * @param {object} headers extra headers add to the call + * @return {object} the fly request instance + */ + HttpClass.prototype.request = function request (payload, options, headers) { + var obj; + + if ( options === void 0 ) options = {}; + if ( headers === void 0 ) headers = {}; + this.headers = headers; + var params = merge({}, cacheBurst(), this.extraParams); + // @TODO need to add a jsonp url and payload + if (this.opts.enableJsonp) { + var resolverName = getNameFromPayload(payload); + params = merge({}, params, ( obj = {}, obj[JSONP_CALLBACK_NAME] = resolverName, obj )); + payload = payload[resolverName]; + } + // double up the url param and see what happen @TODO remove later + var reqParams = merge({}, { method: POST, params: params }, options); + this.log('request params', reqParams, this.jsonqlEndpoint); + + return this.fly.request(this.jsonqlEndpoint, payload, reqParams) + }; + + /** + * This will replace the create baseRequest method + * + */ + HttpClass.prototype.reqInterceptor = function reqInterceptor () { + var this$1 = this; + + this.fly.interceptors.request.use( + function (req) { + var headers = this$1.getHeaders(); + this$1.log('request interceptor call', headers); + + for (var key in headers) { + req.headers[key] = headers[key]; + } + return req; + } + ); + }; + + // @TODO + HttpClass.prototype.processJsonp = function processJsonp (result) { + return resultHandler(result) + }; + + /** + * This will be replacement of the first then call + * + */ + HttpClass.prototype.resInterceptor = function resInterceptor () { + var this$1 = this; + + var self = this; + var jsonp = self.opts.enableJsonp; + this.fly.interceptors.response.use( + function (res) { + this$1.log('response interceptor call', res); + self.cleanUp(); + // now more processing here + // there is a problem if we throw the result.error here + // the original data is lost, so we need to do what we did before + // deal with that error in the first then instead + var result = isString$1(res.data) ? JSON.parse(res.data) : res.data; + if (jsonp) { + return self.processJsonp(result) + } + return resultHandler(result) + }, + // this get call when it's not 200 + function (err) { + self.cleanUp(); + console.error(err); + throw new JsonqlServerError('Server side error', err) + } + ); + }; + + /** + * Get the headers inject into the call + * @return {object} headers + */ + HttpClass.prototype.getHeaders = function getHeaders () { + if (this.opts.enableAuth) { + return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader) + } + return merge({}, DEFAULT_HEADER, this.extraHeader) + }; + + /** + * Post http call operation to clean up things we need + */ + HttpClass.prototype.cleanUp = function cleanUp () { + this.extraHeader = {}; + this.extraParams = {}; + }; + + /** + * GET for contract only + * @return {promise} resolve the contract + */ + HttpClass.prototype.getRemoteContract = function getRemoteContract () { + var this$1 = this; + + if (this.opts.showContractDesc) { + this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM); + } + return this.request({}, {method: 'GET'}, this.contractHeader) + .then(clientErrorsHandler$1) + .then(function (result) { + this$1.log('get contract result', result); + // when refresh the window the result is different! + // @TODO need to check the Koa side about why is that + // also it should set a flag if we want the description or not + if (result.cache && result.contract) { + return result.contract; + } + // just the normal result + return result + }) + .catch(function (err) { + console.error('getRemoteContract err', err); + throw new JsonqlServerError('getRemoteContract', err) + }) + }; + + /** + * POST to server - query + * @param {object} name of the resolver + * @param {array} args arguments + * @return {object} promise resolve to the resolver return + */ + HttpClass.prototype.query = function query (name, args) { + if ( args === void 0 ) args = []; + + return this.request(createQuery(name, args)) + .then(clientErrorsHandler$1) + }; + + /** + * PUT to server - mutation + * @param {string} name of resolver + * @param {object} payload what it said + * @param {object} conditions what it said + * @return {object} promise resolve to the resolver return + */ + HttpClass.prototype.mutation = function mutation (name, payload, conditions) { + if ( payload === void 0 ) payload = {}; + if ( conditions === void 0 ) conditions = {}; + + return this.request(createMutation(name, payload, conditions), {method: PUT}) + .then(clientErrorsHandler$1) + }; + + Object.defineProperties( HttpClass.prototype, prototypeAccessors ); + + return HttpClass; + }(StoreClass)); + + // all the contract related methods will be here + + // export + var ContractClass = /*@__PURE__*/(function (HttpClass) { + function ContractClass(opts) { + HttpClass.call(this, opts); + } + + if ( HttpClass ) ContractClass.__proto__ = HttpClass; + ContractClass.prototype = Object.create( HttpClass && HttpClass.prototype ); + ContractClass.prototype.constructor = ContractClass; + + var prototypeAccessors = { contractHeader: { configurable: true } }; + + /** + * return the contract public api + * @return {object} contract + */ + ContractClass.prototype.getContract = function getContract () { + var contract = this.readContract(); + this.log('getContract first call', contract); + return contract ? Promise.resolve(contract) + : this.getRemoteContract().then(this.storeContract.bind(this)) + }; + + /** + * We are changing the way how to auth to get the contract.json + * Instead of in the url, we will be putting that key value in the header + * @return {object} header + */ + prototypeAccessors.contractHeader.get = function () { + var base = {}; + if (this.opts.contractKey !== false) { + base[this.opts.contractKeyName] = this.opts.contractKey; + } + return base; + }; + + /** + * Save the contract to local store + * @param {object} contract to save + * @return {object|boolean} false when its not a contract or contract on OK + */ + ContractClass.prototype.storeContract = function storeContract (contract) { + var obj; + + // first need to check if the contract is a contract + if (!isContract(contract)) { + throw new JsonqlValidationError("Contract is malformed!") + //return false; + } + /* @TODO need to rethink how to expired the contract + let args = [contract] + if (this.opts.contractExpired) { + let expired = parseFloat(this.opts.contractExpired) + if (!isNaN(expired) && expired > 0) { + args.push(expired) + } + } + // calling the setter + this.jsonqlContract = args; + */ + this.lset = ( obj = {}, obj[CLS_CONTRACT_NAME] = contract, obj ); + // return it + this.log('storeContract return result', contract); + return contract; + }; + + /** + * return the contract from options or localStore + * @return {object|boolean} false on not found + */ + ContractClass.prototype.readContract = function readContract () { + var contract = isContract(this.opts.contract); + if (contract !== false) { + return contract; + } + var data = this.lget; + if (data) { + return data[CLS_CONTRACT_NAME] + } + return false; + }; + + Object.defineProperties( ContractClass.prototype, prototypeAccessors ); + + return ContractClass; + }(HttpClass)); + + // this is the new auth class that integrate with the jsonql-jwt + // export + var AuthClass = /*@__PURE__*/(function (ContractClass) { + function AuthClass(opts) { + ContractClass.call(this, opts); + if (opts.enableAuth) { + this.setDecoder = jwtDecode; + } + } + + if ( ContractClass ) AuthClass.__proto__ = ContractClass; + AuthClass.prototype = Object.create( ContractClass && ContractClass.prototype ); + AuthClass.prototype.constructor = AuthClass; + + var prototypeAccessors = { profileIndex: { configurable: true },setDecoder: { configurable: true },saveProfile: { configurable: true },readProfile: { configurable: true },jsonqlToken: { configurable: true },jsonqlUserdata: { configurable: true } }; + + /** + * for overwrite + * @param {string} token stored token + * @return {string} token + */ + AuthClass.prototype.decoder = function decoder (token) { + return token; + }; + + /** + * set the profile index + * @param {number} idx + */ + prototypeAccessors.profileIndex.set = function (idx) { + var obj; + + var key = CLS_PROFILE_IDX; + if (isNumber$1(idx)) { + this[key] = idx; + if (this.opts.persistToken) { + this.lset = ( obj = {}, obj[key] = idx, obj ); + } + return; + } + throw new JsonqlValidationError('profileIndex', ("Expect idx to be number but got " + (typeof idx))) + }; + + /** + * get the profile index + * @return {number} idx + */ + prototypeAccessors.profileIndex.get = function () { + var key = CLS_PROFILE_IDX; + if (this.opts.persistToken) { + var data = this.lget; + if (data[key]) { + return data[key] + } + } + return this[key] ? this[key] : ZERO_IDX + }; + + /** + * Return the token from session store + * @param {number} [idx=false] profile index + * @return {string} token + */ + AuthClass.prototype.rawAuthToken = function rawAuthToken (idx) { + if ( idx === void 0 ) idx = false; + + if (idx !== false) { + this.profileIndex = idx; + } + // this should return from the base + return this.jsonqlToken; // see base-cls + }; + + /** + * Setter to add a decoder when retrieve user token + * @param {function} d a decoder + */ + prototypeAccessors.setDecoder.set = function (d) { + if (typeof d === 'function') { + this.decoder = d; + } + }; + + /** + * getter to return the session or local store set method + * @param {*} data to save + * @return {object} set method + */ + prototypeAccessors.saveProfile.set = function (data) { + if (this.opts.persistToken) { + // this.log('--- saveProfile lset ---', data) + this.lset = data; + } else { + // this.log('--- saveProfile sset ---', data) + this.sset = data; + } + }; + + /** + * getter to return the session or local store get method + * @return {object} get method + */ + prototypeAccessors.readProfile.get = function () { + return this.opts.persistToken ? this.lget : this.sget + }; + + // these were in the base class before but it should be here + /** + * save token + * @param {string} token to store + * @return {string|boolean} false on failed + */ + prototypeAccessors.jsonqlToken.set = function (token) { + var obj; + + var data = this.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + // @TODO also have to make sure the token is not already existed! + var tokens = (data && data[key]) ? data[key] : []; + tokens.push(token); + this.saveProfile = ( obj = {}, obj[key] = tokens, obj ); + // store the userdata + this.jsonqlUserdata = this.decoder(token); + }; + + /** + * Jsonql token getter + * 1.5.1 each token associate with the same profileIndex + * @return {string|boolean} false when failed + */ + prototypeAccessors.jsonqlToken.get = function () { + var data = this.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + if (data && data[key]) { + this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex]); + return data[key][this.profileIndex] + } + return false + }; + + /** + * this one will use the sessionStore + * basically we hook this onto the token store and decode it to store here + * we only store one decoded user data at a time, but the token can be multiple + */ + prototypeAccessors.jsonqlUserdata.set = function (userdata) { + var obj; + + this.sset = ( obj = {}, obj[USERDATA_TABLE] = userdata, obj ); + }; + + /** + * this one store in the session store + * get login userdata decoded jwt + * 1.5.1 each userdata associate with the same profileIndex + * @return {object|null} + */ + prototypeAccessors.jsonqlUserdata.get = function () { + var data = this.sget; + return data ? data[USERDATA_TABLE] : false + }; + + /** + * Construct the auth header + * @return {object} header + */ + AuthClass.prototype.getAuthHeader = function getAuthHeader () { + var obj; + + var token = this.jsonqlToken; // only call the getter to get the default one + return token ? ( obj = {}, obj[this.opts.AUTH_HEADER] = (BEARER + " " + token), obj ) : {}; + }; + + /** + * return all the stored token and decode it + * @param {number} [idx=false] profile index + * @return {array|boolean|string} false not found or array + */ + AuthClass.prototype.getProfiles = function getProfiles (idx) { + if ( idx === void 0 ) idx = false; + + var self = this; // just in case the scope problem + var data = self.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + if (data && data[key]) { + if (idx !== false && isNumber$1(idx)) { + return data[key][idx] || false + } + return data[key].map(self.decoder.bind(self)) + } + return false + }; + + /** + * call after the login + * @param {string} token return from server + * @return {object} decoded token to userdata object + */ + AuthClass.prototype.postLoginAction = function postLoginAction (token) { + this.jsonqlToken = token; + return token + }; + + /** + * call after the logout @TODO + */ + AuthClass.prototype.postLogoutAction = function postLogoutAction () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + console.info("postLogoutAction", args); + }; + + Object.defineProperties( AuthClass.prototype, prototypeAccessors ); + + return AuthClass; + }(ContractClass)); + + // this the core of the internal storage management + + // This class will only focus on the storage system + var JsonqlBaseClient = /*@__PURE__*/(function (AuthCls) { + function JsonqlBaseClient(fly, opts) { + // change at 1.4.10 pass it directly without init it + this.fly = fly; + AuthCls.call(this, opts); + } + + if ( AuthCls ) JsonqlBaseClient.__proto__ = AuthCls; + JsonqlBaseClient.prototype = Object.create( AuthCls && AuthCls.prototype ); + JsonqlBaseClient.prototype.constructor = JsonqlBaseClient; + + var prototypeAccessors = { jsonqlEndpoint: { configurable: true } }; + + /** + * construct the end point + * @return {string} the end point to call + */ + prototypeAccessors.jsonqlEndpoint.get = function () { + var baseUrl = this.opts.hostname || ''; + return [baseUrl, this.opts.jsonqlPath].join('/') + }; + + /** + * simple log + */ + JsonqlBaseClient.prototype.log = function log () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (this.opts.debugOn === true) { + Reflect.apply(console.info, console, args); + } + }; + + Object.defineProperties( JsonqlBaseClient.prototype, prototypeAccessors ); + + return JsonqlBaseClient; + }(AuthClass)); + + // export interface + + // all the client configuration options here + var constProps = { + contract: false, + MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong? + CONTENT_TYPE: CONTENT_TYPE, + BEARER: BEARER, + AUTH_HEADER: AUTH_HEADER + }; + + // grab the localhost name and put into the hostname as default + var getHostName = function () { + try { + return [window.location.protocol, window.location.host].join('//') + } catch(e) { + return null + } + }; + + var appProps$1 = { + + hostname: createConfig$1(getHostName(), [STRING_TYPE]), // required the hostname + jsonqlPath: createConfig$1(JSONQL_PATH, [STRING_TYPE]), // The path on the server + + loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), + logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), + // add to koa v1.3.0 - this might remove in the future + enableJsonp: createConfig$1(false, [BOOLEAN_TYPE]), + enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), + // enable useJwt by default @TODO replace with something else and remove them later + useJwt: createConfig$1(true, [BOOLEAN_TYPE]), + // when true then store infinity or pass a time in seconds then we check against + // the token date of creation + persistToken: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE]), + // the header + // v1.2.0 we are using this option during the dev + // so it won't save anything to the localstorage and fetch a new contract + // whenever the browser reload + useLocalstorage: createConfig$1(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage + storageKey: createConfig$1(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage + authKey: createConfig$1(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage + contractExpired: createConfig$1(0, [NUMBER_TYPE]),// -1 always fetch contract, + // 0 never expired, + // > 0 then compare the timestamp with the current one to see if we need to get contract again + // useful during development + keepContract: createConfig$1(true, [BOOLEAN_TYPE]), + exposeContract: createConfig$1(false, [BOOLEAN_TYPE]), + exposeStore: createConfig$1(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn + // @1.2.1 new option for the contract-console to fetch the contract with description + showContractDesc: createConfig$1(false, [BOOLEAN_TYPE]), + contractKey: createConfig$1(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this + contractKeyName: createConfig$1(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs + enableTimeout: createConfig$1(false, [BOOLEAN_TYPE]), // @TODO + timeout: createConfig$1(5000, [NUMBER_TYPE]), // 5 seconds + returnInstance: createConfig$1(false, [BOOLEAN_TYPE]), + allowReturnRawToken: createConfig$1(false, [BOOLEAN_TYPE]), + debugOn: createConfig$1(false, [BOOLEAN_TYPE]) + }; + + // This is for the sync version therefore we don't need to care about the contract options + + function checkOptions(config) { + return checkConfig$1(config, appProps$1, constProps) + } + + // export interface + + // sync version without needing the promise + function checkOptions$1(config) { + return objHasProp(config, CHECKED_KEY) ? config : checkOptions(config) + } + + var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); + var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); + + // making all the functionality on it's own + // import { WatchClass } from './watch' + + var SuspendClass = function SuspendClass() { + // suspend, release and queue + this.__suspend__ = null; + this.queueStore = new Set(); + /* + this.watch('suspend', function(value, prop, oldValue) { + this.logger(`${prop} set from ${oldValue} to ${value}`) + // it means it set the suspend = true then release it + if (oldValue === true && value === false) { + // we want this happen after the return happens + setTimeout(() => { + this.release() + }, 1) + } + return value; // we need to return the value to store it + }) + */ + }; + + var prototypeAccessors$1 = { $suspend: { configurable: true },$queues: { configurable: true } }; + + /** + * setter to set the suspend and check if it's boolean value + * @param {boolean} value to trigger + */ + prototypeAccessors$1.$suspend.set = function (value) { + var this$1 = this; + + if (typeof value === 'boolean') { + var lastValue = this.__suspend__; + this.__suspend__ = value; + this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); + if (lastValue === true && value === false) { + setTimeout(function () { + this$1.release(); + }, 1); + } + } else { + throw new Error("$suspend only accept Boolean value!") + } + }; + + /** + * queuing call up when it's in suspend mode + * @param {any} value + * @return {Boolean} true when added or false when it's not + */ + SuspendClass.prototype.$queue = function $queue () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (this.__suspend__ === true) { + this.logger('($queue)', 'added to $queue', args); + // there shouldn't be any duplicate ... + this.queueStore.add(args); + } + return this.__suspend__; + }; + + /** + * a getter to get all the store queue + * @return {array} Set turn into Array before return + */ + prototypeAccessors$1.$queues.get = function () { + var size = this.queueStore.size; + this.logger('($queues)', ("size: " + size)); + if (size > 0) { + return Array.from(this.queueStore) + } + return [] + }; + + /** + * Release the queue + * @return {int} size if any + */ + SuspendClass.prototype.release = function release () { + var this$1 = this; + + var size = this.queueStore.size; + this.logger('(release)', ("Release was called " + size)); + if (size > 0) { + var queue = Array.from(this.queueStore); + this.queueStore.clear(); + this.logger('queue', queue); + queue.forEach(function (args) { + this$1.logger(args); + Reflect.apply(this$1.$trigger, this$1, args); + }); + this.logger(("Release size " + (this.queueStore.size))); + } + }; + + Object.defineProperties( SuspendClass.prototype, prototypeAccessors$1 ); + + // break up the main file because its getting way too long + + var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { + function NbEventServiceBase(config) { + if ( config === void 0 ) config = {}; + + SuspendClass.call(this); + if (config.logger && typeof config.logger === 'function') { + this.logger = config.logger; + } + this.keep = config.keep; + // for the $done setter + this.result = config.keep ? [] : null; + // we need to init the store first otherwise it could be a lot of checking later + this.normalStore = new Map(); + this.lazyStore = new Map(); + } + + if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; + NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); + NbEventServiceBase.prototype.constructor = NbEventServiceBase; + + var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; + + /** + * validate the event name(s) + * @param {string[]} evt event name + * @return {boolean} true when OK + */ + NbEventServiceBase.prototype.validateEvt = function validateEvt () { + var this$1 = this; + var evt = [], len = arguments.length; + while ( len-- ) evt[ len ] = arguments[ len ]; + + evt.forEach(function (e) { + if (typeof e !== 'string') { + this$1.logger('(validateEvt)', e); + throw new Error("event name must be string type!") + } + }); + return true; + }; + + /** + * Simple quick check on the two main parameters + * @param {string} evt event name + * @param {function} callback function to call + * @return {boolean} true when OK + */ + NbEventServiceBase.prototype.validate = function validate (evt, callback) { + if (this.validateEvt(evt)) { + if (typeof callback === 'function') { + return true; + } + } + throw new Error("callback required to be function type!") + }; + + /** + * Check if this type is correct or not added in V1.5.0 + * @param {string} type for checking + * @return {boolean} true on OK + */ + NbEventServiceBase.prototype.validateType = function validateType (type) { + var types = ['on', 'only', 'once', 'onlyOnce']; + return !!types.filter(function (t) { return type === t; }).length; + }; + + /** + * Run the callback + * @param {function} callback function to execute + * @param {array} payload for callback + * @param {object} ctx context or null + * @return {void} the result store in $done + */ + NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { + this.logger('(run)', callback, payload, ctx); + this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); + }; + + /** + * Take the content out and remove it from store id by the name + * @param {string} evt event name + * @param {string} [storeName = lazyStore] name of store + * @return {object|boolean} content or false on not found + */ + NbEventServiceBase.prototype.takeFromStore = function takeFromStore (evt, storeName) { + if ( storeName === void 0 ) storeName = 'lazyStore'; + + var store = this[storeName]; // it could be empty at this point + if (store) { + this.logger('(takeFromStore)', storeName, store); + if (store.has(evt)) { + var content = store.get(evt); + this.logger('(takeFromStore)', ("has " + evt), content); + store.delete(evt); + return content; + } + return false; + } + throw new Error((storeName + " is not supported!")) + }; + + /** + * The add to store step is similar so make it generic for resuse + * @param {object} store which store to use + * @param {string} evt event name + * @param {spread} args because the lazy store and normal store store different things + * @return {array} store and the size of the store + */ + NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { + var args = [], len = arguments.length - 2; + while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; + + var fnSet; + if (store.has(evt)) { + this.logger('(addToStore)', (evt + " existed")); + fnSet = store.get(evt); + } else { + this.logger('(addToStore)', ("create new Set for " + evt)); + // this is new + fnSet = new Set(); + } + // lazy only store 2 items - this is not the case in V1.6.0 anymore + // we need to check the first parameter is string or not + if (args.length > 2) { + if (Array.isArray(args[0])) { // lazy store + // check if this type of this event already register in the lazy store + var t = args[2]; + if (!this.checkTypeInLazyStore(evt, t)) { + fnSet.add(args); + } + } else { + if (!this.checkContentExist(args, fnSet)) { + this.logger('(addToStore)', "insert new", args); + fnSet.add(args); + } + } + } else { // add straight to lazy store + fnSet.add(args); + } + store.set(evt, fnSet); + return [store, fnSet.size] + }; + + /** + * @param {array} args for compare + * @param {object} fnSet A Set to search from + * @return {boolean} true on exist + */ + NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { + var list = Array.from(fnSet); + return !!list.filter(function (l) { + var hash = l[0]; + if (hash === args[0]) { + return true; + } + return false; + }).length; + }; + + /** + * get the existing type to make sure no mix type add to the same store + * @param {string} evtName event name + * @param {string} type the type to check + * @return {boolean} true you can add, false then you can't add this type + */ + NbEventServiceBase.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { + this.validateEvt(evtName, type); + var all = this.$get(evtName, true); + if (all === false) { + // pristine it means you can add + return true; + } + // it should only have ONE type in ONE event store + return !all.filter(function (list) { + var t = list[3]; + return type !== t; + }).length; + }; + + /** + * This is checking just the lazy store because the structure is different + * therefore we need to use a new method to check it + */ + NbEventServiceBase.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { + this.validateEvt(evtName, type); + var store = this.lazyStore.get(evtName); + this.logger('(checkTypeInLazyStore)', store); + if (store) { + return !!Array + .from(store) + .filter(function (l) { + var t = l[2]; + return t !== type; + }).length + } + return false; + }; + + /** + * wrapper to re-use the addToStore, + * V1.3.0 add extra check to see if this type can add to this evt + * @param {string} evt event name + * @param {string} type on or once + * @param {function} callback function + * @param {object} context the context the function execute in or null + * @return {number} size of the store + */ + NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { + if ( context === void 0 ) context = null; + + this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); + // @TODO we need to check the existing store for the type first! + if (this.checkTypeInStore(evt, type)) { + this.logger('(addToNormalStore)', (type + " can add to " + evt + " normal store")); + var key = this.hashFnToKey(callback); + var args = [this.normalStore, evt, key, callback, context, type]; + var ref = Reflect.apply(this.addToStore, this, args); + var _store = ref[0]; + var size = ref[1]; + this.normalStore = _store; + return size; + } + return false; + }; + + /** + * Add to lazy store this get calls when the callback is not register yet + * so we only get a payload object or even nothing + * @param {string} evt event name + * @param {array} payload of arguments or empty if there is none + * @param {object} [context=null] the context the callback execute in + * @param {string} [type=false] register a type so no other type can add to this evt + * @return {number} size of the store + */ + NbEventServiceBase.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { + if ( payload === void 0 ) payload = []; + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = false; + + // this is add in V1.6.0 + // when there is type then we will need to check if this already added in lazy store + // and no other type can add to this lazy store + var args = [this.lazyStore, evt, this.toArray(payload), context]; + if (type) { + args.push(type); + } + var ref = Reflect.apply(this.addToStore, this, args); + var _store = ref[0]; + var size = ref[1]; + this.lazyStore = _store; + return size; + }; + + /** + * make sure we store the argument correctly + * @param {*} arg could be array + * @return {array} make sured + */ + NbEventServiceBase.prototype.toArray = function toArray (arg) { + return Array.isArray(arg) ? arg : [arg]; + }; + + /** + * setter to store the Set in private + * @param {object} obj a Set + */ + prototypeAccessors.normalStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); + }; + + /** + * @return {object} Set object + */ + prototypeAccessors.normalStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) + }; + + /** + * setter to store the Set in lazy store + * @param {object} obj a Set + */ + prototypeAccessors.lazyStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); + }; + + /** + * @return {object} the lazy store Set + */ + prototypeAccessors.lazyStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) + }; + + /** + * generate a hashKey to identify the function call + * The build-in store some how could store the same values! + * @param {function} fn the converted to string function + * @return {string} hashKey + */ + NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { + return hashCode(fn.toString()) + ''; + }; + + Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); + + return NbEventServiceBase; + }(SuspendClass)); + + // The top level + // export + var EventService = /*@__PURE__*/(function (NbStoreService) { + function EventService(config) { + if ( config === void 0 ) config = {}; + + NbStoreService.call(this, config); + } + + if ( NbStoreService ) EventService.__proto__ = NbStoreService; + EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); + EventService.prototype.constructor = EventService; + + var prototypeAccessors = { $done: { configurable: true } }; + + /** + * logger function for overwrite + */ + EventService.prototype.logger = function logger () {}; + + ////////////////////////// + // PUBLIC METHODS // + ////////////////////////// + + /** + * Register your evt handler, note we don't check the type here, + * we expect you to be sensible and know what you are doing. + * @param {string} evt name of event + * @param {function} callback bind method --> if it's array or not + * @param {object} [context=null] to execute this call in + * @return {number} the size of the store + */ + EventService.prototype.$on = function $on (evt , callback , context) { + var this$1 = this; + if ( context === void 0 ) context = null; + + var type = 'on'; + this.validate(evt, callback); + // first need to check if this evt is in lazy store + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register first then call later + if (lazyStoreContent === false) { + this.logger('($on)', (evt + " callback is not in lazy store")); + // @TODO we need to check if there was other listener to this + // event and are they the same type then we could solve that + // register the different type to the same event name + + return this.addToNormalStore(evt, type, callback, context) + } + this.logger('($on)', (evt + " found in lazy store")); + // this is when they call $trigger before register this callback + var size = 0; + lazyStoreContent.forEach(function (content) { + var payload = content[0]; + var ctx = content[1]; + var t = content[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this$1.logger("($on)", ("call run on " + evt)); + this$1.run(callback, payload, context || ctx); + size += this$1.addToNormalStore(evt, type, callback, context || ctx); + }); + return size; + }; + + /** + * once only registered it once, there is no overwrite option here + * @NOTE change in v1.3.0 $once can add multiple listeners + * but once the event fired, it will remove this event (see $only) + * @param {string} evt name + * @param {function} callback to execute + * @param {object} [context=null] the handler execute in + * @return {boolean} result + */ + EventService.prototype.$once = function $once (evt , callback , context) { + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'once'; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (lazyStoreContent === false) { + this.logger('($once)', (evt + " not in the lazy store")); + // v1.3.0 $once now allow to add multiple listeners + return this.addToNormalStore(evt, type, callback, context) + } else { + // now this is the tricky bit + // there is a potential bug here that cause by the developer + // if they call $trigger first, the lazy won't know it's a once call + // so if in the middle they register any call with the same evt name + // then this $once call will be fucked - add this to the documentation + this.logger('($once)', lazyStoreContent); + var list = Array.from(lazyStoreContent); + // should never have more than 1 + var ref = list[0]; + var payload = ref[0]; + var ctx = ref[1]; + var t = ref[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this.logger('($once)', ("call run for " + evt)); + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); + } + }; + + /** + * This one event can only bind one callbackback + * @param {string} evt event name + * @param {function} callback event handler + * @param {object} [context=null] the context the event handler execute in + * @return {boolean} true bind for first time, false already existed + */ + EventService.prototype.$only = function $only (evt, callback, context) { + var this$1 = this; + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'only'; + var added = false; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (!nStore.has(evt)) { + this.logger("($only)", (evt + " add to store")); + added = this.addToNormalStore(evt, type, callback, context); + } + if (lazyStoreContent !== false) { + // there are data store in lazy store + this.logger('($only)', (evt + " found data in lazy store to execute")); + var list = Array.from(lazyStoreContent); + // $only allow to trigger this multiple time on the single handler + list.forEach( function (l) { + var payload = l[0]; + var ctx = l[1]; + var t = l[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this$1.logger("($only)", ("call run for " + evt)); + this$1.run(callback, payload, context || ctx); + }); + } + return added; + }; + + /** + * $only + $once this is because I found a very subtile bug when we pass a + * resolver, rejecter - and it never fire because that's OLD added in v1.4.0 + * @param {string} evt event name + * @param {function} callback to call later + * @param {object} [context=null] exeucte context + * @return {void} + */ + EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'onlyOnce'; + var added = false; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (!nStore.has(evt)) { + this.logger("($onlyOnce)", (evt + " add to store")); + added = this.addToNormalStore(evt, type, callback, context); + } + if (lazyStoreContent !== false) { + // there are data store in lazy store + this.logger('($onlyOnce)', lazyStoreContent); + var list = Array.from(lazyStoreContent); + // should never have more than 1 + var ref = list[0]; + var payload = ref[0]; + var ctx = ref[1]; + var t = ref[2]; + if (t && t !== 'onlyOnce') { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this.logger("($onlyOnce)", ("call run for " + evt)); + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); + } + return added; + }; + + /** + * This is a shorthand of $off + $on added in V1.5.0 + * @param {string} evt event name + * @param {function} callback to exeucte + * @param {object} [context = null] or pass a string as type + * @param {string} [type=on] what type of method to replace + * @return {} + */ + EventService.prototype.$replace = function $replace (evt, callback, context, type) { + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = 'on'; + + if (this.validateType(type)) { + this.$off(evt); + var method = this['$' + type]; + this.logger("($replace)", evt, callback); + return Reflect.apply(method, this, [evt, callback, context]) + } + throw new Error((type + " is not supported!")) + }; + + /** + * trigger the event + * @param {string} evt name NOT allow array anymore! + * @param {mixed} [payload = []] pass to fn + * @param {object|string} [context = null] overwrite what stored + * @param {string} [type=false] if pass this then we need to add type to store too + * @return {number} if it has been execute how many times + */ + EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { + if ( payload === void 0 ) payload = []; + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = false; + + this.validateEvt(evt); + var found = 0; + // first check the normal store + var nStore = this.normalStore; + this.logger('($trigger)', 'normalStore', nStore); + if (nStore.has(evt)) { + // @1.8.0 to add the suspend queue + var added = this.$queue(evt, payload, context, type); + this.logger('($trigger)', evt, 'found; add to queue: ', added); + if (added === true) { + this.logger('($trigger)', evt, 'not executed. Exit now.'); + return false; // not executed + } + var nSet = Array.from(nStore.get(evt)); + var ctn = nSet.length; + var hasOnce = false; + for (var i=0; i < ctn; ++i) { + ++found; + // this.logger('found', found) + var ref = nSet[i]; + var _ = ref[0]; + var callback = ref[1]; + var ctx = ref[2]; + var type$1 = ref[3]; + this.logger("($trigger)", ("call run for " + evt)); + this.run(callback, payload, context || ctx); + if (type$1 === 'once' || type$1 === 'onlyOnce') { + hasOnce = true; + } + } + if (hasOnce) { + nStore.delete(evt); + } + return found; + } + // now this is not register yet + this.addToLazyStore(evt, payload, context, type); + return found; + }; + + /** + * this is an alias to the $trigger + * @NOTE breaking change in V1.6.0 we swap the parameter around + * @param {string} evt event name + * @param {*} params pass to the callback + * @param {string} type of call + * @param {object} context what context callback execute in + * @return {*} from $trigger + */ + EventService.prototype.$call = function $call (evt, params, type, context) { + if ( type === void 0 ) type = false; + if ( context === void 0 ) context = null; + + var args = [evt, params, context, type]; + return Reflect.apply(this.$trigger, this, args) + }; + + /** + * remove the evt from all the stores + * @param {string} evt name + * @return {boolean} true actually delete something + */ + EventService.prototype.$off = function $off (evt) { + var this$1 = this; + + this.validateEvt(evt); + var stores = [ this.lazyStore, this.normalStore ]; + var found = false; + stores.forEach(function (store) { + if (store.has(evt)) { + found = true; + this$1.logger('($off)', evt); + store.delete(evt); + } + }); + return found; + }; + + /** + * return all the listener from the event + * @param {string} evtName event name + * @param {boolean} [full=false] if true then return the entire content + * @return {array|boolean} listerner(s) or false when not found + */ + EventService.prototype.$get = function $get (evt, full) { + if ( full === void 0 ) full = false; + + this.validateEvt(evt); + var store = this.normalStore; + if (store.has(evt)) { + return Array + .from(store.get(evt)) + .map( function (l) { + if (full) { + return l; + } + var key = l[0]; + var callback = l[1]; + return callback; + }) + } + return false; + }; + + /** + * store the return result from the run + * @param {*} value whatever return from callback + */ + prototypeAccessors.$done.set = function (value) { + this.logger('($done)', 'value: ', value); + if (this.keep) { + this.result.push(value); + } else { + this.result = value; + } + }; + + /** + * @TODO is there any real use with the keep prop? + * getter for $done + * @return {*} whatever last store result + */ + prototypeAccessors.$done.get = function () { + if (this.keep) { + this.logger('(get $done)', this.result); + return this.result[this.result.length - 1] + } + return this.result; + }; + + Object.defineProperties( EventService.prototype, prototypeAccessors ); + + return EventService; + }(NbEventServiceBase)); + + // default + + // this will generate a event emitter and will be use everywhere + // output + function getEventEmitter(debugOn) { + var logger = debugOn ? function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + args.unshift('[NBS]'); + console.log.apply(null, args); + }: undefined; + return new EventService({ logger: logger }) + } + + // this is the new Event base interface + /** + * this is the slim client without Fly, you pick the version of Fly to use + * This is a breaking change because it swap the input positions + * @param {object} fly fly.js + * @param {object} config configuration + * @return {object} the jsonql client instance + */ + function jsonqlStaticClient(fly, config) { + if ( config === void 0 ) config = {}; + + var contract = config.contract; + var opts = checkOptions$1(config); + var jsonqlBase = new JsonqlBaseClient(fly, opts); + var contractPromise = getContractFromConfig(jsonqlBase, contract); + var ee = getEventEmitter(opts.debugOn); + // finally + var methods = generator(jsonqlBase, opts, contractPromise, ee); + methods.eventEmitter = ee; + return methods; + } + + // This is the static version that build with the Fly for Browser + + // this is the slim client without Fly + function jsonqlStaticClientFull(config) { + if ( config === void 0 ) config = {}; + + return jsonqlStaticClient(new Fly(), config) + } + + return jsonqlStaticClientFull; + +}))); //# sourceMappingURL=jsonql-client.static.js.map diff --git a/packages/http-client/dist/jsonql-client.static.js.map b/packages/http-client/dist/jsonql-client.static.js.map index 04d47b5f..0d1c3e77 100644 --- a/packages/http-client/dist/jsonql-client.static.js.map +++ b/packages/http-client/dist/jsonql-client.static.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client.static.js","sources":["../node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"ikiDAAA"} \ No newline at end of file +{"version":3,"file":"jsonql-client.static.js","sources":["../node_modules/lodash-es/isArray.js","../node_modules/rollup-plugin-node-globals/src/global.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/lodash-es/_arrayMap.js","../node_modules/lodash-es/_baseSlice.js","../node_modules/lodash-es/_baseFindIndex.js","../node_modules/lodash-es/_baseIsNaN.js","../node_modules/lodash-es/_strictIndexOf.js","../node_modules/lodash-es/_asciiToArray.js","../node_modules/lodash-es/_hasUnicode.js","../node_modules/lodash-es/_unicodeToArray.js","../node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-errors/src/get-error-by-status.js","../node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-errors/src/resolver-not-found-error.js","../node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-errors/src/index.js","../node_modules/jsonql-errors/src/client-errors-handler.js","../node_modules/jsonql-errors/src/get-error-name-by-instance.js","../node_modules/jsonql-errors/index.js","../node_modules/jsonql-params-validator/src/number.js","../node_modules/jsonql-params-validator/src/string.js","../node_modules/jsonql-params-validator/src/boolean.js","../node_modules/jsonql-params-validator/src/any.js","../node_modules/jsonql-params-validator/src/constants.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/_listCacheClear.js","../node_modules/lodash-es/eq.js","../node_modules/lodash-es/_stackDelete.js","../node_modules/lodash-es/_stackGet.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-params-validator/src/validator.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/negate.js","../node_modules/lodash-es/_baseFindKey.js","../node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-params-validator/src/options/check-options-sync.js","../node_modules/jsonql-params-validator/src/options/construct-config.js","../node_modules/jsonql-params-validator/src/options/index.js","../node_modules/jsonql-params-validator/index.js","../src/core/methods-generator.js","../src/core/jsonql-static-generator.js","../node_modules/jsonql-utils/src/contract.js","../node_modules/nb-event-service/src/hash-code.js","../src/utils.js","../node_modules/jwt-decode/lib/atob.js","../node_modules/jsonql-jwt/src/client/decode-token/decode-token.js","../node_modules/jsonql-utils/src/timestamp.js","../node_modules/store/plugins/defaults.js","../src/stores/local-store.js","../src/stores/session-store.js","../src/stores/index.js","../node_modules/jsonql-utils/src/params-api.js","../node_modules/jsonql-utils/src/results.js","../src/base/store-cls.js","../src/base/http-cls.js","../src/base/contract-cls.js","../src/base/auth-cls.js","../src/base/base-cls.js","../src/base/index.js","../src/options/base-options.js","../src/options/check-options.js","../src/options/index.js","../node_modules/nb-event-service/src/suspend.js","../node_modules/nb-event-service/src/store-service.js","../node_modules/nb-event-service/src/event-service.js","../node_modules/nb-event-service/index.js","../src/ee.js","../src/static.js","../src/static-full.js"],"sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length;\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg];\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @return {*} json object on success\n */\nconst parse = function(n) {\n try {\n return JSON.parse(n)\n } catch(e) {\n return n;\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false;\n /*\n console.info('obj', obj)\n console.error(e)\n throw new Error(e)\n */\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = (n) => {\n if (typeof n === 'string') {\n return parse(n)\n }\n return JSON.parse(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== '';\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n","// just a simple util method to return the error based on the status code\n/**\n * @param {number} statusCode to check\n * @param {boolean} contract if this is a contract call or not\n * @return {string} the error name\n */\nexport default function getErrorByStatus(statusCode, contract = false) {\n switch (statusCode) {\n case 401:\n return contract ? 'JsonqlContractAuthError' : 'JsonqlAuthorisationError';\n case 403:\n return 'JsonqlForbiddenError';\n case 404:\n return 'JsonqlResolverNotFoundError';\n case 406:\n return 'Jsonql406Error';\n case 500:\n return 'Jsonql500Error';\n default:\n return 'JsonqlError';\n }\n}\n","/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error)\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","/**\n * This is a custom error to throw when could not find the resolver\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class JsonqlResolverNotFoundError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlResolverNotFoundError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlResolverNotFoundError);\n }\n }\n\n static get statusCode() {\n return 404;\n }\n\n static get name() {\n return 'JsonqlResolverNotFoundError';\n }\n}\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError);\n }\n }\n\n static get name() {\n return 'JsonqlEnumError';\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlTypeError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError);\n }\n }\n\n static get name() {\n return 'JsonqlTypeError';\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args)\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError)\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError';\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError';\n }\n}\n","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message)\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// server side\nimport Jsonql406Error from './406-error';\nimport Jsonql500Error from './500-error';\nimport JsonqlAuthorisationError from './authorisation-error';\nimport JsonqlContractAuthError from './contract-auth-error';\nimport JsonqlResolverAppError from './resolver-app-error';\nimport JsonqlResolverNotFoundError from './resolver-not-found-error';\n\n// check options error\nimport JsonqlEnumError from './enum-error';\nimport JsonqlTypeError from './type-error';\nimport JsonqlCheckerError from './checker-error';\n// share\nimport JsonqlValidationError from './validation-error';\nimport JsonqlError from './error';\n\nimport JsonqlServerError from './server-error';\n\nexport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n};\n","// this will add directly to the then call in each http call\n\nimport * as errors from './index';\nimport getErrorByStatus from './get-error-by-status';\nimport { NO_ERROR_MSG } from 'jsonql-constants';\nconst { JsonqlError } = errors;\n\n/**\n * We can not just check something like result.data what if the result if false?\n * @param {object} obj the result object\n * @param {string} key we want to check if its exist or not\n * @return {boolean} true on found\n */\nconst isObjectHasKey = (obj, key) => {\n const keys = Object.keys(obj)\n return !!keys.filter(k => key === k).length;\n}\n\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nexport default function clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n","// get error name by instance\nconst UNKNOWN_ERROR = 'unknown'\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {array} filtered with name as value\n */\nfunction mapErrToName(errs, e) {\n return errs.filter(err => e instanceof err)\n .map(err => err.name)\n}\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {string} name of the error object\n */\nfunction getErrorNameByInstance(errs, e) {\n let error = mapErrToName(errs, e)\n return error.length ? error[0] : UNKNOWN_ERROR\n}\n\n/**\n * the same as above with a default JsonqlError as default\n * @param {array} errs same\n * @param {object} e error itself\n * @return {string} the name of the error\n */\nfunction getErrorNameByInstanceWithDefault(errs, e) {\n let name = getErrorNameByInstance(errs, e)\n return name === UNKNOWN_ERROR ? 'JsonqlError' : name;\n}\n\n\nexport {\n getErrorNameByInstanceWithDefault,\n getErrorNameByInstance,\n UNKNOWN_ERROR\n}\n","// jsonql-errors main interface\nimport getErrorByStatus from './src/get-error-by-status'\nimport clientErrorsHandler from './src/client-errors-handler'\nimport {\n getErrorNameByInstance,\n getErrorNameByInstanceWithDefault,\n UNKNOWN_ERROR\n} from './src/get-error-name-by-instance'\nimport finalCatch from './src/final-catch.js'\nconst JSONQL_ERRORS_INFO = '__PLACEHOLDER__'\nimport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n JsonqlValidationError,\n JsonqlError,\n JsonqlServerError\n} from './src'\n// export\nexport {\n JSONQL_ERRORS_INFO,\n UNKNOWN_ERROR,\n\n getErrorByStatus,\n clientErrorsHandler,\n finalCatch,\n getErrorNameByInstance,\n getErrorNameByInstanceWithDefault,\n\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n}\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false;\n}\n\nexport default checkIsString\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nexport const ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\n","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber;\n case STRING_TYPE:\n return checkIsString;\n case BOOLEAN_TYPE:\n return checkIsBoolean;\n default:\n return checkIsAny;\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false;\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false;\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p;\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length;\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length;\n}\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport filter from 'lodash-es/filter'\n\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true;\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (_value !== undefined) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true;\n }).length)\n }).length;\n }\n }\n return false;\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p;\n let _args = [arg];\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return Reflect.apply(checkIsObject, null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\n\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n checkIsObject,\n combineFn,\n notEmpty\n} from './index'\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params;\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false;\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (arg !== undefined) {\n return arg;\n }\n return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ))\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ))\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ))\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length:\n let ctn = params.length;\n // this happens when we have those array. type\n let _type = [ DEFAULT_TYPE ]\n // we only looking at the first one, this might be a @BUG\n /*\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n } */\n // if we use the params as guide then the rest will get throw out\n // which is not what we want, instead, anything without the param\n // will get a any type and optional flag\n return args.map((arg, i) => {\n let optional = i >= ctn ? true : !!params[i].optional\n let param = params[i] || { type: _type, name: `_${i}` }\n return {\n arg: optional ? getOptionalValue(arg, param) : arg,\n index: i,\n param,\n optional\n }\n })\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n // v1.4.4 this fixed the problem, the root level optional is from the last fn\n if (p.optional === true || p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length;\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport isFunction from 'lodash-es/isFunction'\nimport merge from 'lodash-es/merge'\nimport mapValues from 'lodash-es/mapValues'\n\nimport JsonqlEnumError from 'jsonql-errors/src/enum-error'\nimport JsonqlTypeError from 'jsonql-errors/src/type-error'\nimport JsonqlCheckerError from 'jsonql-errors/src/checker-error'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true;\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // log('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n // log(ENUM_KEY, value[ENUM_KEY])\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n // log(CHECKER_KEY, value[CHECKER_KEY])\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args;\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","// this is port back from the client to share across all projects\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return merge(\n runValidation(\n prepareArgsForValidation(config, appProps),\n cb\n ),\n constProps\n )\n}\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\nimport checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n };\n if (optional === true) {\n base[OPTIONAL_KEY] = true;\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv;\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker;\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias;\n }\n return base;\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__';\n\n/**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n checkConfigAsync,\n checkConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nexport const inArray = isInArray;\nexport const isObjectHasKey = isObjectHasKeyFn;\n","// breaking out the inner methods generator in here\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { LOGOUT_NAME, LOGIN_NAME, KEY_WORD } from 'jsonql-constants'\nimport { chainFns } from 'jsonql-utils/src/chain-fns'\nimport { injectToFn } from 'jsonql-utils/src/obj-define-props'\n\n/**\n * generate authorisation specific methods\n * @param {object} jsonqlInstance instance of this\n * @param {string} name of method\n * @param {object} opts configuration\n * @param {object} contract to match\n * @return {function} for use\n */\nconst authMethodGenerator = (jsonqlInstance, name, opts, contract) => {\n return (...args) => {\n const params = contract.auth[name].params;\n const values = params.map((p, i) => args[i])\n const header = args[params.length] || {};\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [name, values, header])\n )\n .catch(finalCatch)\n }\n}\n\n/**\n * Break up the different type each - create query methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let query = {}\n for (let queryFn in contract.query) {\n // to keep it clean we use a param to id the auth method\n // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn;\n // generate the query method\n query = injectToFn(query, queryFn, function queryFnHandler(...args) {\n const params = contract.query[queryFn].params;\n const _args = params.map((param, i) => args[i])\n // debug('query', queryFn, _params);\n // @TODO this need to change to a different way to add an extra header\n const header = {}\n // @TODO validate against the type\n return validateAsync(_args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [queryFn, _args, header])\n )\n .catch(finalCatch)\n })\n }\n obj.query = query;\n // create an alias to the helloWorld method\n obj.helloWorld = query.helloWorld;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create mutation methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let mutation = {}\n // process the mutation, the reason the mutation has a fixed number of parameters\n // there is only the payload, and conditions parameters\n // plus a header at the end\n for (let mutationFn in contract.mutation) {\n mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header = {}) {\n const args = [payload, conditions];\n const params = contract.mutation[mutationFn].params;\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .mutation\n .apply(jsonqlInstance, [mutationFn, payload, conditions, header])\n )\n .catch(e => {\n console.error('--- mutation fn catch ---', e)\n return finalCatch(e)\n })\n })\n }\n obj.mutation = mutation;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create auth methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createAuthMethods = (obj, jsonqlInstance, ee, config, contract) => {\n if (config.enableAuth && contract.auth) {\n let auth = {} // v1.3.1 add back the auth prop name in contract\n const { loginHandlerName, logoutHandlerName } = config;\n if (contract.auth[loginHandlerName]) {\n // changing to the name the config specify\n auth[loginHandlerName] = function loginHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance))\n .then(token => {\n ee.$trigger(LOGIN_NAME, token)\n return token;\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) {\n auth[logoutHandlerName] = function logoutHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance))\n .then(r => {\n ee.$trigger(LOGOUT_NAME, r)\n return r;\n })\n }\n } else {\n auth[logoutHandlerName] = function logoutHandlerFn() {\n jsonqlInstance.postLogoutAction(KEY_WORD)\n ee.$trigger(LOGOUT_NAME, KEY_WORD)\n }\n }\n obj.auth = auth;\n }\n\n return obj;\n}\n\n/**\n * Here just generate the methods calls\n * @param {object} jsonqlInstance what it said\n * @param {object} ee event emitter\n * @param {object} config configuration\n * @param {object} contract the map\n * @return {object} with mapped methods\n */\nexport function methodsGenerator(jsonqlInstance, ee, config, contract) {\n let obj = {}\n const executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods)\n return executor(obj, jsonqlInstance, ee, config, contract)\n}\n","// This generator will use the old style\n// with default methods\nimport { ON_RESULT_PROP_NAME, ON_ERROR_PROP_NAME } from 'jsonql-constants'\nimport { createEvt } from 'jsonql-utils/src/generic'\n\nimport { methodsGenerator } from './methods-generator'\n\n/**\n * Group all the same methods together\n * @param {object} ee event emitters\n * @param {string} type query, mutation or auth\n * @param {string} resolverName use as the guide\n * @param {array} args from the call\n * @return {function} the handler itself\n */\nconst handler = (ee, type) => {\n // we don't run validate here because we want until the contract is ready\n return (resolverName, ...args) => (\n new Promise((resolver, rejecter) => {\n // this are the callbacks\n ee.$only(createEvt(type, resolverName, ON_RESULT_PROP_NAME), resolver)\n ee.$only(createEvt(type, resolverName, ON_ERROR_PROP_NAME), rejecter)\n // this is the main call\n ee.$trigger(type, { resolverName, args })\n })\n )\n}\n\n/**\n * @param {object} ee eventEmitter\n * @param {object} contract the map\n * @param {object} config configuration\n */\nconst validateRegisteredEvents = (ee, contract, config) => {\n const storedEvt = ee.$queues;\n const debug = config.debugOn;\n if (debug) {\n console.info('(validateRegisteredEvents)', 'storedEvt', storedEvt)\n }\n storedEvt.forEach(args => {\n let [type, payload] = args;\n let { resolverName } = payload;\n if (debug) {\n console.info('(validateRegisteredEvents)', type, resolverName)\n }\n if (!contract[type][resolverName]) {\n throw new Error(`${type}.${resolverName} not existed in contract!`)\n }\n })\n}\n\n/**\n * set up all the event handlers once the contract is ready\n * @param {object} jsonqlInstance what the name said\n * @param {object} ee event emitter\n * @param {object} config the configuration\n * @param {object} contract the map\n * @return {void} nothing\n */\nfunction setupEventHandlers(jsonqlInstance, ee, config, contract) {\n let methods = methodsGenerator(jsonqlInstance, ee, config, contract)\n validateRegisteredEvents(ee, contract, config)\n // create handler\n for (let type in methods) {\n // setup event listeners - only one listener per type\n ee.$only(type, function({resolverName, args}) {\n if (methods[type][resolverName]) {\n Reflect.apply(methods[type][resolverName], null, args)\n .then(result => {\n ee.$trigger(createEvt(type, resolverName, ON_RESULT_PROP_NAME), result)\n })\n .catch(err => {\n ee.$trigger(createEvt(type, resolverName, ON_ERROR_PROP_NAME), err)\n })\n } else {\n console.error(`${resolverName} is not defined in the contract!`)\n }\n })\n }\n // all done now release the queue if any\n setTimeout(() => {\n ee.$suspend = false;\n }, 1)\n}\n\n/**\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} config options\n * @param {object} contractPromise an unresolve promise\n * @param {object} ee eventEmitter\n * @return {object} constructed functions call\n */\nconst generator = (jsonqlInstance, config, contractPromise, ee) => {\n ee.$suspend = true; // hold all the calls\n // wait for the promise to resolve\n contractPromise.then(contract => {\n setupEventHandlers(jsonqlInstance, ee, config, contract)\n })\n // construct the api\n let obj = {\n query: handler(ee, 'query'),\n mutation: handler(ee, 'mutation'),\n auth: handler(ee, 'auth')\n }\n // allow getting the token for valdiate agains the socket\n obj.getToken = () => jsonqlInstance.rawAuthToken;\n // this will pass to the ws-client if needed\n // obj.eventEmitter = ee;\n // this will require a param\n if (config.exposeContract) {\n obj.getContract = () => jsonqlInstance.get()\n }\n if (config.enableAuth) {\n obj.userdata = () => jsonqlInstance.userdata;\n }\n obj.version = '__VERSION__';\n // output\n return obj;\n}\n\nexport default generator;\n","// split the contract into the node side and the generic side\nimport { isObjectHasKey } from './generic'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n SOCKET_NAME,\n QUERY_ARG_NAME,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlResolverNotFoundError } from 'jsonql-errors'\n/**\n * Check if the json is a contract file or not\n * @param {object} contract json object\n * @return {boolean} true\n */\nexport function checkIsContract(contract) {\n return isPlainObject(contract)\n && (\n isObjectHasKey(contract, QUERY_NAME)\n || isObjectHasKey(contract, MUTATION_NAME)\n || isObjectHasKey(contract, SOCKET_NAME)\n )\n}\n\n/**\n * Wrapper method that check if it's contract then return the contract or false\n * @param {object} contract the object to check\n * @return {boolean | object} false when it's not\n */\nexport function isContract(contract) {\n return checkIsContract(contract) ? contract : false;\n}\n\n/**\n * Ported from jsonql-params-validator but different\n * if we don't find the socket part then return false\n * @param {object} contract the contract object\n * @return {object|boolean} false on failed\n */\nexport function extractSocketPart(contract) {\n if (isObjectHasKey(contract, 'socket')) {\n return contract.socket;\n }\n return false;\n}\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @param {boolean} [fallback=false] this is a fall back option for old code\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport function groupByNamespace(contract, fallback = false) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n if (fallback) {\n return contract; // just return the whole contract\n }\n throw new JsonqlError(`socket not found in contract!`)\n }\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\n}\n\n/**\n * @NOTE ported from jsonql-ws-client\n * Got to make sure the connection order otherwise\n * it will hang\n * @param {object} nspSet contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspSet, publicNamespace) {\n let names = []; // need to make sure the order!\n for (let namespace in nspSet) {\n if (namespace === publicNamespace) {\n names[1] = namespace;\n } else {\n names[0] = namespace;\n }\n }\n return names;\n}\n\n\n/**\n * Extract the args from the payload\n * @param {object} payload to work with\n * @param {string} type of call\n * @return {array} args\n */\nexport function extractArgsFromPayload(payload, type) {\n switch (type) {\n case QUERY_NAME:\n return payload[QUERY_ARG_NAME];\n case MUTATION_NAME:\n return [\n payload[PAYLOAD_PARAM_NAME],\n payload[CONDITION_PARAM_NAME]\n ];\n default:\n throw new JsonqlError(`Unknown ${type} to extract argument from!`)\n }\n}\n\n/**\n * Like what the name said\n * @param {object} contract the contract json\n * @param {string} type query|mutation\n * @param {string} name of the function\n * @return {object} the params part of the contract\n */\nexport function extractParamsFromContract(contract, type, name) {\n try {\n const result = contract[type][name];\n // debug('extractParamsFromContract', result)\n if (!result) {\n // debug(name, type, contract)\n throw new JsonqlResolverNotFoundError(name, type)\n }\n return result;\n } catch(e) {\n throw new JsonqlResolverNotFoundError(name, e)\n }\n}\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport default function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n","// take only the module part which is what we use here\n// and export it again to use through out the client\n// this way we avoid those that we don't want node.js module got build into the code\nimport { isContract } from 'jsonql-utils/src/contract'\nimport hashCodeFn from 'nb-event-service/src/hash-code'\n/**\n * @param {object} jsonqlInstance the init instance of jsonql client\n * @param {object} contract the static contract\n * @return {object} contract may be from server\n */\nconst getContractFromConfig = function(jsonqlInstance, contract = {}) {\n if (isContract(contract)) {\n return Promise.resolve(contract)\n }\n return jsonqlInstance.getContract()\n}\n// wrapper method to make sure it's a string\nconst hashCode = str => hashCodeFn(str) + ''\n\n// simple util to check if an object has any properties\n// const hasProp = obj => isObject(obj) && Object.keys(obj).length\n\n// export some constants as well\n// since it's only use here there is no point of adding it to the constants module\n// or may be we add it back later\nconst ENDPOINT_TABLE = 'endpoint' // not in use anymore delete later @TODO\nconst USERDATA_TABLE = 'userdata'\nconst CLS_LOCAL_STORE_NAME = 'localStore'\nconst CLS_SESS_STORE_NAME = 'sessionStore'\nconst CLS_CONTRACT_NAME = 'contract'\nconst CLS_PROFILE_IDX = 'prof_idx'\nconst ZERO_IDX = 0\n// export\nexport {\n hashCode,\n getContractFromConfig,\n ENDPOINT_TABLE,\n USERDATA_TABLE,\n CLS_LOCAL_STORE_NAME,\n CLS_SESS_STORE_NAME,\n CLS_CONTRACT_NAME,\n CLS_PROFILE_IDX,\n ZERO_IDX\n}\n","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\nfunction polyfill (input) {\n var str = String(input).replace(/=+$/, '');\n if (str.length % 4 == 1) {\n throw new InvalidCharacterError(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = '';\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n return output;\n}\n\n\nmodule.exports = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill;\n","// when the user is login with the jwt\n// we use call this to decode the token and then add the payload\n// to the resolver so the user can call ResolverName.userdata\n// and get back the payload\nimport jwt_decode from 'jwt-decode'\nimport isString from 'jsonql-params-validator/src/string'\nimport JsonqlError from 'jsonql-errors/src/error'\n\nconst timestamp = function (sec = false) {\n var time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n\n/**\n * We only check the nbf and exp\n * @param {object} token for checking\n * @return {object} token on success\n */\nfunction validate(token) {\n const start = token.iat || timestamp(true)\n // we only check the exp for the time being\n if (token.exp) {\n if (start >= token.exp) {\n const expired = new Date(token.exp).toISOString()\n throw new JsonqlError(`Token has expired on ${expired}`, token)\n }\n }\n return token;\n}\n\n/**\n * The browser client version it has far fewer options and it doesn't verify it\n * because it couldn't this is the job for the server\n * @TODO we need to add some extra proessing here to check for the exp field\n * @param {string} token to decrypted\n * @return {object} decrypted object\n */\nexport default function jwtDecode(token) {\n if (isString(token)) {\n const t = jwt_decode(token)\n return validate(t)\n }\n throw new JsonqlError('Token must be a string!')\n}\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n","module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n","// sort of persist on the user side\nimport engine from 'store/src/store-engine'\n\nimport localStorage from 'store/storages/localStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// @1.5.0 stop using the expired plugin, and deal with it ourself\n// import expiredPlugin from 'store/plugins/expire'\nimport eventsPlugin from 'store/plugins/events'\nimport compressionPlugin from 'store/plugins/compression'\n\nconst storages = [localStorage, cookieStorage]\nconst plugins = [defaultPlugin, eventsPlugin, compressionPlugin]\n\nconst localStore = engine.createStore(storages, plugins)\n\nexport default localStore\n","// session store with watch\nimport engine from 'store/src/store-engine'\n\nimport sessionStorage from 'store/storages/sessionStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// start using compression in 1.5.0 \nimport compressionPlugin from 'store/plugins/compression'\n// @1.5.0 stop using the expired plugin and deal it ourself\n// import expiredPlugin from 'store/plugins/expire'\n\nconst storages = [sessionStorage, cookieStorage]\nconst plugins = [defaultPlugin, compressionPlugin]\n\nconst sessionStore = engine.createStore(storages, plugins)\n\nexport default sessionStore\n","// export store interface\n// @TODO need to figure out how to make this as a outside dependencies instead of built into it\nimport localStoreEngine from './local-store'\nimport sessionStoreEngine from './session-store'\n\n// export back the raw version for development purposes\nexport const localStore = localStoreEngine\nexport const sessionStore = sessionStoreEngine\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport isString from 'lodash-es/isString'\n\nimport { timestamp } from './timestamp'\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? JSON.parse(payload) : payload;\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName\n * @param {*} payload\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload) {\n return {\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload;\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload;\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getNameFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// break up from node-middleware\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n API_REQUEST_METHODS,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME ,\n QUERY_ARG_NAME,\n DATA_KEY,\n ERROR_KEY,\n INDEX_KEY,\n EXT,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport { isObjectHasKey } from './generic'\nimport { timestamp } from './timestamp'\nimport isArray from 'lodash-es/isArray'\nimport merge from 'lodash-es/merge'\n/**\n * getting what is calling after the above check\n * @param {string} method of call\n * @return {mixed} false on failed\n */\nexport const getCallMethod = method => {\n const [ POST, PUT ] = API_REQUEST_METHODS;\n switch (true) {\n case method === POST:\n return QUERY_NAME;\n case method === PUT:\n return MUTATION_NAME;\n default:\n return false;\n }\n}\n\n/**\n * wrapper method\n * @param {mixed} result of fn return\n * @param {boolean|array} [ts=false] when pass this then we append a new value to the end\n * @return {string} stringify data\n */\nexport const packResult = function(result, ts = false) {\n let payload = { [DATA_KEY]: result }\n if (ts && isArray(ts)) {\n ts.push(timestamp())\n payload[TIMESTAMP_PARAM_NAME] = ts\n }\n return JSON.stringify(payload)\n}\n\n/**\n * Check if the error object contain out custom key\n * @param {*} e object\n * @return {boolean} true\n */\nexport const isJsonqlErrorObj = e => {\n const searchFields = ['detail', 'className']\n const test = !!searchFields.filter(field => isObjectHasKey(e, field)).length\n if (test) {\n return ['className', 'message', 'statusCode']\n .filter(field => isObjectHasKey(e, field))\n .map(field => (\n {\n [field]: typeof e[field] === 'object' ? e[field].toString() : e[field]\n }\n ))\n .reduce(merge, {detail: e.toString()}) // can only get as much as possible\n }\n return false;\n}\n\n/**\n * wrapper method - the output is trying to match up the structure of the Error sub class\n * @param {mixed} detail of fn error\n * @param {string} [className=JsonqlError] the errorName\n * @param {number} [statusCode=500] the original error code\n * @return {string} stringify error\n */\nexport const packError = function(detail, className = 'JsonqlError', statusCode = 0, message = '') {\n let errorObj = { detail, className, statusCode, message }\n // we need to check the detail object to see if it has detail, className and message\n // if it has then we should merge the object instead\n return JSON.stringify({\n [ERROR_KEY]: isJsonqlErrorObj(detail) || errorObj,\n [TIMESTAMP_PARAM_NAME]: timestamp()\n })\n}\n\n// ported from http-client\n\n/**\n * handle the return data\n * @TODO how to handle the return timestamp and calculate the diff?\n * @param {object} result return from server\n * @return {object} strip the data part out, or if the error is presented\n */\nexport const resultHandler = result => (\n (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result\n)\n","// new 1.5.0\n// create a class method to handle all the saving and retriving data\n// using the instanceKey to id the data hence allow to use multiple instance\nimport merge from 'lodash-es/merge'\nimport { localStore, sessionStore } from '../stores'\nimport { CLS_SESS_STORE_NAME, CLS_LOCAL_STORE_NAME, hashCode } from '../utils'\n\n// this becomes the base class instead of the HttpCls\nexport default class StoreClass {\n\n constructor(opts) {\n this.opts = opts\n // make it a string\n this.instanceKey = hashCode(this.opts.hostname)\n // pass this store for use later\n this.localStore = localStore\n this.sessionStore = sessionStore\n /*\n if (this.opts.debugOn) { // reuse this to clear out the data\n this.log('clear all stores')\n localStore.clearAll()\n sessionStore.clearAll()\n\n localStore.set('TEST', Date.now())\n sessionStore.set('TEST', Date.now())\n }\n */\n }\n // store in local storage id by the instanceKey\n // values should be an object so with key so we just merge\n // into the existing store without going through the keys\n __setMethod(storeType, values) {\n let store = this[storeType]\n let data = this.__getMethod(storeType)\n const skey = this.opts.storageKey\n const ikey = this.instanceKey\n store.set(skey, {\n [ikey]: data ? merge({}, data, values) : values\n })\n }\n // return the data id by the instaceKey\n __getMethod(storeType) {\n let store = this[storeType]\n let data = store.get(this.opts.storageKey)\n return data ? data[this.instanceKey] : false\n }\n // remove from local store id by instanceKey\n __delMethod(storeType, key) {\n let data = this.__getMethod(storeType)\n if (data) {\n let store = {}\n for (let k in data) {\n if (k !== key) {\n store[k] = data[k]\n }\n }\n this.__setMethod(storeType, store)\n }\n }\n // clear everything by this instanceKey\n __clearMethod(storeKey) {\n const skey = this.opts.storageKey\n const store = this[storeKey]\n let data = store.get(skey)\n if (data) {\n let _store = {}\n for (let k in data) {\n if (k !== this.instanceKey) {\n _store[k] = data[k]\n }\n }\n store.set(skey, _store)\n }\n }\n // Alias for different store\n set lset(values) {\n return this.__setMethod(CLS_LOCAL_STORE_NAME, values)\n }\n\n get lget() {\n return this.__getMethod(CLS_LOCAL_STORE_NAME)\n }\n\n ldel(key) {\n return this.__delMethod(CLS_LOCAL_STORE_NAME, key)\n }\n\n lclear() {\n return this.__clearMethod(CLS_LOCAL_STORE_NAME)\n }\n\n // store in session store id by the instanceKey\n set sset(values) {\n // this.log('--- sset ---', values)\n return this.__setMethod(CLS_SESS_STORE_NAME, values)\n }\n\n get sget() {\n return this.__getMethod(CLS_SESS_STORE_NAME)\n }\n\n sdel(key) {\n return this.__delMethod(CLS_SESS_STORE_NAME, key)\n }\n\n sclear() {\n return this.__clearMethod(CLS_SESS_STORE_NAME)\n }\n\n\n}\n","// base HttpClass\nimport merge from 'lodash-es/merge'\nimport {\n createQuery,\n createMutation,\n getNameFromPayload\n} from 'jsonql-utils/src/params-api'\nimport { cacheBurst, urlParams } from 'jsonql-utils/src/urls'\nimport { resultHandler } from 'jsonql-utils/src/results'\nimport { isObject, isString } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlServerError,\n JsonqlError,\n // clientErrorsHandler\n} from 'jsonql-errors'\nimport {\n API_REQUEST_METHODS,\n DEFAULT_HEADER,\n JSONP_CALLBACK_NAME,\n SHOW_CONTRACT_DESC_PARAM\n} from 'jsonql-constants'\n\n// @DEBUG\nimport * as errors from 'jsonql-errors'\nimport { isObjectHasKey } from 'jsonql-utils/src/generic'\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nfunction clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n console.info('--- errorName ---', errorName, errors)\n\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n\n\n\n// extract the one we need\nconst [ POST, PUT ] = API_REQUEST_METHODS\n\nimport StoreClass from './store-cls'\n\nexport default class HttpClass extends StoreClass {\n /**\n * The opts has been check at the init stage\n * @param {object} opts configuration options\n */\n constructor(opts) {\n super(opts)\n // change the way how we init Fly\n // flyio now become external depedencies and it makes it easier to switch\n // @BUG should we run test to check if we have the windows object?\n // this.log(opts)\n // this.fly = opts.Fly ? new opts.Fly() : new Fly()\n // to a different environment like WeChat mini app\n\n this.extraHeader = {};\n // @1.2.1 for adding query to the call on the fly\n this.extraParams = {};\n // this.log('start up opts', opts);\n this.reqInterceptor()\n this.resInterceptor()\n }\n\n // set headers for that one call\n set headers(header) {\n this.extraHeader = header;\n }\n\n /**\n * Create the reusage request method\n * @param {object} payload jsonql payload\n * @param {object} options extra options add the request\n * @param {object} headers extra headers add to the call\n * @return {object} the fly request instance\n */\n request(payload, options = {}, headers = {}) {\n this.headers = headers;\n let params = merge({}, cacheBurst(), this.extraParams)\n // @TODO need to add a jsonp url and payload\n if (this.opts.enableJsonp) {\n let resolverName = getNameFromPayload(payload)\n params = merge({}, params, {[JSONP_CALLBACK_NAME]: resolverName})\n payload = payload[resolverName]\n }\n // double up the url param and see what happen @TODO remove later\n const reqParams = merge({}, { method: POST, params }, options)\n this.log('request params', reqParams, this.jsonqlEndpoint)\n\n return this.fly.request(this.jsonqlEndpoint, payload, reqParams)\n }\n\n /**\n * This will replace the create baseRequest method\n *\n */\n reqInterceptor() {\n this.fly.interceptors.request.use(\n req => {\n const headers = this.getHeaders()\n this.log('request interceptor call', headers)\n\n for (let key in headers) {\n req.headers[key] = headers[key]\n }\n return req;\n }\n )\n }\n\n // @TODO\n processJsonp(result) {\n return resultHandler(result)\n }\n\n /**\n * This will be replacement of the first then call\n *\n */\n resInterceptor() {\n const self = this;\n const jsonp = self.opts.enableJsonp;\n this.fly.interceptors.response.use(\n res => {\n this.log('response interceptor call', res)\n self.cleanUp()\n // now more processing here\n // there is a problem if we throw the result.error here\n // the original data is lost, so we need to do what we did before\n // deal with that error in the first then instead\n const result = isString(res.data) ? JSON.parse(res.data) : res.data;\n if (jsonp) {\n return self.processJsonp(result)\n }\n return resultHandler(result)\n },\n // this get call when it's not 200\n err => {\n self.cleanUp()\n console.error(err)\n throw new JsonqlServerError('Server side error', err)\n }\n )\n }\n\n /**\n * Get the headers inject into the call\n * @return {object} headers\n */\n getHeaders() {\n if (this.opts.enableAuth) {\n return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader)\n }\n return merge({}, DEFAULT_HEADER, this.extraHeader)\n }\n\n /**\n * Post http call operation to clean up things we need\n */\n cleanUp() {\n this.extraHeader = {}\n this.extraParams = {}\n }\n\n /**\n * GET for contract only\n * @return {promise} resolve the contract\n */\n getRemoteContract() {\n if (this.opts.showContractDesc) {\n this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM)\n }\n return this.request({}, {method: 'GET'}, this.contractHeader)\n .then(clientErrorsHandler)\n .then(result => {\n this.log('get contract result', result)\n // when refresh the window the result is different!\n // @TODO need to check the Koa side about why is that\n // also it should set a flag if we want the description or not\n if (result.cache && result.contract) {\n return result.contract;\n }\n // just the normal result\n return result\n })\n .catch(err => {\n console.error('getRemoteContract err', err)\n throw new JsonqlServerError('getRemoteContract', err)\n })\n }\n\n /**\n * POST to server - query\n * @param {object} name of the resolver\n * @param {array} args arguments\n * @return {object} promise resolve to the resolver return\n */\n query(name, args = []) {\n return this.request(createQuery(name, args))\n .then(clientErrorsHandler)\n }\n\n /**\n * PUT to server - mutation\n * @param {string} name of resolver\n * @param {object} payload what it said\n * @param {object} conditions what it said\n * @return {object} promise resolve to the resolver return\n */\n mutation(name, payload = {}, conditions = {}) {\n return this.request(createMutation(name, payload, conditions), {method: PUT})\n .then(clientErrorsHandler)\n }\n\n}\n","// all the contract related methods will be here\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { timestamp } from 'jsonql-utils/src/timestamp'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { ENDPOINT_TABLE, CLS_CONTRACT_NAME } from '../utils'\nimport { localStore } from '../stores'\nimport HttpClass from './http-cls'\n\n// export\nexport default class ContractClass extends HttpClass {\n\n constructor(opts) {\n super(opts)\n }\n\n /**\n * return the contract public api\n * @return {object} contract\n */\n getContract() {\n const contract = this.readContract()\n this.log('getContract first call', contract)\n return contract ? Promise.resolve(contract)\n : this.getRemoteContract().then(this.storeContract.bind(this))\n }\n\n /**\n * We are changing the way how to auth to get the contract.json\n * Instead of in the url, we will be putting that key value in the header\n * @return {object} header\n */\n get contractHeader() {\n let base = {};\n if (this.opts.contractKey !== false) {\n base[this.opts.contractKeyName] = this.opts.contractKey;\n }\n return base;\n }\n\n /**\n * Save the contract to local store\n * @param {object} contract to save\n * @return {object|boolean} false when its not a contract or contract on OK\n */\n storeContract(contract) {\n // first need to check if the contract is a contract\n if (!isContract(contract)) {\n throw new JsonqlValidationError(`Contract is malformed!`)\n //return false;\n }\n /* @TODO need to rethink how to expired the contract\n let args = [contract]\n if (this.opts.contractExpired) {\n let expired = parseFloat(this.opts.contractExpired)\n if (!isNaN(expired) && expired > 0) {\n args.push(expired)\n }\n }\n // calling the setter\n this.jsonqlContract = args;\n */\n this.lset = {[CLS_CONTRACT_NAME]: contract}\n // return it\n this.log('storeContract return result', contract)\n return contract;\n }\n\n /**\n * return the contract from options or localStore\n * @return {object|boolean} false on not found\n */\n readContract() {\n let contract = isContract(this.opts.contract)\n if (contract !== false) {\n return contract;\n }\n let data = this.lget\n if (data) {\n return data[CLS_CONTRACT_NAME]\n }\n return false;\n }\n}\n","// this is the new auth class that integrate with the jsonql-jwt\n// all the auth related methods will be here\nimport { decodeToken } from 'jsonql-jwt/src/client'\nimport { isNumber } from 'jsonql-params-validator'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { CREDENTIAL_STORAGE_KEY, AUTH_HEADER, BEARER } from 'jsonql-constants'\nimport { CLS_PROFILE_IDX, ZERO_IDX, USERDATA_TABLE } from '../utils'\nimport ContractClass from './contract-cls'\n// export\nexport default class AuthClass extends ContractClass {\n\n constructor(opts) {\n super(opts)\n if (opts.enableAuth) {\n this.setDecoder = decodeToken;\n }\n }\n\n /**\n * for overwrite\n * @param {string} token stored token\n * @return {string} token\n */\n decoder(token) {\n return token;\n }\n\n /**\n * set the profile index\n * @param {number} idx\n */\n set profileIndex(idx) {\n const key = CLS_PROFILE_IDX\n if (isNumber(idx)) {\n this[key] = idx;\n if (this.opts.persistToken) {\n this.lset = {[key]: idx}\n }\n return;\n }\n throw new JsonqlValidationError('profileIndex', `Expect idx to be number but got ${typeof idx}`)\n }\n\n /**\n * get the profile index\n * @return {number} idx\n */\n get profileIndex() {\n const key = CLS_PROFILE_IDX\n if (this.opts.persistToken) {\n const data = this.lget;\n if (data[key]) {\n return data[key]\n }\n }\n return this[key] ? this[key] : ZERO_IDX\n }\n\n /**\n * Return the token from session store\n * @param {number} [idx=false] profile index\n * @return {string} token\n */\n rawAuthToken(idx = false) {\n if (idx !== false) {\n this.profileIndex = idx;\n }\n // this should return from the base\n return this.jsonqlToken; // see base-cls\n }\n\n /**\n * Setter to add a decoder when retrieve user token\n * @param {function} d a decoder\n */\n set setDecoder(d) {\n if (typeof d === 'function') {\n this.decoder = d;\n }\n }\n\n /**\n * getter to return the session or local store set method\n * @param {*} data to save\n * @return {object} set method\n */\n set saveProfile(data) {\n if (this.opts.persistToken) {\n // this.log('--- saveProfile lset ---', data)\n this.lset = data\n } else {\n // this.log('--- saveProfile sset ---', data)\n this.sset = data\n }\n }\n\n /**\n * getter to return the session or local store get method\n * @return {object} get method\n */\n get readProfile() {\n return this.opts.persistToken ? this.lget : this.sget\n }\n\n // these were in the base class before but it should be here\n /**\n * save token\n * @param {string} token to store\n * @return {string|boolean} false on failed\n */\n set jsonqlToken(token) {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n // @TODO also have to make sure the token is not already existed!\n let tokens = (data && data[key]) ? data[key] : []\n tokens.push(token)\n this.saveProfile = {[key]: tokens}\n // store the userdata\n this.jsonqlUserdata = this.decoder(token)\n }\n\n /**\n * Jsonql token getter\n * 1.5.1 each token associate with the same profileIndex\n * @return {string|boolean} false when failed\n */\n get jsonqlToken() {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex])\n return data[key][this.profileIndex]\n }\n return false\n }\n\n /**\n * this one will use the sessionStore\n * basically we hook this onto the token store and decode it to store here\n * we only store one decoded user data at a time, but the token can be multiple\n */\n set jsonqlUserdata(userdata) {\n this.sset = {[USERDATA_TABLE]: userdata}\n }\n\n /**\n * this one store in the session store\n * get login userdata decoded jwt\n * 1.5.1 each userdata associate with the same profileIndex\n * @return {object|null}\n */\n get jsonqlUserdata() {\n const data = this.sget\n return data ? data[USERDATA_TABLE] : false\n }\n\n /**\n * Construct the auth header\n * @return {object} header\n */\n getAuthHeader() {\n const token = this.jsonqlToken // only call the getter to get the default one\n return token ? {[this.opts.AUTH_HEADER]: `${BEARER} ${token}`} : {};\n }\n\n /**\n * return all the stored token and decode it\n * @param {number} [idx=false] profile index\n * @return {array|boolean|string} false not found or array\n */\n getProfiles(idx = false) {\n const self = this; // just in case the scope problem\n const data = self.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n if (idx !== false && isNumber(idx)) {\n return data[key][idx] || false\n }\n return data[key].map(self.decoder.bind(self))\n }\n return false\n }\n\n /**\n * call after the login\n * @param {string} token return from server\n * @return {object} decoded token to userdata object\n */\n postLoginAction(token) {\n this.jsonqlToken = token\n return token\n }\n\n /**\n * call after the logout @TODO\n */\n postLogoutAction(...args) {\n console.info(`postLogoutAction`, args)\n }\n}\n","// this the core of the internal storage management\nimport { CREDENTIAL_STORAGE_KEY } from 'jsonql-constants'\n// import { isObject, isArray } from 'jsonql-params-validator'\n// import { JsonqlValidationError } from 'jsonql-errors'\n// import { timestamp } from 'jsonql-utils/src/timestamp'\n// import { inArray } from 'jsonql-utils/src/generic'\nimport { USERDATA_TABLE } from '../utils'\nimport AuthCls from './auth-cls'\n\n// This class will only focus on the storage system\nexport default class JsonqlBaseClient extends AuthCls {\n // change the order of the interface in 1.4.10 to match up the top level\n constructor(fly, opts) {\n // change at 1.4.10 pass it directly without init it\n this.fly = fly;\n super(opts)\n }\n\n /**\n * construct the end point\n * @return {string} the end point to call\n */\n get jsonqlEndpoint() {\n const baseUrl = this.opts.hostname || ''\n return [baseUrl, this.opts.jsonqlPath].join('/')\n }\n\n /**\n * simple log\n */\n log(...args) {\n if (this.opts.debugOn === true) {\n Reflect.apply(console.info, console, args)\n }\n }\n\n}\n","// export interface\n// @public\nimport JsonqlBaseClient from './base-cls'\n\nexport default JsonqlBaseClient\n","// all the client configuration options here\nimport {\n JSONQL_PATH,\n CONTENT_TYPE,\n BEARER,\n CLIENT_STORAGE_KEY,\n CLIENT_AUTH_KEY,\n CONTRACT_KEY_NAME,\n AUTH_HEADER,\n ISSUER_NAME,\n LOGOUT_NAME,\n BOOLEAN_TYPE,\n STRING_TYPE,\n NUMBER_TYPE,\n DEFAULT_HEADER\n} from 'jsonql-constants'\nimport { createConfig } from 'jsonql-params-validator'\nexport const constProps = {\n contract: false,\n MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong?\n CONTENT_TYPE,\n BEARER,\n AUTH_HEADER\n}\n\n// grab the localhost name and put into the hostname as default\nconst getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n return null\n }\n}\n\nexport const appProps = {\n\n hostname: createConfig(getHostName(), [STRING_TYPE]), // required the hostname\n jsonqlPath: createConfig(JSONQL_PATH, [STRING_TYPE]), // The path on the server\n\n loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]),\n logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]),\n // add to koa v1.3.0 - this might remove in the future\n enableJsonp: createConfig(false, [BOOLEAN_TYPE]),\n enableAuth: createConfig(false, [BOOLEAN_TYPE]),\n // enable useJwt by default @TODO replace with something else and remove them later\n useJwt: createConfig(true, [BOOLEAN_TYPE]),\n // when true then store infinity or pass a time in seconds then we check against\n // the token date of creation\n persistToken: createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE]),\n // the header\n // v1.2.0 we are using this option during the dev\n // so it won't save anything to the localstorage and fetch a new contract\n // whenever the browser reload\n useLocalstorage: createConfig(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage\n storageKey: createConfig(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage\n authKey: createConfig(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage\n contractExpired: createConfig(0, [NUMBER_TYPE]),// -1 always fetch contract,\n // 0 never expired,\n // > 0 then compare the timestamp with the current one to see if we need to get contract again\n // useful during development\n keepContract: createConfig(true, [BOOLEAN_TYPE]),\n exposeContract: createConfig(false, [BOOLEAN_TYPE]),\n exposeStore: createConfig(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn \n // @1.2.1 new option for the contract-console to fetch the contract with description\n showContractDesc: createConfig(false, [BOOLEAN_TYPE]),\n contractKey: createConfig(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this\n contractKeyName: createConfig(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs\n enableTimeout: createConfig(false, [BOOLEAN_TYPE]), // @TODO\n timeout: createConfig(5000, [NUMBER_TYPE]), // 5 seconds\n returnInstance: createConfig(false, [BOOLEAN_TYPE]),\n allowReturnRawToken: createConfig(false, [BOOLEAN_TYPE]),\n debugOn: createConfig(false, [BOOLEAN_TYPE])\n}\n","// This is for the sync version therefore we don't need to care about the contract options\nimport { appProps, constProps } from './base-options'\nimport { checkConfig } from 'jsonql-params-validator'\n\nexport default function checkOptions(config) {\n return checkConfig(config, appProps, constProps)\n}\n","// export interface\nimport checkOptionsAsyncLocal from './check-options-async'\nimport checkOptionsLocal from './check-options'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport { objHasProp } from 'jsonql-utils/src/obj-define-props'\n/**\n * 1.5.0 overload the orginal functions to pass over the check\n */\nfunction checkOptionsAsync(config) {\n return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsyncLocal(config)\n}\n\n// sync version without needing the promise\nfunction checkOptions(config) {\n return objHasProp(config, CHECKED_KEY) ? config : checkOptionsLocal(config)\n}\n\nexport {\n checkOptionsAsync,\n checkOptions\n}\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n\nexport default class SuspendClass {\n\n constructor() {\n // suspend, release and queue\n this.__suspend__ = null;\n this.queueStore = new Set()\n /*\n this.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n })\n */\n }\n\n /**\n * setter to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n set $suspend(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend__;\n this.__suspend__ = value;\n this.logger('($suspend)', `Change from ${lastValue} --> ${value}`)\n if (lastValue === true && value === false) {\n setTimeout(() => {\n this.release()\n }, 1)\n }\n } else {\n throw new Error(`$suspend only accept Boolean value!`)\n }\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {any} value\n * @return {Boolean} true when added or false when it's not\n */\n $queue(...args) {\n if (this.__suspend__ === true) {\n this.logger('($queue)', 'added to $queue', args)\n // there shouldn't be any duplicate ...\n this.queueStore.add(args)\n }\n return this.__suspend__;\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size;\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n release() {\n let size = this.queueStore.size\n this.logger('(release)', `Release was called ${size}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('queue', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport genHaskKey from './hash-code'\nimport SuspendClass from './suspend'\n\nexport default class NbEventServiceBase extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger;\n }\n this.keep = config.keep;\n // for the $done setter\n this.result = config.keep ? [] : null;\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (typeof e !== 'string') {\n this.logger('(validateEvt)', e)\n throw new Error(`event name must be string type!`)\n }\n })\n return true;\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n return true;\n }\n }\n throw new Error(`callback required to be function type!`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n const types = ['on', 'only', 'once', 'onlyOnce']\n return !!types.filter(t => type === t).length;\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run)', callback, payload, ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName]; // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger('(takeFromStore)', `has ${evt}`, content)\n store.delete(evt)\n return content;\n }\n return false;\n }\n throw new Error(`${storeName} is not supported!`)\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n let fnSet;\n if (store.has(evt)) {\n this.logger('(addToStore)', `${evt} existed`)\n fnSet = store.get(evt)\n } else {\n this.logger('(addToStore)', `create new Set for ${evt}`)\n // this is new\n fnSet = new Set()\n }\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args;\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger('(addToStore)', `insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(l => {\n let [hash,] = l;\n if (hash === args[0]) {\n return true;\n }\n return false;\n }).length;\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true;\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list;\n return type !== t;\n }).length;\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n this.logger('(checkTypeInLazyStore)', store)\n if (store) {\n return !!Array\n .from(store)\n .filter(l => {\n let [,,t] = l;\n return t !== type;\n }).length\n }\n return false;\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger('(addToNormalStore)', evt, type, 'try to add to normal store')\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n this.logger('(addToNormalStore)', `${type} can add to ${evt} normal store`)\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store;\n return size;\n }\n return false;\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store;\n return size;\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg];\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n return genHaskKey(fn.toString()) + '';\n }\n}\n","// The top level\nimport NbStoreService from './store-service'\n// export\nexport default class EventService extends NbStoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on';\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger('($on)', `${evt} callback is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger('($on)', `${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0;\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($on)`, `call run on ${evt}`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n return size;\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n const type = 'once';\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (lazyStoreContent === false) {\n this.logger('($once)', `${evt} not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, type, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger('($once)', `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'only';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($only)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($only)', `${evt} found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( l => {\n const [ payload, ctx, t ] = l;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($only)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n })\n }\n return added;\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD added in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'onlyOnce';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== 'onlyOnce') {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($onlyOnce)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added;\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {}\n */\n $replace(evt, callback, context = null, type = 'on') {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n this.logger(`($replace)`, evt, callback)\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0;\n // first check the normal store\n let nStore = this.normalStore;\n this.logger('($trigger)', 'normalStore', nStore)\n if (nStore.has(evt)) {\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n this.logger('($trigger)', evt, 'found; add to queue: ', added)\n if (added === true) {\n this.logger('($trigger)', evt, 'not executed. Exit now.')\n return false; // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length;\n let hasOnce = false;\n let hasOnly = false;\n for (let i=0; i < ctn; ++i) {\n ++found;\n // this.logger('found', found)\n let [ _, callback, ctx, type ] = nSet[i]\n this.logger(`($trigger)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n if (type === 'once' || type === 'onlyOnce') {\n hasOnce = true;\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found;\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found;\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter around\n * @param {string} evt event name\n * @param {*} params pass to the callback\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, params, type = false, context = null) {\n let args = [evt, params, context, type]\n return Reflect.apply(this.$trigger, this, args)\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n let found = false;\n stores.forEach(store => {\n if (store.has(evt)) {\n found = true;\n this.logger('($off)', evt)\n store.delete(evt)\n }\n })\n return found;\n }\n\n /**\n * return all the listener from the event\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n this.validateEvt(evt)\n let store = this.normalStore;\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l;\n }\n let [key, callback, ] = l;\n return callback;\n })\n }\n return false;\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done)', 'value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value;\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n if (this.keep) {\n this.logger('(get $done)', this.result)\n return this.result[this.result.length - 1]\n }\n return this.result;\n }\n\n\n}\n","// default\nimport NBEventService from './src/event-service'\n\nexport default NBEventService\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// output\nexport default function(debugOn) {\n let logger = debugOn ? (...args) => {\n args.unshift('[NBS]')\n console.log.apply(null, args)\n }: undefined;\n return new NBEventService({ logger })\n}\n","// this is the new Event base interface\n// the export will be different and purposely design for framework that\n// is very hard to use Promise such as Vue\nimport jsonqlStaticGenerator from './core/jsonql-static-generator'\nimport JsonqlBaseClient from './base'\nimport { checkOptions } from './options'\nimport { getContractFromConfig } from './utils'\nimport getEventEmitter from './ee'\n/**\n * this is the slim client without Fly, you pick the version of Fly to use\n * This is a breaking change because it swap the input positions\n * @param {object} fly fly.js\n * @param {object} config configuration\n * @return {object} the jsonql client instance\n */\nexport default function jsonqlStaticClient(fly, config = {}) {\n const { contract } = config;\n const opts = checkOptions(config)\n const jsonqlBase = new JsonqlBaseClient(fly, opts)\n const contractPromise = getContractFromConfig(jsonqlBase, contract)\n const ee = getEventEmitter(opts.debugOn)\n // finally\n let methods = jsonqlStaticGenerator(jsonqlBase, opts, contractPromise, ee)\n methods.eventEmitter = ee;\n return methods;\n}\n","// This is the static version that build with the Fly for Browser\nimport Fly from 'flyio/dist/npm/fly'\nimport jsonqlStaticClient from './static'\n\n// this is the slim client without Fly\nexport default function jsonqlStaticClientFull(config = {}) {\n return jsonqlStaticClient(new Fly(), config)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/packages/http-client/dist/jsonql-client.umd.js b/packages/http-client/dist/jsonql-client.umd.js index a3a92b32..fab4cb49 100644 --- a/packages/http-client/dist/jsonql-client.umd.js +++ b/packages/http-client/dist/jsonql-client.umd.js @@ -1,2 +1,9635 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClient=e()}(this,(function(){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r,n=e((function(t,e){var r;r=function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=2)}([function(t,e,r){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};t.exports={type:function(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()},isObject:function(t,e){return e?"object"===this.type(t):t&&"object"===(void 0===t?"undefined":n(t))},isFormData:function(t){return"undefined"!=typeof FormData&&t instanceof FormData},trim:function(t){return t.replace(/(^\s*)|(\s*$)/g,"")},encode:function(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")},formatParams:function(t){var e="",r=!0,n=this;return this.isObject(t)?(function t(o,i){var a=n.encode,u=n.type(o);if("array"==u)o.forEach((function(e,r){n.isObject(e)||(r=""),t(e,i+"%5B"+r+"%5D")}));else if("object"==u)for(var c in o)t(o[c],i?i+"%5B"+a(c)+"%5D":a(c));else r||(e+="&"),r=!1,e+=i+"="+a(o)}(t,""),e):t},merge:function(t,e){for(var r in e)t.hasOwnProperty(r)?this.isObject(e[r],1)&&this.isObject(t[r],1)&&this.merge(t[r],e[r]):t[r]=e[r];return t}}},,function(t,e,r){var n=function(){function t(t,e){for(var r=0;r0&&(t+=(-1===t.indexOf("?")?"?":"&")+w.join("&")),a.open(r.method,t);try{a.withCredentials=!!r.withCredentials,a.timeout=r.timeout||0,"stream"!==y&&(a.responseType=y)}catch(t){}var j=r.headers[u]||r.headers[c],S="application/x-www-form-urlencoded";for(var O in o.trim((j||"").toLowerCase())===S?e=o.formatParams(e):o.isFormData(e)||-1===["object","array"].indexOf(o.type(e))||(S="application/json;charset=utf-8",e=JSON.stringify(e)),j||b||(r.headers[u]=S),r.headers)if(O===u&&o.isFormData(e))delete r.headers[O];else try{a.setRequestHeader(O,r.headers[O])}catch(t){}function k(t,e,n){v(l.p,(function(){if(t){n&&(e.request=r);var o=t.call(l,e,Promise);e=void 0===o?e:o}d(e)||(e=Promise[0===n?"resolve":"reject"](e)),e.then((function(t){s(t)})).catch((function(t){h(t)}))}))}function E(t){t.engine=a,k(l.onerror,t,-1)}function A(t,e){this.message=t,this.status=e}a.onload=function(){try{var t=a.response||a.responseText;t&&r.parseJson&&-1!==(a.getResponseHeader(u)||"").indexOf("json")&&!o.isObject(t)&&(t=JSON.parse(t));var e=a.responseHeaders;if(!e){e={};var n=(a.getAllResponseHeaders()||"").split("\r\n");n.pop(),n.forEach((function(t){if(t){var r=t.split(":")[0];e[r]=a.getResponseHeader(r)}}))}var i=a.status,c=a.statusText,s={data:t,headers:e,status:i,statusText:c};if(o.merge(s,a._response),i>=200&&i<300||304===i)s.engine=a,s.request=r,k(l.handler,s,0);else{var f=new A(c,i);f.response=s,E(f)}}catch(f){E(new A(f.msg,a.status))}},a.onerror=function(t){E(new A(t.msg||"Network Error",0))},a.ontimeout=function(){E(new A("timeout [ "+a.timeout+"ms ]",1))},a._options=r,setTimeout((function(){a.send(b?null:e)}),0)}(n):s(n)}),(function(t){h(t)}))}))}));return h.engine=a,h}},{key:"all",value:function(t){return Promise.all(t)}},{key:"spread",value:function(t){return function(e){return t.apply(null,e)}}}]),t}();a.default=a,["get","post","put","patch","head","delete"].forEach((function(t){a.prototype[t]=function(e,r,n){return this.request(e,r,o.merge({method:t},n))}})),["lock","unlock","clear"].forEach((function(t){a.prototype[t]=function(){this.interceptors.request[t]()}})),t.exports=a}])},t.exports=r()})),o=(r=n)&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r,i="application/vnd.api+json",a={Accept:i,"Content-Type":[i,"charset=utf-8"].join(";")},u="query",c="mutation",s="socket",f="payload",l="condition",p="TS",h=["POST","PUT"],d="type",v="optional",g="enumv",y="args",b="checker",m="alias",_="__checked__",w={desc:"y"},j="No message",S=Array.isArray,O="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},k="object"==typeof O&&O&&O.Object===Object&&O,E="object"==typeof self&&self&&self.Object===Object&&self,A=k||E||Function("return this")(),x=A.Symbol,T=Object.prototype,P=T.hasOwnProperty,q=T.toString,C=x?x.toStringTag:void 0;var $=Object.prototype.toString;var z="[object Null]",N="[object Undefined]",R=x?x.toStringTag:void 0;function M(t){return null==t?void 0===t?N:z:R&&R in Object(t)?function(t){var e=P.call(t,C),r=t[C];try{t[C]=void 0;var n=!0}catch(t){}var o=q.call(t);return n&&(e?t[C]=r:delete t[C]),o}(t):function(t){return $.call(t)}(t)}function I(t,e){return function(r){return t(e(r))}}var F=I(Object.getPrototypeOf,Object);function J(t){return null!=t&&"object"==typeof t}var D="[object Object]",U=Function.prototype,H=Object.prototype,L=U.toString,B=H.hasOwnProperty,K=L.call(Object);function G(t){if(!J(t)||M(t)!=D)return!1;var e=F(t);if(null===e)return!0;var r=B.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&L.call(r)==K}var V=function(t){return S(t)?t:[t]},W=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},Y=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),Q=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),X=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),Z=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),rt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),nt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),it=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),at=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),ut=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),ct=Object.freeze({__proto__:null,Jsonql406Error:Y,Jsonql500Error:Q,JsonqlAuthorisationError:X,JsonqlContractAuthError:Z,JsonqlResolverAppError:tt,JsonqlResolverNotFoundError:et,JsonqlEnumError:rt,JsonqlTypeError:nt,JsonqlCheckerError:ot,JsonqlValidationError:it,JsonqlError:at,JsonqlServerError:ut}),st=at,ft=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function lt(t){if(ft(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||j,a=e.detail||e;if(o&&ct[o])throw new ct[r](i,a);throw new st(i,a)}return t}function pt(t){if(Array.isArray(t))throw new it("",t);var e=t.message||j,r=t.detail||t;switch(!0){case t instanceof Y:throw new Y(e,r);case t instanceof Q:throw new Q(e,r);case t instanceof X:throw new X(e,r);case t instanceof Z:throw new Z(e,r);case t instanceof tt:throw new tt(e,r);case t instanceof et:throw new et(e,r);case t instanceof rt:throw new rt(e,r);case t instanceof nt:throw new nt(e,r);case t instanceof ot:throw new ot(e,r);case t instanceof it:throw new it(e,r);case t instanceof ut:throw new ut(e,r);default:throw new at(e,r)}}function ht(t){return!!function(t){return G(t)&&(W(t,u)||W(t,c)||W(t,s))}(t)&&t}function dt(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var vt=function(t,e){return void 0===e&&(e={}),ht(e)?Promise.resolve(e):t.getContract()},gt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function yt(t){this.message=t}yt.prototype=new Error,yt.prototype.name="InvalidCharacterError";var bt="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new yt("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=gt.indexOf(n);return a};var mt=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(bt(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return bt(e)}};function _t(t){this.message=t}_t.prototype=new Error,_t.prototype.name="InvalidTokenError";var wt=function(t,e){if("string"!=typeof t)throw new _t("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(mt(t.split(".")[r]))}catch(t){throw new _t("Invalid token specified: "+t.message)}},jt=_t;function St(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&Ct(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var Vt="[object String]";function Wt(t){return"string"==typeof t||!S(t)&&J(t)&&M(t)==Vt}var Yt=function(t){return""!==Gt(t)&&Wt(t)},Qt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Xt(t){if(Yt(t))return function(t){var e=t.iat||Qt(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new at("Token has expired on "+r,t)}return t}(wt(t));throw new at("Token must be a string!")}var Zt=function(t){return!!S(t)||null!=t&&""!==Gt(t)},te="[object Number]";function ee(t){return function(t){return"number"==typeof t||J(t)&&M(t)==te}(t)&&t!=+t}var re=function(t){return!Wt(t)&&!ee(parseFloat(t))},ne=function(t){return null!=t&&"boolean"==typeof t},oe=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==Gt(t)&&(!1===e||!0===e&&null!==t)},ie=d,ae=v,ue=g,ce=y,se=b,fe=m,le="continue",pe=function(t){switch(t){case"number":return re;case"string":return Yt;case"boolean":return ne;default:return oe}},he=function(t,e){return void 0===e&&(e=""),!!S(t)&&(""===e||""===Gt(e)||!(t.filter((function(t){return!pe(e)(t)})).length>0))},de=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ve=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!pe(e)(t)})).length)})).length:e.length>e.filter((function(t){return!he(r,t)})).length};var ge,ye=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[ge?a:++n];if(!1===e(o[u],u,o))break}return t};var be="[object Arguments]";function me(t){return J(t)&&M(t)==be}var _e=Object.prototype,we=_e.hasOwnProperty,je=_e.propertyIsEnumerable,Se=me(function(){return arguments}())?me:function(t){return J(t)&&we.call(t,"callee")&&!je.call(t,"callee")};var Oe="object"==typeof exports&&exports&&!exports.nodeType&&exports,ke=Oe&&"object"==typeof module&&module&&!module.nodeType&&module,Ee=ke&&ke.exports===Oe?A.Buffer:void 0,Ae=(Ee?Ee.isBuffer:void 0)||function(){return!1},xe=9007199254740991,Te=/^(?:0|[1-9]\d*)$/;function Pe(t,e){var r=typeof t;return!!(e=null==e?xe:e)&&("number"==r||"symbol"!=r&&Te.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=qe}var $e={};$e["[object Float32Array]"]=$e["[object Float64Array]"]=$e["[object Int8Array]"]=$e["[object Int16Array]"]=$e["[object Int32Array]"]=$e["[object Uint8Array]"]=$e["[object Uint8ClampedArray]"]=$e["[object Uint16Array]"]=$e["[object Uint32Array]"]=!0,$e["[object Arguments]"]=$e["[object Array]"]=$e["[object ArrayBuffer]"]=$e["[object Boolean]"]=$e["[object DataView]"]=$e["[object Date]"]=$e["[object Error]"]=$e["[object Function]"]=$e["[object Map]"]=$e["[object Number]"]=$e["[object Object]"]=$e["[object RegExp]"]=$e["[object Set]"]=$e["[object String]"]=$e["[object WeakMap]"]=!1;var ze,Ne="object"==typeof exports&&exports&&!exports.nodeType&&exports,Re=Ne&&"object"==typeof module&&module&&!module.nodeType&&module,Me=Re&&Re.exports===Ne&&k.process,Ie=function(){try{var t=Re&&Re.require&&Re.require("util").types;return t||Me&&Me.binding&&Me.binding("util")}catch(t){}}(),Fe=Ie&&Ie.isTypedArray,Je=Fe?(ze=Fe,function(t){return ze(t)}):function(t){return J(t)&&Ce(t.length)&&!!$e[M(t)]},De=Object.prototype.hasOwnProperty;function Ue(t,e){var r=S(t),n=!r&&Se(t),o=!r&&!n&&Ae(t),i=!r&&!n&&!o&&Je(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},ir.prototype.set=function(t,e){var r=this.__data__,n=nr(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var ar,ur=A["__core-js_shared__"],cr=(ar=/[^.]+$/.exec(ur&&ur.keys&&ur.keys.IE_PROTO||""))?"Symbol(src)_1."+ar:"";var sr=Function.prototype.toString;function fr(t){if(null!=t){try{return sr.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var lr=/^\[object .+?Constructor\]$/,pr=Function.prototype,hr=Object.prototype,dr=pr.toString,vr=hr.hasOwnProperty,gr=RegExp("^"+dr.call(vr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function yr(t){return!(!Ge(t)||function(t){return!!cr&&cr in t}(t))&&(Xe(t)?gr:lr).test(fr(t))}function br(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return yr(r)?r:void 0}var mr=br(A,"Map"),_r=br(Object,"create");var wr="__lodash_hash_undefined__",jr=Object.prototype.hasOwnProperty;var Sr=Object.prototype.hasOwnProperty;var Or="__lodash_hash_undefined__";function kr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&zr?new qr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=de(t))?!ve({arg:r},e):!pe(t)(r))})).length)})).length}return!1},eo=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(to,null,a);case"array"===t:return!he(e.arg);case!1!==(r=de(t)):return!ve(e,r);default:return!pe(t)(e.arg)}},ro=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},no=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!he(e))throw new at("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!he(t))throw new at("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?ro(t,a):t,index:r,param:a,optional:i}}));default:throw new at("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Zt(e)&&!(r.type.length>r.type.filter((function(e){return eo(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return eo(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},oo=function(){try{var t=br(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function io(t,e,r){"__proto__"==e&&oo?oo(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function ao(t,e,r){(void 0===r||rr(t[e],r))&&(void 0!==r||e in t)||io(t,e,r)}var uo="object"==typeof exports&&exports&&!exports.nodeType&&exports,co=uo&&"object"==typeof module&&module&&!module.nodeType&&module,so=co&&co.exports===uo?A.Buffer:void 0,fo=so?so.allocUnsafe:void 0;function lo(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new Rr(n).set(new Rr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var po=Object.create,ho=function(){function t(){}return function(e){if(!Ge(e))return{};if(po)return po(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function vo(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var go=Object.prototype.hasOwnProperty;function yo(t,e,r){var n=t[e];go.call(t,e)&&rr(n,r)&&(void 0!==r||e in t)||io(t,e,r)}var bo=Object.prototype.hasOwnProperty;function mo(t){if(!Ge(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Le(t),r=[];for(var n in t)("constructor"!=n||!e&&bo.call(t,n))&&r.push(n);return r}function _o(t){return Ze(t)?Ue(t,!0):mo(t)}function wo(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=Ao)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Eo);function qo(t,e){return Po(function(t,e,r){return e=ko(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=ko(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Co.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!Ge(r))return!1;var n=typeof e;return!!("number"==n?Ze(r)&&Pe(e,r.length):"string"==n&&e in r)&&rr(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=0;e--){var r=Ni().key(e);t(Ri(r),r)}},remove:function(t){return Ni().removeItem(t)},clearAll:function(){return Ni().clear()}};function Ni(){return $i.localStorage}function Ri(t){return Ni().getItem(t)}var Mi=yi.trim,Ii={name:"cookieStorage",read:function(t){if(!t||!Ui(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Fi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Fi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Ji,remove:Di,clearAll:function(){Ji((function(t,e){Di(e)}))}},Fi=yi.Global.document;function Ji(t){for(var e=Fi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Mi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Di(t){t&&Ui(t)&&(Fi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Ui(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Fi.cookie)}var Hi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Li=yi.bind,Bi=yi.each,Ki=yi.create,Gi=yi.slice,Vi=function(){var t=Ki(Wi,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Li(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Li(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),Bi(r,(function(e,r){t.fire(r,void 0,e)}))}}};var Wi={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Li(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Gi(arguments,1);Bi(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},Yi=e((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),Qi=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=Yi.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=Yi.compress(this._serialize(r));t(e,n)}}};var Xi=[zi,Ii],Zi=[Hi,Vi,Qi],ta=Pi.createStore(Xi,Zi),ea=yi.Global;function ra(){return ea.sessionStorage}function na(t){return ra().getItem(t)}var oa=[{name:"sessionStorage",read:na,write:function(t,e){return ra().setItem(t,e)},each:function(t){for(var e=ra().length-1;e>=0;e--){var r=ra().key(e);t(na(r),r)}},remove:function(t){return ra().removeItem(t)},clearAll:function(){return ra().clear()}},Ii],ia=[Hi,Qi],aa=Pi.createStore(oa,ia),ua=ta,ca=aa,sa=function(t){var e;return(e={}).args=t,e};function fa(t,e){var r;return(r={})[t]=e,r[p]=[pi()],r}var la=function(t){return W(t,"data")&&!W(t,"error")?t.data:t},pa=function(t){this.opts=t,this.instanceKey=dt(this.opts.hostname)+"",this.localStore=ua,this.sessionStore=ca},ha={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};pa.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?$o({},o,e):e,r))},pa.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},pa.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},pa.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},ha.lset.set=function(t){return this.__setMethod("localStore",t)},ha.lget.get=function(){return this.__getMethod("localStore")},pa.prototype.ldel=function(t){return this.__delMethod("localStore",t)},pa.prototype.lclear=function(){return this.__clearMethod("localStore")},ha.sset.set=function(t){return this.__setMethod("sessionStore",t)},ha.sget.get=function(){return this.__getMethod("sessionStore")},pa.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},pa.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(pa.prototype,ha);var da=h[0],va=h[1],ga=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];!0===this.opts.debugOn&&Reflect.apply(console.info,console,t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Xt)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(ci(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new it("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&ci(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!ht(t))throw new it("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=ht(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={headers:{configurable:!0}};return r.headers.set=function(t){this.extraHeader=t},e.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=$o({},{_cb:pi()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=$o({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=$o({},{method:da,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},e.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},e.prototype.processJsonp=function(t){return la(t)},e.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=ui(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):la(o)}),(function(t){throw e.cleanUp(),console.error(t),new ut("Server side error",t)}))},e.prototype.getHeaders=function(){return this.opts.enableAuth?$o({},a,this.getAuthHeader(),this.extraHeader):$o({},a,this.extraHeader)},e.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},e.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=$o({},this.extraParams,w)),this.request({},{method:"GET"},this.contractHeader).then(lt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(t){throw console.error("getRemoteContract err",t),new ut("getRemoteContract",t)}))},e.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Wt(t)&&S(e)){var n=sa(e);return!0===r?n:fa(t,n)}throw new it("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(lt)},e.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[f]=e,o[l]=r,!0===n)return o;if(Wt(t))return fa(t,o);throw new it("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:va}).then(lt)},Object.defineProperties(e.prototype,r),e}(pa)))),ya=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,V(t))}),Reflect.apply(t,null,r))}};function ba(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function ma(t,e,r,n){void 0===n&&(n=!1);var o=ba(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var _a=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return si(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch(pt)}},wa=function(t,e,r,n,o){var i={},a=function(t){i=ma(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return si(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch(pt)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},ja=function(t,e,r,n,o){var i={},a=function(t){i=ma(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return si(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch(pt)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Sa=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=_a(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=_a(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var Oa=function(t,e,r,n){var o=function(t,e,r,n){return ya(wa,ja,Sa)({},t,e,r,n)}(t,n,e,r);return e.enableAuth&&(o.userdata=function(){return t.jsonqlUserdata},o.getToken=function(e){return void 0===e&&(e=!1),t.rawAuthToken(e)},o.profileIndex=function(e){if(void 0===e&&(e=!1),!1===e)return t.profileIndex;t.profileIndex=e},o.getProfiles=function(e){return void 0===e&&(e=!1),t.getProfiles(e)}),e.exposeContract&&(o.getContract=function(){return t.getContract()}),e.exposeStore&&(o.tmpSave=function(t){},o.tmpGet=function(t){},o.tmpDel=function(t){},o.persistSave=function(t){},o.persistGet=function(t){},o.persistDel=function(t){}),o.eventEmitter=n,o.version="1.5.1",o.log=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return Reflect.apply(t.log,t,["[DEV DEBUG]"].concat(e))},o},ka={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:i,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Ea={hostname:fi(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:fi("jsonql",["string"]),loginHandlerName:fi("login",["string"]),logoutHandlerName:fi("logout",["string"]),enableJsonp:fi(!1,["boolean"]),enableAuth:fi(!1,["boolean"]),useJwt:fi(!0,["boolean"]),persistToken:fi(!1,["boolean","number"]),useLocalstorage:fi(!0,["boolean"]),storageKey:fi("jsonqlstore",["string"]),authKey:fi("jsonqlauthkey",["string"]),contractExpired:fi(0,["number"]),keepContract:fi(!0,["boolean"]),exposeContract:fi(!1,["boolean"]),exposeStore:fi(!1,["boolean"]),showContractDesc:fi(!1,["boolean"]),contractKey:fi(!1,["boolean"]),contractKeyName:fi("X-JSONQL-CV-KEY",["string"]),enableTimeout:fi(!1,["boolean"]),timeout:fi(5e3,["number"]),returnInstance:fi(!1,["boolean"]),allowReturnRawToken:fi(!1,["boolean"]),debugOn:fi(!1,["boolean"])};function Aa(t){return ba(t,_)?Promise.resolve(t):function(t){var e=t.contract;return li(t,Ea,ka).then((function(t){return t.contract=e,t}))}(t)}var xa=new WeakMap,Ta=new WeakMap,Pa=function(){this.__suspend__=null,this.queueStore=new Set},qa={$suspend:{configurable:!0},$queues:{configurable:!0}};qa.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Pa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},qa.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Pa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Pa.prototype,qa);var Ca=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){xa.set(this,t)},r.normalStore.get=function(){return xa.get(this)},r.lazyStore.set=function(t){Ta.set(this,t)},r.lazyStore.get=function(){return Ta.get(this)},e.prototype.hashFnToKey=function(t){return dt(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Pa));function $a(t,e){var r;return function(t,e,r){return void 0===e&&(e={}),Aa(e).then((function(t){return{baseClient:new ga(r,t),opts:t}})).then((function(e){var r=e.baseClient,n=e.opts;return vt(r,n.contract).then((function(e){return Oa(r,n,e,t)}))}))}((r=e.debugOn,new Ca({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),e,t)}return function(t){return void 0===t&&(t={}),$a(new o,t)}})); +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.jsonqlClient = factory()); +}(this, (function () { 'use strict'; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var fly = createCommonjsModule(function (module, exports) { + (function webpackUniversalModuleDefinition(root, factory) { + { module.exports = factory(); } + })(commonjsGlobal, function() { + return /******/ (function(modules) { // webpackBootstrap + /******/ // The module cache + /******/ var installedModules = {}; + /******/ + /******/ // The require function + /******/ function __webpack_require__(moduleId) { + /******/ + /******/ // Check if module is in cache + /******/ if(installedModules[moduleId]) { + /******/ return installedModules[moduleId].exports; + /******/ } + /******/ // Create a new module (and put it into the cache) + /******/ var module = installedModules[moduleId] = { + /******/ i: moduleId, + /******/ l: false, + /******/ exports: {} + /******/ }; + /******/ + /******/ // Execute the module function + /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + /******/ + /******/ // Flag the module as loaded + /******/ module.l = true; + /******/ + /******/ // Return the exports of the module + /******/ return module.exports; + /******/ } + /******/ + /******/ + /******/ // expose the modules object (__webpack_modules__) + /******/ __webpack_require__.m = modules; + /******/ + /******/ // expose the module cache + /******/ __webpack_require__.c = installedModules; + /******/ + /******/ // identity function for calling harmony imports with the correct context + /******/ __webpack_require__.i = function(value) { return value; }; + /******/ + /******/ // define getter function for harmony exports + /******/ __webpack_require__.d = function(exports, name, getter) { + /******/ if(!__webpack_require__.o(exports, name)) { + /******/ Object.defineProperty(exports, name, { + /******/ configurable: false, + /******/ enumerable: true, + /******/ get: getter + /******/ }); + /******/ } + /******/ }; + /******/ + /******/ // getDefaultExport function for compatibility with non-harmony modules + /******/ __webpack_require__.n = function(module) { + /******/ var getter = module && module.__esModule ? + /******/ function getDefault() { return module['default']; } : + /******/ function getModuleExports() { return module; }; + /******/ __webpack_require__.d(getter, 'a', getter); + /******/ return getter; + /******/ }; + /******/ + /******/ // Object.prototype.hasOwnProperty.call + /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; + /******/ + /******/ // __webpack_public_path__ + /******/ __webpack_require__.p = ""; + /******/ + /******/ // Load entry module and return exports + /******/ return __webpack_require__(__webpack_require__.s = 2); + /******/ }) + /************************************************************************/ + /******/ ([ + /* 0 */ + /***/ (function(module, exports, __webpack_require__) { + + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + module.exports = { + type: function type(ob) { + return Object.prototype.toString.call(ob).slice(8, -1).toLowerCase(); + }, + isObject: function isObject(ob, real) { + if (real) { + return this.type(ob) === "object"; + } else { + return ob && (typeof ob === 'undefined' ? 'undefined' : _typeof(ob)) === 'object'; + } + }, + isFormData: function isFormData(val) { + return typeof FormData !== 'undefined' && val instanceof FormData; + }, + trim: function trim(str) { + return str.replace(/(^\s*)|(\s*$)/g, ''); + }, + encode: function encode(val) { + return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); + }, + formatParams: function formatParams(data) { + var str = ""; + var first = true; + var that = this; + if (!this.isObject(data)) { + return data; + } + + function _encode(sub, path) { + var encode = that.encode; + var type = that.type(sub); + if (type == "array") { + sub.forEach(function (e, i) { + if (!that.isObject(e)) { i = ""; } + _encode(e, path + ('%5B' + i + '%5D')); + }); + } else if (type == "object") { + for (var key in sub) { + if (path) { + _encode(sub[key], path + "%5B" + encode(key) + "%5D"); + } else { + _encode(sub[key], encode(key)); + } + } + } else { + if (!first) { + str += "&"; + } + first = false; + str += path + "=" + encode(sub); + } + } + + _encode(data, ""); + return str; + }, + + // Do not overwrite existing attributes + merge: function merge(a, b) { + for (var key in b) { + if (!a.hasOwnProperty(key)) { + a[key] = b[key]; + } else if (this.isObject(b[key], 1) && this.isObject(a[key], 1)) { + this.merge(a[key], b[key]); + } + } + return a; + } + }; + + /***/ }), + /* 1 */, + /* 2 */ + /***/ (function(module, exports, __webpack_require__) { + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var utils = __webpack_require__(0); + var isBrowser = typeof document !== "undefined"; + + var Fly = function () { + function Fly(engine) { + _classCallCheck(this, Fly); + + this.engine = engine || XMLHttpRequest; + + this.default = this; //For typeScript + + /** + * Add lock/unlock API for interceptor. + * + * Once an request/response interceptor is locked, the incoming request/response + * will be added to a queue before they enter the interceptor, they will not be + * continued until the interceptor is unlocked. + * + * @param [interceptor] either is interceptors.request or interceptors.response + */ + function wrap(interceptor) { + var resolve = void 0; + var reject = void 0; + + function _clear() { + interceptor.p = resolve = reject = null; + } + + utils.merge(interceptor, { + lock: function lock() { + if (!resolve) { + interceptor.p = new Promise(function (_resolve, _reject) { + resolve = _resolve; + reject = _reject; + }); + } + }, + unlock: function unlock() { + if (resolve) { + resolve(); + _clear(); + } + }, + clear: function clear() { + if (reject) { + reject("cancel"); + _clear(); + } + } + }); + } + + var interceptors = this.interceptors = { + response: { + use: function use(handler, onerror) { + this.handler = handler; + this.onerror = onerror; + } + }, + request: { + use: function use(handler) { + this.handler = handler; + } + } + }; + + var irq = interceptors.request; + var irp = interceptors.response; + wrap(irp); + wrap(irq); + + this.config = { + method: "GET", + baseURL: "", + headers: {}, + timeout: 0, + params: {}, // Default Url params + parseJson: true, // Convert response data to JSON object automatically. + withCredentials: false + }; + } + + _createClass(Fly, [{ + key: "request", + value: function request(url, data, options) { + var _this = this; + + var engine = new this.engine(); + var contentType = "Content-Type"; + var contentTypeLowerCase = contentType.toLowerCase(); + var interceptors = this.interceptors; + var requestInterceptor = interceptors.request; + var responseInterceptor = interceptors.response; + var requestInterceptorHandler = requestInterceptor.handler; + var promise = new Promise(function (resolve, reject) { + if (utils.isObject(url)) { + options = url; + url = options.url; + } + options = options || {}; + options.headers = options.headers || {}; + + function isPromise(p) { + // some polyfill implementation of Promise may be not standard, + // so, we test by duck-typing + return p && p.then && p.catch; + } + + /** + * If the request/response interceptor has been locked, + * the new request/response will enter a queue. otherwise, it will be performed directly. + * @param [promise] if the promise exist, means the interceptor is locked. + * @param [callback] + */ + function enqueueIfLocked(promise, callback) { + if (promise) { + promise.then(function () { + callback(); + }); + } else { + callback(); + } + } + + // make the http request + function makeRequest(options) { + data = options.body; + // Normalize the request url + url = utils.trim(options.url); + var baseUrl = utils.trim(options.baseURL || ""); + if (!url && isBrowser && !baseUrl) { url = location.href; } + if (url.indexOf("http") !== 0) { + var isAbsolute = url[0] === "/"; + if (!baseUrl && isBrowser) { + var arr = location.pathname.split("/"); + arr.pop(); + baseUrl = location.protocol + "//" + location.host + (isAbsolute ? "" : arr.join("/")); + } + if (baseUrl[baseUrl.length - 1] !== "/") { + baseUrl += "/"; + } + url = baseUrl + (isAbsolute ? url.substr(1) : url); + if (isBrowser) { + + // Normalize the url which contains the ".." or ".", such as + // "http://xx.com/aa/bb/../../xx" to "http://xx.com/xx" . + var t = document.createElement("a"); + t.href = url; + url = t.href; + } + } + + var responseType = utils.trim(options.responseType || ""); + var needQuery = ["GET", "HEAD", "DELETE", "OPTION"].indexOf(options.method) !== -1; + var dataType = utils.type(data); + var params = options.params || {}; + + // merge url params when the method is "GET" (data is object) + if (needQuery && dataType === "object") { + params = utils.merge(data, params); + } + // encode params to String + params = utils.formatParams(params); + + // save url params + var _params = []; + if (params) { + _params.push(params); + } + // Add data to url params when the method is "GET" (data is String) + if (needQuery && data && dataType === "string") { + _params.push(data); + } + + // make the final url + if (_params.length > 0) { + url += (url.indexOf("?") === -1 ? "?" : "&") + _params.join("&"); + } + + engine.open(options.method, url); + + // try catch for ie >=9 + try { + engine.withCredentials = !!options.withCredentials; + engine.timeout = options.timeout || 0; + if (responseType !== "stream") { + engine.responseType = responseType; + } + } catch (e) {} + + var customContentType = options.headers[contentType] || options.headers[contentTypeLowerCase]; + + // default content type + var _contentType = "application/x-www-form-urlencoded"; + // If the request data is json object, transforming it to json string, + // and set request content-type to "json". In browser, the data will + // be sent as RequestBody instead of FormData + if (utils.trim((customContentType || "").toLowerCase()) === _contentType) { + data = utils.formatParams(data); + } else if (!utils.isFormData(data) && ["object", "array"].indexOf(utils.type(data)) !== -1) { + _contentType = 'application/json;charset=utf-8'; + data = JSON.stringify(data); + } + //If user doesn't set content-type, set default. + if (!(customContentType || needQuery)) { + options.headers[contentType] = _contentType; + } + + for (var k in options.headers) { + if (k === contentType && utils.isFormData(data)) { + // Delete the content-type, Let the browser set it + delete options.headers[k]; + } else { + try { + // In browser environment, some header fields are readonly, + // write will cause the exception . + engine.setRequestHeader(k, options.headers[k]); + } catch (e) {} + } + } + + function onresult(handler, data, type) { + enqueueIfLocked(responseInterceptor.p, function () { + if (handler) { + //如果失败,添加请求信息 + if (type) { + data.request = options; + } + var ret = handler.call(responseInterceptor, data, Promise); + data = ret === undefined ? data : ret; + } + if (!isPromise(data)) { + data = Promise[type === 0 ? "resolve" : "reject"](data); + } + data.then(function (d) { + resolve(d); + }).catch(function (e) { + reject(e); + }); + }); + } + + function onerror(e) { + e.engine = engine; + onresult(responseInterceptor.onerror, e, -1); + } + + function Err(msg, status) { + this.message = msg; + this.status = status; + } + + engine.onload = function () { + try { + // The xhr of IE9 has not response field + var response = engine.response || engine.responseText; + if (response && options.parseJson && (engine.getResponseHeader(contentType) || "").indexOf("json") !== -1 + // Some third engine implementation may transform the response text to json object automatically, + // so we should test the type of response before transforming it + && !utils.isObject(response)) { + response = JSON.parse(response); + } + + var headers = engine.responseHeaders; + // In browser + if (!headers) { + headers = {}; + var items = (engine.getAllResponseHeaders() || "").split("\r\n"); + items.pop(); + items.forEach(function (e) { + if (!e) { return; } + var key = e.split(":")[0]; + headers[key] = engine.getResponseHeader(key); + }); + } + var status = engine.status; + var statusText = engine.statusText; + var _data = { data: response, headers: headers, status: status, statusText: statusText }; + // The _response filed of engine is set in adapter which be called in engine-wrapper.js + utils.merge(_data, engine._response); + if (status >= 200 && status < 300 || status === 304) { + _data.engine = engine; + _data.request = options; + onresult(responseInterceptor.handler, _data, 0); + } else { + var e = new Err(statusText, status); + e.response = _data; + onerror(e); + } + } catch (e) { + onerror(new Err(e.msg, engine.status)); + } + }; + + engine.onerror = function (e) { + onerror(new Err(e.msg || "Network Error", 0)); + }; + + engine.ontimeout = function () { + onerror(new Err("timeout [ " + engine.timeout + "ms ]", 1)); + }; + engine._options = options; + setTimeout(function () { + engine.send(needQuery ? null : data); + }, 0); + } + + enqueueIfLocked(requestInterceptor.p, function () { + utils.merge(options, JSON.parse(JSON.stringify(_this.config))); + var headers = options.headers; + headers[contentType] = headers[contentType] || headers[contentTypeLowerCase] || ""; + delete headers[contentTypeLowerCase]; + options.body = data || options.body; + url = utils.trim(url || ""); + options.method = options.method.toUpperCase(); + options.url = url; + var ret = options; + if (requestInterceptorHandler) { + ret = requestInterceptorHandler.call(requestInterceptor, options, Promise) || options; + } + if (!isPromise(ret)) { + ret = Promise.resolve(ret); + } + ret.then(function (d) { + //if options continue + if (d === options) { + makeRequest(d); + } else { + resolve(d); + } + }, function (err) { + reject(err); + }); + }); + }); + promise.engine = engine; + return promise; + } + }, { + key: "all", + value: function all(promises) { + return Promise.all(promises); + } + }, { + key: "spread", + value: function spread(callback) { + return function (arr) { + return callback.apply(null, arr); + }; + } + }]); + + return Fly; + }(); + + //For typeScript + + + Fly.default = Fly; + + ["get", "post", "put", "patch", "head", "delete"].forEach(function (e) { + Fly.prototype[e] = function (url, data, option) { + return this.request(url, data, utils.merge({ method: e }, option)); + }; + }); + ["lock", "unlock", "clear"].forEach(function (e) { + Fly.prototype[e] = function () { + this.interceptors.request[e](); + }; + }); + module.exports = Fly; + + /***/ }) + /******/ ]); + }); + }); + + var Fly = unwrapExports(fly); + + // the core stuff to id if it's calling with jsonql + var DATA_KEY = 'data'; + var ERROR_KEY = 'error'; + + var JSONQL_PATH = 'jsonql'; + // according to the json query spec + var CONTENT_TYPE = 'application/vnd.api+json'; + var CHARSET = 'charset=utf-8'; + var DEFAULT_HEADER = { + 'Accept': CONTENT_TYPE, + 'Content-Type': [ CONTENT_TYPE, CHARSET ].join(';') + }; + + // export const INDEX = 'index'; use INDEX_KEY instead + var DEFAULT_TYPE = 'any'; + + // @TODO remove this is not in use + // export const CLIENT_CONFIG_FILE = '.clients.json'; + // export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js'; + // type of resolvers + var QUERY_NAME = 'query'; + var MUTATION_NAME = 'mutation'; + var SOCKET_NAME = 'socket'; + // for calling the mutation + var PAYLOAD_PARAM_NAME = 'payload'; // @TODO shortern them + var CONDITION_PARAM_NAME = 'condition'; + var QUERY_ARG_NAME = 'args'; + var TIMESTAMP_PARAM_NAME = 'TS'; + // new jsonp + var JSONP_CALLBACK_NAME = 'jsonqlJsonpCallback'; + + // methods allow + var API_REQUEST_METHODS = ['POST', 'PUT']; + // for contract-cli + var KEY_WORD = 'continue'; + + var TYPE_KEY = 'type'; + var OPTIONAL_KEY = 'optional'; + var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word + var ARGS_KEY = 'args'; + var CHECKER_KEY = 'checker'; + var ALIAS_KEY = 'alias'; + var CHECKED_KEY = '__checked__'; + var LOGIN_NAME = 'login'; + var ISSUER_NAME = LOGIN_NAME; // legacy issue need to replace them later + var LOGOUT_NAME = 'logout'; + + var AUTH_HEADER = 'Authorization'; + var BEARER = 'Bearer'; + + // for client use @TODO need to clean this up some of them are not in use + var CREDENTIAL_STORAGE_KEY = 'jsonqlcredential'; + var CLIENT_STORAGE_KEY = 'jsonqlstore'; + var CLIENT_AUTH_KEY = 'jsonqlauthkey'; + // contract key + var CONTRACT_KEY_NAME = 'X-JSONQL-CV-KEY'; + var SHOW_CONTRACT_DESC_PARAM = {desc: 'y'}; + + var OR_SEPERATOR = '|'; + + var STRING_TYPE = 'string'; + var BOOLEAN_TYPE = 'boolean'; + var ARRAY_TYPE = 'array'; + var OBJECT_TYPE = 'object'; + + var NUMBER_TYPE = 'number'; + var ARRAY_TYPE_LFT = 'array.<'; + var ARRAY_TYPE_RGT = '>'; + + var NO_ERROR_MSG$1 = 'No message'; + var NO_STATUS_CODE = -1; + var HSA_ALGO = 'HS256'; + + /** + * 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; + + 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$1 = root.Symbol; + + /** 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$1 ? Symbol$1.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$1 ? Symbol$1.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); + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** Built-in value references. */ + var getPrototype = overArg(Object.getPrototypeOf, Object); + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @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 objectTag = '[object Object]'; + + /** Used for built-in method references. */ + var funcProto = Function.prototype, + objectProto$2 = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty$1 = objectProto$2.hasOwnProperty; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty$1.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * 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; + } + + /** `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$1 ? Symbol$1.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(''); + } + + // bunch of generic helpers + + /** + * DIY in Array + * @param {array} arr to check from + * @param {*} value to check against + * @return {boolean} true on found + */ + var inArray = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; + + // quick and dirty to turn non array to array + var toArray = function (arg) { return isArray(arg) ? arg : [arg]; }; + + /** + * @param {object} obj for search + * @param {string} key target + * @return {boolean} true on success + */ + var isObjectHasKey = function(obj, key) { + try { + var keys = Object.keys(obj); + return inArray(keys, key) + } catch(e) { + // @BUG when the obj is not an OBJECT we got some weird output + return false; + /* + console.info('obj', obj) + console.error(e) + throw new Error(e) + */ + } + }; + + // just a simple util method to return the error based on the status code + /** + * @param {number} statusCode to check + * @param {boolean} contract if this is a contract call or not + * @return {string} the error name + */ + function getErrorByStatus(statusCode, contract) { + if ( contract === void 0 ) contract = false; + + switch (statusCode) { + case 401: + return contract ? 'JsonqlContractAuthError' : 'JsonqlAuthorisationError'; + case 403: + return 'JsonqlForbiddenError'; + case 404: + return 'JsonqlResolverNotFoundError'; + case 406: + return 'Jsonql406Error'; + case 500: + return 'Jsonql500Error'; + default: + return 'JsonqlError'; + } + } + + /** + * This is a custom error to throw when server throw a 406 + * 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 Jsonql406Error = /*@__PURE__*/(function (Error) { + function Jsonql406Error() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + this.message = args[0]; + this.detail = args[1]; + // We can't access the static name from an instance + // but we can do it like this + this.className = Jsonql406Error.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Jsonql406Error); + } + } + + if ( Error ) Jsonql406Error.__proto__ = Error; + Jsonql406Error.prototype = Object.create( Error && Error.prototype ); + Jsonql406Error.prototype.constructor = Jsonql406Error; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 406; + }; + + staticAccessors.name.get = function () { + return 'Jsonql406Error'; + }; + + Object.defineProperties( Jsonql406Error, staticAccessors ); + + return Jsonql406Error; + }(Error)); + + /** + * This is a custom error to throw when server throw a 500 + * 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 Jsonql500Error = /*@__PURE__*/(function (Error) { + function Jsonql500Error() { + 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 = Jsonql500Error.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Jsonql500Error); + } + } + + if ( Error ) Jsonql500Error.__proto__ = Error; + Jsonql500Error.prototype = Object.create( Error && Error.prototype ); + Jsonql500Error.prototype.constructor = Jsonql500Error; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 500; + }; + + staticAccessors.name.get = function () { + return 'Jsonql500Error'; + }; + + Object.defineProperties( Jsonql500Error, staticAccessors ); + + return Jsonql500Error; + }(Error)); + + /** + * This is a custom error to throw when pass credential but fail + * 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 JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { + function JsonqlAuthorisationError() { + 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 = JsonqlAuthorisationError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlAuthorisationError); + } + } + + if ( Error ) JsonqlAuthorisationError.__proto__ = Error; + JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); + JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 401; + }; + + staticAccessors.name.get = function () { + return 'JsonqlAuthorisationError'; + }; + + Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); + + return JsonqlAuthorisationError; + }(Error)); + + /** + * This is a custom error when not supply the credential and try to get contract + * 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 JsonqlContractAuthError = /*@__PURE__*/(function (Error) { + function JsonqlContractAuthError() { + 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 = JsonqlContractAuthError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlContractAuthError); + } + } + + if ( Error ) JsonqlContractAuthError.__proto__ = Error; + JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); + JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 401; + }; + + staticAccessors.name.get = function () { + return 'JsonqlContractAuthError'; + }; + + Object.defineProperties( JsonqlContractAuthError, staticAccessors ); + + return JsonqlContractAuthError; + }(Error)); + + /** + * This is a custom error to throw when the resolver throw error and capture inside the middleware + * 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 JsonqlResolverAppError = /*@__PURE__*/(function (Error) { + function JsonqlResolverAppError() { + 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 = JsonqlResolverAppError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlResolverAppError); + } + } + + if ( Error ) JsonqlResolverAppError.__proto__ = Error; + JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); + JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 500; + }; + + staticAccessors.name.get = function () { + return 'JsonqlResolverAppError'; + }; + + Object.defineProperties( JsonqlResolverAppError, staticAccessors ); + + return JsonqlResolverAppError; + }(Error)); + + /** + * This is a custom error to throw when could not find the resolver + * 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 JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { + function JsonqlResolverNotFoundError() { + 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 = JsonqlResolverNotFoundError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlResolverNotFoundError); + } + } + + if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; + JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); + JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 404; + }; + + staticAccessors.name.get = function () { + return 'JsonqlResolverNotFoundError'; + }; + + Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); + + return JsonqlResolverNotFoundError; + }(Error)); + + // this get throw from within the checkOptions when run through the enum failed + var JsonqlEnumError = /*@__PURE__*/(function (Error) { + function JsonqlEnumError() { + 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 = JsonqlEnumError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlEnumError); + } + } + + if ( Error ) JsonqlEnumError.__proto__ = Error; + JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); + JsonqlEnumError.prototype.constructor = JsonqlEnumError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlEnumError'; + }; + + Object.defineProperties( JsonqlEnumError, staticAccessors ); + + return JsonqlEnumError; + }(Error)); + + // this will throw from inside the checkOptions + var JsonqlTypeError = /*@__PURE__*/(function (Error) { + function JsonqlTypeError() { + 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 = JsonqlTypeError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlTypeError); + } + } + + if ( Error ) JsonqlTypeError.__proto__ = Error; + JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); + JsonqlTypeError.prototype.constructor = JsonqlTypeError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlTypeError'; + }; + + Object.defineProperties( JsonqlTypeError, staticAccessors ); + + return JsonqlTypeError; + }(Error)); + + // allow supply a custom checker function + // if that failed then we throw this error + var JsonqlCheckerError = /*@__PURE__*/(function (Error) { + function JsonqlCheckerError() { + 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 = JsonqlCheckerError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlCheckerError); + } + } + + if ( Error ) JsonqlCheckerError.__proto__ = Error; + JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); + JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlCheckerError'; + }; + + Object.defineProperties( JsonqlCheckerError, staticAccessors ); + + return JsonqlCheckerError; + }(Error)); + + // custom validation error class + // when validaton failed + var JsonqlValidationError = /*@__PURE__*/(function (Error) { + function JsonqlValidationError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlValidationError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlValidationError); + } + } + + if ( Error ) JsonqlValidationError.__proto__ = Error; + JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); + JsonqlValidationError.prototype.constructor = JsonqlValidationError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlValidationError'; + }; + + Object.defineProperties( JsonqlValidationError, staticAccessors ); + + return JsonqlValidationError; + }(Error)); + + /** + * This is a custom error to throw whenever a error happen inside the jsonql + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ + var JsonqlError = /*@__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)); + + // this is from an example from Koa team to use for internal middleware ctx.throw + // but after the test the res.body part is unable to extract the required data + // I keep this one here for future reference + + var JsonqlServerError = /*@__PURE__*/(function (Error) { + function JsonqlServerError(statusCode, message) { + Error.call(this, message); + this.statusCode = statusCode; + this.className = JsonqlServerError.name; + } + + if ( Error ) JsonqlServerError.__proto__ = Error; + JsonqlServerError.prototype = Object.create( Error && Error.prototype ); + JsonqlServerError.prototype.constructor = JsonqlServerError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlServerError'; + }; + + Object.defineProperties( JsonqlServerError, staticAccessors ); + + return JsonqlServerError; + }(Error)); + + // server side + + var errors = /*#__PURE__*/Object.freeze({ + __proto__: null, + Jsonql406Error: Jsonql406Error, + Jsonql500Error: Jsonql500Error, + JsonqlAuthorisationError: JsonqlAuthorisationError, + JsonqlContractAuthError: JsonqlContractAuthError, + JsonqlResolverAppError: JsonqlResolverAppError, + JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, + JsonqlEnumError: JsonqlEnumError, + JsonqlTypeError: JsonqlTypeError, + JsonqlCheckerError: JsonqlCheckerError, + JsonqlValidationError: JsonqlValidationError, + JsonqlError: JsonqlError, + JsonqlServerError: JsonqlServerError + }); + + // this will add directly to the then call in each http call + var JsonqlError$1 = JsonqlError; + + /** + * We can not just check something like result.data what if the result if false? + * @param {object} obj the result object + * @param {string} key we want to check if its exist or not + * @return {boolean} true on found + */ + var isObjectHasKey$1 = function (obj, key) { + var keys = Object.keys(obj); + return !!keys.filter(function (k) { return key === k; }).length; + }; + + /** + * It will ONLY have our own jsonql specific implement check + * @param {object} result the server return result + * @return {object} this will just throw error + */ + function clientErrorsHandler(result) { + if (isObjectHasKey$1(result, 'error')) { + var error = result.error; + var className = error.className; + var name = error.name; + var errorName = className || name; + // just throw the whole thing back + var msg = error.message || NO_ERROR_MSG$1; + var detail = error.detail || error; + if (errorName && errors[errorName]) { + throw new errors[className](msg, detail) + } + throw new JsonqlError$1(msg, detail) + } + // pass through to the next + return result; + } + + // get error name by instance + var UNKNOWN_ERROR = 'unknown'; + + /** + * @param {array} errs list of errors to compare from + * @param {object} e the error captured + * @return {array} filtered with name as value + */ + function mapErrToName(errs, e) { + return errs.filter(function (err) { return e instanceof err; }) + .map(function (err) { return err.name; }) + } + + /** + * @param {array} errs list of errors to compare from + * @param {object} e the error captured + * @return {string} name of the error object + */ + function getErrorNameByInstance(errs, e) { + var error = mapErrToName(errs, e); + return error.length ? error[0] : UNKNOWN_ERROR + } + + /** + * the same as above with a default JsonqlError as default + * @param {array} errs same + * @param {object} e error itself + * @return {string} the name of the error + */ + function getErrorNameByInstanceWithDefault(errs, e) { + var name = getErrorNameByInstance(errs, e); + return name === UNKNOWN_ERROR ? 'JsonqlError' : name; + } + + /** + * this will put into generator call at the very end and catch + * the error throw from inside then throw again + * this is necessary because we split calls inside and the throw + * will not reach the actual client unless we do it this way + * @param {object} e Error + * @return {void} just throw + */ + function finalCatch(e) { + // this is a hack to get around the validateAsync not actually throw error + // instead it just rejected it with the array of failed parameters + if (Array.isArray(e)) { + // if we want the message then I will have to create yet another function + // to wrap this function to provide the name prop + throw new JsonqlValidationError('', e) + } + var msg = e.message || NO_ERROR_MSG$1; + var detail = e.detail || e; + switch (true) { + case e instanceof Jsonql406Error: + throw new Jsonql406Error(msg, detail) + case e instanceof Jsonql500Error: + throw new Jsonql500Error(msg, detail) + case e instanceof JsonqlAuthorisationError: + throw new JsonqlAuthorisationError(msg, detail) + case e instanceof JsonqlContractAuthError: + throw new JsonqlContractAuthError(msg, detail) + case e instanceof JsonqlResolverAppError: + throw new JsonqlResolverAppError(msg, detail) + case e instanceof JsonqlResolverNotFoundError: + throw new JsonqlResolverNotFoundError(msg, detail) + case e instanceof JsonqlEnumError: + throw new JsonqlEnumError(msg, detail) + case e instanceof JsonqlTypeError: + throw new JsonqlTypeError(msg, detail) + case e instanceof JsonqlCheckerError: + throw new JsonqlCheckerError(msg, detail) + case e instanceof JsonqlValidationError: + throw new JsonqlValidationError(msg, detail) + case e instanceof JsonqlServerError: + throw new JsonqlServerError(msg, detail) + default: + throw new JsonqlError(msg, detail) + } + } + + // jsonql-errors main interface + var JSONQL_ERRORS_INFO = '__PLACEHOLDER__'; + + var errors$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + JSONQL_ERRORS_INFO: JSONQL_ERRORS_INFO, + UNKNOWN_ERROR: UNKNOWN_ERROR, + getErrorByStatus: getErrorByStatus, + clientErrorsHandler: clientErrorsHandler, + finalCatch: finalCatch, + getErrorNameByInstance: getErrorNameByInstance, + getErrorNameByInstanceWithDefault: getErrorNameByInstanceWithDefault, + Jsonql406Error: Jsonql406Error, + Jsonql500Error: Jsonql500Error, + JsonqlAuthorisationError: JsonqlAuthorisationError, + JsonqlContractAuthError: JsonqlContractAuthError, + JsonqlResolverAppError: JsonqlResolverAppError, + JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, + JsonqlEnumError: JsonqlEnumError, + JsonqlTypeError: JsonqlTypeError, + JsonqlCheckerError: JsonqlCheckerError, + JsonqlValidationError: JsonqlValidationError, + JsonqlError: JsonqlError, + JsonqlServerError: JsonqlServerError + }); + + // split the contract into the node side and the generic side + /** + * Check if the json is a contract file or not + * @param {object} contract json object + * @return {boolean} true + */ + function checkIsContract(contract) { + return isPlainObject(contract) + && ( + isObjectHasKey(contract, QUERY_NAME) + || isObjectHasKey(contract, MUTATION_NAME) + || isObjectHasKey(contract, SOCKET_NAME) + ) + } + + /** + * Wrapper method that check if it's contract then return the contract or false + * @param {object} contract the object to check + * @return {boolean | object} false when it's not + */ + function isContract(contract) { + return checkIsContract(contract) ? contract : false; + } + + /** + * generate a 32bit hash based on the function.toString() + * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery + * @param {string} s the converted to string function + * @return {string} the hashed function string + */ + function hashCode(s) { + return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) + } + + // take only the module part which is what we use here + /** + * @param {object} jsonqlInstance the init instance of jsonql client + * @param {object} contract the static contract + * @return {object} contract may be from server + */ + var getContractFromConfig = function(jsonqlInstance, contract) { + if ( contract === void 0 ) contract = {}; + + if (isContract(contract)) { + return Promise.resolve(contract) + } + return jsonqlInstance.getContract() + }; + // wrapper method to make sure it's a string + var hashCode$1 = function (str) { return hashCode(str) + ''; }; + var USERDATA_TABLE = 'userdata'; + var CLS_LOCAL_STORE_NAME = 'localStore'; + var CLS_SESS_STORE_NAME = 'sessionStore'; + var CLS_CONTRACT_NAME = 'contract'; + var CLS_PROFILE_IDX = 'prof_idx'; + var ZERO_IDX = 0; + + /** + * The code was extracted from: + * https://github.com/davidchambers/Base64.js + */ + + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + + function InvalidCharacterError(message) { + this.message = message; + } + + InvalidCharacterError.prototype = new Error(); + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + + function polyfill (input) { + var str = String(input).replace(/=+$/, ''); + if (str.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); + } + for ( + // initialize result and counters + var bc = 0, bs, buffer, idx = 0, output = ''; + // get next character + buffer = str.charAt(idx++); + // character found in table? initialize bit storage and add its ascii value; + ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, + // and if not first of each 4 characters, + // convert the first 8 bits to one ascii character + bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 + ) { + // try to find character in table (0-63, not found => -1) + buffer = chars.indexOf(buffer); + } + return output; + } + + + var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; + + function b64DecodeUnicode(str) { + return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { + var code = p.charCodeAt(0).toString(16).toUpperCase(); + if (code.length < 2) { + code = '0' + code; + } + return '%' + code; + })); + } + + var base64_url_decode = function(str) { + var output = str.replace(/-/g, "+").replace(/_/g, "/"); + switch (output.length % 4) { + case 0: + break; + case 2: + output += "=="; + break; + case 3: + output += "="; + break; + default: + throw "Illegal base64url string!"; + } + + try{ + return b64DecodeUnicode(output); + } catch (err) { + return atob(output); + } + }; + + function InvalidTokenError(message) { + this.message = message; + } + + InvalidTokenError.prototype = new Error(); + InvalidTokenError.prototype.name = 'InvalidTokenError'; + + var lib = function (token,options) { + if (typeof token !== 'string') { + throw new InvalidTokenError('Invalid token specified'); + } + + options = options || {}; + var pos = options.header === true ? 0 : 1; + try { + return JSON.parse(base64_url_decode(token.split('.')[pos])); + } catch (e) { + throw new InvalidTokenError('Invalid token specified: ' + e.message); + } + }; + + var InvalidTokenError_1 = InvalidTokenError; + lib.InvalidTokenError = InvalidTokenError_1; + + /** `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; + }; + + // when the user is login with the jwt + + 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 = lib(token); + return validate(t) + } + throw new JsonqlError('Token must be a string!') + } + + /** + * Check several parameter that there is something in the param + * @param {*} param input + * @return {boolean} + */ + var isNotEmpty = function (a) { + if (isArray(a)) { + return true; + } + return a !== undefined && a !== null && trim(a) !== ''; + }; + + /** `Object#toString` result references. */ + var numberTag = '[object Number]'; + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + // validator numbers + /** + * @2015-05-04 found a problem if the value is a number like string + * it will pass, so add a chck if it's string before we pass to next + * @param {number} value expected value + * @return {boolean} true if OK + */ + var checkIsNumber = function(value) { + return isString(value) ? false : !isNaN( parseFloat(value) ) + }; + + // check for boolean + + /** + * @param {boolean} value expected + * @return {boolean} true if OK + */ + var checkIsBoolean = function(value) { + return value !== null && value !== undefined && typeof value === 'boolean' + }; + + // validate any thing only check if there is something + + /** + * @param {*} value the value + * @param {boolean} [checkNull=true] strict check if there is null value + * @return {boolean} true is OK + */ + var checkIsAny = function(value, checkNull) { + if ( checkNull === void 0 ) checkNull = true; + + if (value !== undefined && value !== '' && trim(value) !== '') { + if (checkNull === false || (checkNull === true && value !== null)) { + return true; + } + } + return false; + }; + + // Good practice rule - No magic number + + var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; + var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; + var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; + // @TODO the jsdoc return array. and we should also allow array syntax + var DEFAULT_TYPE$1 = DEFAULT_TYPE; + var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; + var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; + + var TYPE_KEY$1 = TYPE_KEY; + var OPTIONAL_KEY$1 = OPTIONAL_KEY; + var ENUM_KEY$1 = ENUM_KEY; + var ARGS_KEY$1 = ARGS_KEY; + var CHECKER_KEY$1 = CHECKER_KEY; + var ALIAS_KEY$1 = ALIAS_KEY; + + var ARRAY_TYPE$1 = ARRAY_TYPE; + var OBJECT_TYPE$1 = OBJECT_TYPE; + var STRING_TYPE$1 = STRING_TYPE; + var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; + var NUMBER_TYPE$1 = NUMBER_TYPE; + var KEY_WORD$1 = KEY_WORD; + var OR_SEPERATOR$1 = OR_SEPERATOR; + + // not actually in use + // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; + + // primitive types + + /** + * this is a wrapper method to call different one based on their type + * @param {string} type to check + * @return {function} a function to handle the type + */ + var combineFn = function(type) { + switch (type) { + case NUMBER_TYPE$1: + return checkIsNumber; + case STRING_TYPE$1: + return checkIsString; + case BOOLEAN_TYPE$1: + return checkIsBoolean; + default: + return checkIsAny; + } + }; + + // validate array type + + /** + * @param {array} value expected + * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well + * @return {boolean} true if OK + */ + var checkIsArray = function(value, type) { + if ( type === void 0 ) type=''; + + if (isArray(value)) { + if (type === '' || trim(type)==='') { + return true; + } + // we test it in reverse + // @TODO if the type is an array (OR) then what? + // we need to take into account this could be an array + var c = value.filter(function (v) { return !combineFn(type)(v); }); + return !(c.length > 0) + } + return false; + }; + + /** + * check if it matches the array. pattern + * @param {string} type + * @return {boolean|array} false means NO, always return array + */ + var isArrayLike = function(type) { + // @TODO could that have something like array<> instead of array.<>? missing the dot? + // because type script is Array without the dot + if (type.indexOf(ARRAY_TYPE_LFT$1) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { + var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); + if (_type.indexOf(OR_SEPERATOR$1)) { + return _type.split(OR_SEPERATOR$1) + } + return [_type] + } + return false; + }; + + /** + * we might encounter something like array. then we need to take it apart + * @param {object} p the prepared object for processing + * @param {string|array} type the type came from + * @return {boolean} for the filter to operate on + */ + var arrayTypeHandler = function(p, type) { + var arg = p.arg; + // need a special case to handle the OR type + // we need to test the args instead of the type(s) + if (type.length > 1) { + return !arg.filter(function (v) { return ( + !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) + ); }).length; + } + // type is array so this will be or! + return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length; + }; + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]'; + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** Used for built-in method references. */ + var objectProto$3 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$2 = objectProto$3.hasOwnProperty; + + /** Built-in value references. */ + var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + function stubFalse() { + return false; + } + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Built-in value references. */ + var Buffer = moduleExports ? root.Buffer : undefined; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER = 9007199254740991; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER$1 = 9007199254740991; + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; + } + + /** `Object#toString` result references. */ + var argsTag$1 = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag$1 = '[object Number]', + objectTag$1 = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag$1 = '[object String]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag$1] = + typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag$1] = + typedArrayTags[weakMapTag] = false; + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** Detect free variable `exports`. */ + var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports$1 && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** Used for built-in method references. */ + var objectProto$4 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$3 = objectProto$4.hasOwnProperty; + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$3.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** Used for built-in method references. */ + var objectProto$5 = Object.prototype; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; + + return value === proto; + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeKeys = overArg(Object.keys, Object); + + /** Used for built-in method references. */ + var objectProto$6 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$4 = objectProto$6.hasOwnProperty; + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$4.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** `Object#toString` result references. */ + var asyncTag = '[object AsyncFunction]', + funcTag$1 = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike$1(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** Used for built-in method references. */ + var arrayProto = Array.prototype; + + /** Built-in value references. */ + var splice = arrayProto.splice; + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** Used to detect overreaching core-js shims. */ + var coreJsData = root['__core-js_shared__']; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** Used for built-in method references. */ + var funcProto$1 = Function.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString$1 = funcProto$1.toString; + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString$1.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used for built-in method references. */ + var funcProto$2 = Function.prototype, + objectProto$7 = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString$2 = funcProto$2.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty$5 = objectProto$7.hasOwnProperty; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString$2.call(hasOwnProperty$5).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /* Built-in method references that are verified to be native. */ + var Map$1 = getNative(root, 'Map'); + + /* Built-in method references that are verified to be native. */ + var nativeCreate = getNative(Object, 'create'); + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used for built-in method references. */ + var objectProto$8 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$6 = objectProto$8.hasOwnProperty; + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty$6.call(data, key) ? data[key] : undefined; + } + + /** Used for built-in method references. */ + var objectProto$9 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$7 = objectProto$9.hasOwnProperty; + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key); + } + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; + return this; + } + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map$1 || ListCache), + 'string': new Hash + }; + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED$2); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** Built-in value references. */ + var Uint8Array$1 = root.Uint8Array; + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$1 = 1, + COMPARE_UNORDERED_FLAG$1 = 2; + + /** `Object#toString` result references. */ + var boolTag$1 = '[object Boolean]', + dateTag$1 = '[object Date]', + errorTag$1 = '[object Error]', + mapTag$1 = '[object Map]', + numberTag$2 = '[object Number]', + regexpTag$1 = '[object RegExp]', + setTag$1 = '[object Set]', + stringTag$2 = '[object String]', + symbolTag$1 = '[object Symbol]'; + + var arrayBufferTag$1 = '[object ArrayBuffer]', + dataViewTag$1 = '[object DataView]'; + + /** Used to convert symbols to primitives and strings. */ + var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined, + symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag$1: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag$1: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array$1(object), new Uint8Array$1(other))) { + return false; + } + return true; + + case boolTag$1: + case dateTag$1: + case numberTag$2: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag$1: + return object.name == other.name && object.message == other.message; + + case regexpTag$1: + case stringTag$2: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag$1: + var convert = mapToArray; + + case setTag$1: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG$1; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag$1: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + function stubArray() { + return []; + } + + /** Used for built-in method references. */ + var objectProto$a = Object.prototype; + + /** Built-in value references. */ + var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols = Object.getOwnPropertySymbols; + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable$1.call(object, symbol); + }); + }; + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$2 = 1; + + /** Used for built-in method references. */ + var objectProto$b = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$8 = objectProto$b.hasOwnProperty; + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(root, 'DataView'); + + /* Built-in method references that are verified to be native. */ + var Promise$1 = getNative(root, 'Promise'); + + /* Built-in method references that are verified to be native. */ + var Set$1 = getNative(root, 'Set'); + + /* Built-in method references that are verified to be native. */ + var WeakMap$1 = getNative(root, 'WeakMap'); + + /** `Object#toString` result references. */ + var mapTag$2 = '[object Map]', + objectTag$2 = '[object Object]', + promiseTag = '[object Promise]', + setTag$2 = '[object Set]', + weakMapTag$1 = '[object WeakMap]'; + + var dataViewTag$2 = '[object DataView]'; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map$1), + promiseCtorString = toSource(Promise$1), + setCtorString = toSource(Set$1), + weakMapCtorString = toSource(WeakMap$1); + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$2) || + (Map$1 && getTag(new Map$1) != mapTag$2) || + (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || + (Set$1 && getTag(new Set$1) != setTag$2) || + (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag$2 ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag$2; + case mapCtorString: return mapTag$2; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag$2; + case weakMapCtorString: return weakMapTag$1; + } + } + return result; + }; + } + + var getTag$1 = getTag; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$3 = 1; + + /** `Object#toString` result references. */ + var argsTag$2 = '[object Arguments]', + arrayTag$1 = '[object Array]', + objectTag$3 = '[object Object]'; + + /** Used for built-in method references. */ + var objectProto$c = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$9 = objectProto$c.hasOwnProperty; + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag$1 : getTag$1(object), + othTag = othIsArr ? arrayTag$1 : getTag$1(other); + + objTag = objTag == argsTag$2 ? objectTag$3 : objTag; + othTag = othTag == argsTag$2 ? objectTag$3 : othTag; + + var objIsObj = objTag == objectTag$3, + othIsObj = othTag == objectTag$3, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { + var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$4 = 1, + COMPARE_UNORDERED_FLAG$2 = 2; + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** Error message constants. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** Used to match property names within property paths. */ + var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** Used as references for various `Number` constants. */ + var INFINITY$1 = 1 / 0; + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$5 = 1, + COMPARE_UNORDERED_FLAG$3 = 2; + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); + }; + } + + /** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + function identity(value) { + return value; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ + function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + // validate object type + /** + * @TODO if provide with the keys then we need to check if the key:value type as well + * @param {object} value expected + * @param {array} [keys=null] if it has the keys array to compare as well + * @return {boolean} true if OK + */ + var checkIsObject = function(value, keys) { + if ( keys === void 0 ) keys=null; + + if (isPlainObject(value)) { + if (!keys) { + return true; + } + if (checkIsArray(keys)) { + // please note we DON'T care if some is optional + // plese refer to the contract.json for the keys + return !keys.filter(function (key) { + var _value = value[key.name]; + return !(key.type.length > key.type.filter(function (type) { + var tmp; + if (_value !== undefined) { + if ((tmp = isArrayLike(type)) !== false) { + return !arrayTypeHandler({arg: _value}, tmp) + // return tmp.filter(t => !checkIsArray(_value, t)).length; + // @TODO there might be an object within an object with keys as well :S + } + return !combineFn(type)(_value) + } + return true; + }).length) + }).length; + } + } + return false; + }; + + /** + * fold this into it's own function to handler different object type + * @param {object} p the prepared object for process + * @return {boolean} + */ + var objectTypeHandler = function(p) { + var arg = p.arg; + var param = p.param; + var _args = [arg]; + if (Array.isArray(param.keys) && param.keys.length) { + _args.push(param.keys); + } + // just simple check + return Reflect.apply(checkIsObject, null, _args) + }; + + // move the index.js code here that make more sense to find where things are + // import debug from 'debug' + // const debugFn = debug('jsonql-params-validator:validator') + // also export this for use in other places + + /** + * We need to handle those optional parameter without a default value + * @param {object} params from contract.json + * @return {boolean} for filter operation false is actually OK + */ + var optionalHandler = function( params ) { + var arg = params.arg; + var param = params.param; + if (isNotEmpty(arg)) { + // debug('call optional handler', arg, params); + // loop through the type in param + return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } + ).length) + } + return false; + }; + + /** + * actually picking the validator + * @param {*} type for checking + * @param {*} value for checking + * @return {boolean} true on OK + */ + var validateHandler = function(type, value) { + var tmp; + switch (true) { + case type === OBJECT_TYPE$1: + // debugFn('call OBJECT_TYPE') + return !objectTypeHandler(value) + case type === ARRAY_TYPE$1: + // debugFn('call ARRAY_TYPE') + return !checkIsArray(value.arg) + // @TODO when the type is not present, it always fall through here + // so we need to find a way to actually pre-check the type first + // AKA check the contract.json map before running here + case (tmp = isArrayLike(type)) !== false: + // debugFn('call ARRAY_LIKE: %O', value) + return !arrayTypeHandler(value, tmp) + default: + return !combineFn(type)(value.arg) + } + }; + + /** + * it get too longer to fit in one line so break it out from the fn below + * @param {*} arg value + * @param {object} param config + * @return {*} value or apply default value + */ + var getOptionalValue = function(arg, param) { + if (arg !== undefined) { + return arg; + } + return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null) + }; + + /** + * padding the arguments with defaultValue if the arguments did not provide the value + * this will be the name export + * @param {array} args normalized arguments + * @param {array} params from contract.json + * @return {array} merge the two together + */ + var normalizeArgs = function(args, params) { + // first we should check if this call require a validation at all + // there will be situation where the function doesn't need args and params + if (!checkIsArray(params)) { + // debugFn('params value', params) + throw new JsonqlError(PARAMS_NOT_ARRAY_ERR) + } + if (params.length === 0) { + return []; + } + if (!checkIsArray(args)) { + throw new JsonqlError(ARGS_NOT_ARRAY_ERR) + } + // debugFn(args, params); + // fall through switch + switch(true) { + case args.length == params.length: // standard + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, + param: params[i] + } + ); }) + case params[0].variable === true: // using spread syntax + var type = params[0].type; + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, // keep the index for reference + param: params[i] || { type: type, name: '_' } + } + ); }) + // with optional defaultValue parameters + case args.length < params.length: + return params.map(function (param, i) { return ( + { + param: param, + index: i, + arg: getOptionalValue(args[i], param), + optional: param.optional || false + } + ); }) + // this one pass more than it should have anything after the args.length will be cast as any type + case args.length > params.length: + var ctn = params.length; + // this happens when we have those array. type + var _type = [ DEFAULT_TYPE$1 ]; + // we only looking at the first one, this might be a @BUG + /* + if ((tmp = isArrayLike(params[0].type[0])) !== false) { + _type = tmp; + } */ + // if we use the params as guide then the rest will get throw out + // which is not what we want, instead, anything without the param + // will get a any type and optional flag + return args.map(function (arg, i) { + var optional = i >= ctn ? true : !!params[i].optional; + var param = params[i] || { type: _type, name: ("_" + i) }; + return { + arg: optional ? getOptionalValue(arg, param) : arg, + index: i, + param: param, + optional: optional + } + }) + // @TODO find out if there is more cases not cover + default: // this should never happen + // debugFn('args', args) + // debugFn('params', params) + // this is unknown therefore we just throw it! + throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) + } + }; + + // what we want is after the validaton we also get the normalized result + // which is with the optional property if the argument didn't provide it + /** + * process the array of params back to their arguments + * @param {array} result the params result + * @return {array} arguments + */ + var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; + + /** + * validator main interface + * @param {array} args the arguments pass to the method call + * @param {array} params from the contract for that method + * @param {boolean} [withResul=false] if true then this will return the normalize result as well + * @return {array} empty array on success, or failed parameter and reasons + */ + var validateSync = function(args, params, withResult) { + var obj; + + if ( withResult === void 0 ) withResult = false; + var cleanArgs = normalizeArgs(args, params); + var checkResult = cleanArgs.filter(function (p) { + // v1.4.4 this fixed the problem, the root level optional is from the last fn + if (p.optional === true || p.param.optional === true) { + return optionalHandler(p) + } + // because array of types means OR so if one pass means pass + return !(p.param.type.length > p.param.type.filter( + function (type) { return validateHandler(type, p); } + ).length) + }); + // using the same convention we been using all this time + return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) + }; + + /** + * A wrapper method that return promise + * @param {array} args arguments + * @param {array} params from contract.json + * @param {boolean} [withResul=false] if true then this will return the normalize result as well + * @return {object} promise.then or catch + */ + var validateAsync = function(args, params, withResult) { + if ( withResult === void 0 ) withResult = false; + + return new Promise(function (resolver, rejecter) { + var result = validateSync(args, params, withResult); + if (withResult) { + return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) + : resolver(result[DATA_KEY]) + } + // the different is just in the then or catch phrase + return result.length ? rejecter(result) : resolver([]) + }) + }; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** Detect free variable `exports`. */ + var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; + + /** Built-in value references. */ + var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, + allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** Built-in value references. */ + var objectCreate = Object.create; + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike$1(value); + } + + /** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; + } + + /** Used for built-in method references. */ + var objectProto$d = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$a = objectProto$d.hasOwnProperty; + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty$a.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** Used for built-in method references. */ + var objectProto$e = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$b = objectProto$e.hasOwnProperty; + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty$b.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike$1(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeMax = Math.max; + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ + function constant(value) { + return function() { + return value; + }; + } + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeNow = Date.now; + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike$1(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** Error message constants. */ + var FUNC_ERROR_TEXT$1 = 'Expected a function'; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$1); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols$1 = Object.getOwnPropertySymbols; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = baseIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(baseIteratee(predicate))); + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate), baseForOwn); + } + + /** + * @param {array} arr Array for check + * @param {*} value target + * @return {boolean} true on successs + */ + var isInArray = function(arr, value) { + return !!arr.filter(function (a) { return a === value; }).length; + }; + + var isObjectHasKey$2 = function(obj, key) { + var keys = Object.keys(obj); + return isInArray(keys, key) + }; + + // just not to make my head hurt + var isEmpty = function (value) { return !isNotEmpty(value); }; + + /** + * Map the alias to their key then grab their value over + * @param {object} config the user supplied config + * @param {object} appProps the default option map + * @return {object} the config keys replaced with the appProps key by the ALIAS + */ + function mapAliasConfigKeys(config, appProps) { + // need to do two steps + // 1. take key with alias key + var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$1]; } ); + if (isEqual(aliasMap, {})) { + return config; + } + return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) + } + + /** + * We only want to run the valdiation against the config (user supplied) value + * but keep the defaultOptions untouch + * @param {object} config configuraton supplied by user + * @param {object} appProps the default options map + * @return {object} the pristine values that will add back to the final output + */ + function preservePristineValues(config, appProps) { + // @BUG this will filter out those that is alias key + // we need to first map the alias keys back to their full key + var _config = mapAliasConfigKeys(config, appProps); + // take the default value out + var pristineValues = mapValues( + omitBy(appProps, function (value, key) { return isObjectHasKey$2(_config, key); }), + function (value) { return value.args; } + ); + // for testing the value + var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !isObjectHasKey$2(_config, key); }); + // output + return { + pristineValues: pristineValues, + checkAgainstAppProps: checkAgainstAppProps, + config: _config // passing this correct values back + } + } + + /** + * This will take the value that is ONLY need to check + * @param {object} config that one + * @param {object} props map for creating checking + * @return {object} put that arg into the args + */ + function processConfigAction(config, props) { + // debugFn('processConfigAction', props) + // v.1.2.0 add checking if its mark optional and the value is empty then pass + return mapValues(props, function (value, key) { + var obj, obj$1; + + return ( + config[key] === undefined || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) + ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) + : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) + ); + } + ) + } + + /** + * Quick transform + * @TODO we should only validate those that is pass from the config + * and pass through those values that is from the defaultOptions + * @param {object} opts that one + * @param {object} appProps mutation configuration options + * @return {object} put that arg into the args + */ + function prepareArgsForValidation(opts, appProps) { + var ref = preservePristineValues(opts, appProps); + var config = ref.config; + var pristineValues = ref.pristineValues; + var checkAgainstAppProps = ref.checkAgainstAppProps; + // output + return [ + processConfigAction(config, checkAgainstAppProps), + pristineValues + ] + } + + // breaking the whole thing up to see what cause the multiple calls issue + + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:options:validation') + + /** + * just make sure it returns an array to use + * @param {*} arg input + * @return {array} output + */ + var toArray$1 = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; + + /** + * DIY in array + * @param {array} arr to check against + * @param {*} value to check + * @return {boolean} true on OK + */ + var inArray$1 = function (arr, value) { return ( + !!arr.filter(function (v) { return v === value; }).length + ); }; + + /** + * break out to make the code easier to read + * @param {object} value to process + * @param {function} cb the validateSync + * @return {array} empty on success + */ + function validateHandler$1(value, cb) { + var obj; + + // cb is the validateSync methods + var args = [ + [ value[ARGS_KEY$1] ], + [( obj = {}, obj[TYPE_KEY$1] = toArray$1(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] + ]; + // debugFn('validateHandler', args) + return Reflect.apply(cb, null, args) + } + + /** + * Check against the enum value if it's provided + * @param {*} value to check + * @param {*} enumv to check against if it's not false + * @return {boolean} true on OK + */ + var enumHandler = function (value, enumv) { + if (checkIsArray(enumv)) { + return inArray$1(enumv, value) + } + return true; + }; + + /** + * Allow passing a function to check the value + * There might be a problem here if the function is incorrect + * and that will makes it hard to debug what is going on inside + * @TODO there could be a few feature add to this one under different circumstance + * @param {*} value to check + * @param {function} checker for checking + */ + var checkerHandler = function (value, checker) { + try { + return isFunction(checker) ? checker.apply(null, [value]) : false; + } catch (e) { + return false; + } + }; + + /** + * Taken out from the runValidaton this only validate the required values + * @param {array} args from the config2argsAction + * @param {function} cb validateSync + * @return {array} of configuration values + */ + function runValidationAction(cb) { + return function (value, key) { + // debugFn('runValidationAction', key, value) + if (value[KEY_WORD$1]) { + return value[ARGS_KEY$1] + } + var check = validateHandler$1(value, cb); + if (check.length) { + // log('runValidationAction', key, value) + throw new JsonqlTypeError(key, check) + } + if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { + // log(ENUM_KEY, value[ENUM_KEY]) + throw new JsonqlEnumError(key) + } + if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { + // log(CHECKER_KEY, value[CHECKER_KEY]) + throw new JsonqlCheckerError(key) + } + return value[ARGS_KEY$1] + } + } + + /** + * @param {object} args from the config2argsAction + * @param {function} cb validateSync + * @return {object} of configuration values + */ + function runValidation(args, cb) { + var argsForValidate = args[0]; + var pristineValues = args[1]; + // turn the thing into an array and see what happen here + // debugFn('_args', argsForValidate) + var result = mapValues(argsForValidate, runValidationAction(cb)); + return merge(result, pristineValues) + } + + /// this is port back from the client to share across all projects + + // import debug from 'debug' + // const debugFn = debug('jsonql-params-validator:check-options-async') + + /** + * Quick transform + * @param {object} config that one + * @param {object} appProps mutation configuration options + * @return {object} put that arg into the args + */ + var configToArgs = function (config, appProps) { + return Promise.resolve( + prepareArgsForValidation(config, appProps) + ) + }; + + /** + * @param {object} config user provide configuration option + * @param {object} appProps mutation configuration options + * @param {object} constProps the immutable configuration options + * @param {function} cb the validateSync method + * @return {object} Promise resolve merge config object + */ + function checkOptionsAsync(config, appProps, constProps, cb) { + if ( config === void 0 ) config = {}; + + return configToArgs(config, appProps) + .then(function (args1) { return runValidation(args1, cb); }) + // next if every thing good then pass to final merging + .then(function (args2) { return merge({}, args2, constProps); }) + } + + // create function to construct the config entry so we don't need to keep building object + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:construct-config'); + /** + * @param {*} args value + * @param {string} type for value + * @param {boolean} [optional=false] + * @param {boolean|array} [enumv=false] + * @param {boolean|function} [checker=false] + * @return {object} config entry + */ + function constructConfig(args, type, optional, enumv, checker, alias) { + if ( optional === void 0 ) optional=false; + if ( enumv === void 0 ) enumv=false; + if ( checker === void 0 ) checker=false; + if ( alias === void 0 ) alias=false; + + var base = {}; + base[ARGS_KEY] = args; + base[TYPE_KEY] = type; + if (optional === true) { + base[OPTIONAL_KEY] = true; + } + if (checkIsArray(enumv)) { + base[ENUM_KEY] = enumv; + } + if (isFunction(checker)) { + base[CHECKER_KEY] = checker; + } + if (isString(alias)) { + base[ALIAS_KEY] = alias; + } + return base; + } + + // export also create wrapper methods + + /** + * This has a different interface + * @param {*} value to supply + * @param {string|array} type for checking + * @param {object} params to map against the config check + * @param {array} params.enumv NOT enum + * @param {boolean} params.optional false then nothing + * @param {function} params.checker need more work on this one later + * @param {string} params.alias mostly for cmd + */ + var createConfig = function (value, type, params) { + if ( params === void 0 ) params = {}; + + // Note the enumv not ENUM + // const { enumv, optional, checker, alias } = params; + // let args = [value, type, optional, enumv, checker, alias]; + var o = params[OPTIONAL_KEY]; + var e = params[ENUM_KEY]; + var c = params[CHECKER_KEY]; + var a = params[ALIAS_KEY]; + return constructConfig.apply(null, [value, type, o, e, c, a]) + }; + + /** + * We recreate the method here to avoid the circlar import + * @param {object} config user supply configuration + * @param {object} appProps mutation options + * @param {object} [constantProps={}] optional: immutation options + * @return {object} all checked configuration + */ + var checkConfigAsync = function(validateSync) { + return function(config, appProps, constantProps) { + if ( constantProps === void 0 ) constantProps= {}; + + return checkOptionsAsync(config, appProps, constantProps, validateSync) + } + }; + + // export + var isString$1 = checkIsString; + var isNumber$1 = checkIsNumber; + var validateAsync$1 = validateAsync; + + var createConfig$1 = createConfig; + + var checkConfigAsync$1 = checkConfigAsync(validateSync); + + var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; + + var appProps = { + algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), + expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), + notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), + audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), + subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), + issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), + noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), + header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), + keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), + mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) + }; + + /** + * @param {boolean} sec return in second or not + * @return {number} timestamp + */ + var timestamp$1 = function (sec) { + if ( sec === void 0 ) sec = false; + + var time = Date.now(); + return sec ? Math.floor( time / 1000 ) : time; + }; + + var assign = make_assign(); + var create = make_create(); + var trim$1 = make_trim(); + var Global = (typeof window !== 'undefined' ? window : commonjsGlobal); + + var util = { + assign: assign, + create: create, + trim: trim$1, + bind: bind, + slice: slice, + each: each, + map: map, + pluck: pluck, + isList: isList, + isFunction: isFunction$1, + isObject: isObject$1, + Global: Global + }; + + function make_assign() { + if (Object.assign) { + return Object.assign + } else { + return function shimAssign(obj, props1, props2, etc) { + var arguments$1 = arguments; + + for (var i = 1; i < arguments.length; i++) { + each(Object(arguments$1[i]), function(val, key) { + obj[key] = val; + }); + } + return obj + } + } + } + + function make_create() { + if (Object.create) { + return function create(obj, assignProps1, assignProps2, etc) { + var assignArgsList = slice(arguments, 1); + return assign.apply(this, [Object.create(obj)].concat(assignArgsList)) + } + } else { + function F() {} // eslint-disable-line no-inner-declarations + return function create(obj, assignProps1, assignProps2, etc) { + var assignArgsList = slice(arguments, 1); + F.prototype = obj; + return assign.apply(this, [new F()].concat(assignArgsList)) + } + } + } + + function make_trim() { + if (String.prototype.trim) { + return function trim(str) { + return String.prototype.trim.call(str) + } + } else { + return function trim(str) { + return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '') + } + } + } + + function bind(obj, fn) { + return function() { + return fn.apply(obj, Array.prototype.slice.call(arguments, 0)) + } + } + + function slice(arr, index) { + return Array.prototype.slice.call(arr, index || 0) + } + + function each(obj, fn) { + pluck(obj, function(val, key) { + fn(val, key); + return false + }); + } + + function map(obj, fn) { + var res = (isList(obj) ? [] : {}); + pluck(obj, function(v, k) { + res[k] = fn(v, k); + return false + }); + return res + } + + function pluck(obj, fn) { + if (isList(obj)) { + for (var i=0; i= 0; i--) { + var key = localStorage().key(i); + fn(read(key), key); + } + } + + function remove(key) { + return localStorage().removeItem(key) + } + + function clearAll() { + return localStorage().clear() + } + + // cookieStorage is useful Safari private browser mode, where localStorage + // doesn't work but cookies do. This implementation is adopted from + // https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage + + + var Global$2 = util.Global; + var trim$2 = util.trim; + + var cookieStorage = { + name: 'cookieStorage', + read: read$1, + write: write$1, + each: each$3, + remove: remove$1, + clearAll: clearAll$1, + }; + + var doc = Global$2.document; + + function read$1(key) { + if (!key || !_has(key)) { return null } + var regexpStr = "(?:^|.*;\\s*)" + + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"; + return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")) + } + + function each$3(callback) { + var cookies = doc.cookie.split(/; ?/g); + for (var i = cookies.length - 1; i >= 0; i--) { + if (!trim$2(cookies[i])) { + continue + } + var kvp = cookies[i].split('='); + var key = unescape(kvp[0]); + var val = unescape(kvp[1]); + callback(val, key); + } + } + + function write$1(key, data) { + if(!key) { return } + doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; + } + + function remove$1(key) { + if (!key || !_has(key)) { + return + } + doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; + } + + function clearAll$1() { + each$3(function(_, key) { + remove$1(key); + }); + } + + function _has(key) { + return (new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie) + } + + var defaults = defaultsPlugin; + + function defaultsPlugin() { + var defaultValues = {}; + + return { + defaults: defaults, + get: get + } + + function defaults(_, values) { + defaultValues = values; + } + + function get(super_fn, key) { + var val = super_fn(); + return (val !== undefined ? val : defaultValues[key]) + } + } + + var bind$2 = util.bind; + var each$4 = util.each; + var create$2 = util.create; + var slice$2 = util.slice; + + var events = eventsPlugin; + + function eventsPlugin() { + var pubsub = _newPubSub(); + + return { + watch: watch, + unwatch: unwatch, + once: once, + + set: set, + remove: remove, + clearAll: clearAll + } + + // new pubsub functions + function watch(_, key, listener) { + return pubsub.on(key, bind$2(this, listener)) + } + function unwatch(_, subId) { + pubsub.off(subId); + } + function once(_, key, listener) { + pubsub.once(key, bind$2(this, listener)); + } + + // overwrite function to fire when appropriate + function set(super_fn, key, val) { + var oldVal = this.get(key); + super_fn(); + pubsub.fire(key, val, oldVal); + } + function remove(super_fn, key) { + var oldVal = this.get(key); + super_fn(); + pubsub.fire(key, undefined, oldVal); + } + function clearAll(super_fn) { + var oldVals = {}; + this.each(function(val, key) { + oldVals[key] = val; + }); + super_fn(); + each$4(oldVals, function(oldVal, key) { + pubsub.fire(key, undefined, oldVal); + }); + } + } + + + function _newPubSub() { + return create$2(_pubSubBase, { + _id: 0, + _subSignals: {}, + _subCallbacks: {} + }) + } + + var _pubSubBase = { + _id: null, + _subCallbacks: null, + _subSignals: null, + on: function(signal, callback) { + if (!this._subCallbacks[signal]) { + this._subCallbacks[signal] = {}; + } + this._id += 1; + this._subCallbacks[signal][this._id] = callback; + this._subSignals[this._id] = signal; + return this._id + }, + off: function(subId) { + var signal = this._subSignals[subId]; + delete this._subCallbacks[signal][subId]; + delete this._subSignals[subId]; + }, + once: function(signal, callback) { + var subId = this.on(signal, bind$2(this, function() { + callback.apply(this, arguments); + this.off(subId); + })); + }, + fire: function(signal) { + var args = slice$2(arguments, 1); + each$4(this._subCallbacks[signal], function(callback) { + callback.apply(this, args); + }); + } + }; + + var lzString = createCommonjsModule(function (module) { + /* eslint-disable */ + // Copyright (c) 2013 Pieroxy + // This work is free. You can redistribute it and/or modify it + // under the terms of the WTFPL, Version 2 + // For more information see LICENSE.txt or http://www.wtfpl.net/ + // + // For more information, the home page: + // http://pieroxy.net/blog/pages/lz-string/testing.html + // + // LZ-based compression algorithm, version 1.4.4 + var LZString = (function() { + + // private property + var f = String.fromCharCode; + var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; + var baseReverseDic = {}; + + function getBaseValue(alphabet, character) { + if (!baseReverseDic[alphabet]) { + baseReverseDic[alphabet] = {}; + for (var i=0 ; i>> 8; + buf[i*2+1] = current_value % 256; + } + return buf; + }, + + //decompress from uint8array (UCS-2 big endian format) + decompressFromUint8Array:function (compressed) { + if (compressed===null || compressed===undefined){ + return LZString.decompress(compressed); + } else { + var buf=new Array(compressed.length/2); // 2 bytes per character + for (var i=0, TotalLen=buf.length; i> 1; + } + } else { + value = 1; + for (i=0 ; i> 1; + } + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + delete context_dictionaryToCreate[context_w]; + } else { + value = context_dictionary[context_w]; + for (i=0 ; i> 1; + } + + + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + // Add wc to the dictionary. + context_dictionary[context_wc] = context_dictSize++; + context_w = String(context_c); + } + } + + // Output the code for w. + if (context_w !== "") { + if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) { + if (context_w.charCodeAt(0)<256) { + for (i=0 ; i> 1; + } + } else { + value = 1; + for (i=0 ; i> 1; + } + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + delete context_dictionaryToCreate[context_w]; + } else { + value = context_dictionary[context_w]; + for (i=0 ; i> 1; + } + + + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + } + + // Mark the end of the stream + value = 2; + for (i=0 ; i> 1; + } + + // Flush the last char + while (true) { + context_data_val = (context_data_val << 1); + if (context_data_position == bitsPerChar-1) { + context_data.push(getCharFromInt(context_data_val)); + break; + } + else { context_data_position++; } + } + return context_data.join(''); + }, + + decompress: function (compressed) { + if (compressed == null) { return ""; } + if (compressed == "") { return null; } + return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); }); + }, + + _decompress: function (length, resetValue, getNextValue) { + var dictionary = [], + next, + enlargeIn = 4, + dictSize = 4, + numBits = 3, + entry = "", + result = [], + i, + w, + bits, resb, maxpower, power, + c, + data = {val:getNextValue(0), position:resetValue, index:1}; + + for (i = 0; i < 3; i += 1) { + dictionary[i] = i; + } + + bits = 0; + maxpower = Math.pow(2,2); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + switch (next = bits) { + case 0: + bits = 0; + maxpower = Math.pow(2,8); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + c = f(bits); + break; + case 1: + bits = 0; + maxpower = Math.pow(2,16); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + c = f(bits); + break; + case 2: + return ""; + } + dictionary[3] = c; + w = c; + result.push(c); + while (true) { + if (data.index > length) { + return ""; + } + + bits = 0; + maxpower = Math.pow(2,numBits); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + switch (c = bits) { + case 0: + bits = 0; + maxpower = Math.pow(2,8); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + dictionary[dictSize++] = f(bits); + c = dictSize-1; + enlargeIn--; + break; + case 1: + bits = 0; + maxpower = Math.pow(2,16); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + dictionary[dictSize++] = f(bits); + c = dictSize-1; + enlargeIn--; + break; + case 2: + return result.join(''); + } + + if (enlargeIn == 0) { + enlargeIn = Math.pow(2, numBits); + numBits++; + } + + if (dictionary[c]) { + entry = dictionary[c]; + } else { + if (c === dictSize) { + entry = w + w.charAt(0); + } else { + return null; + } + } + result.push(entry); + + // Add w+entry[0] to the dictionary. + dictionary[dictSize++] = w + entry.charAt(0); + enlargeIn--; + + w = entry; + + if (enlargeIn == 0) { + enlargeIn = Math.pow(2, numBits); + numBits++; + } + + } + } + }; + return LZString; + })(); + + if( module != null ) { + module.exports = LZString; + } + }); + + var compression = compressionPlugin; + + function compressionPlugin() { + return { + get: get, + set: set, + } + + function get(super_fn, key) { + var val = super_fn(key); + if (!val) { return val } + var decompressed = lzString.decompress(val); + // fallback to existing values that are not compressed + return (decompressed == null) ? val : this._deserialize(decompressed) + } + + function set(super_fn, key, val) { + var compressed = lzString.compress(this._serialize(val)); + super_fn(key, compressed); + } + } + + // sort of persist on the user side + + var storages = [localStorage_1, cookieStorage]; + var plugins = [defaults, events, compression]; + + var localStore = storeEngine.createStore(storages, plugins); + + var Global$3 = util.Global; + + var sessionStorage_1 = { + name: 'sessionStorage', + read: read$2, + write: write$2, + each: each$5, + remove: remove$2, + clearAll: clearAll$2 + }; + + function sessionStorage() { + return Global$3.sessionStorage + } + + function read$2(key) { + return sessionStorage().getItem(key) + } + + function write$2(key, data) { + return sessionStorage().setItem(key, data) + } + + function each$5(fn) { + for (var i = sessionStorage().length - 1; i >= 0; i--) { + var key = sessionStorage().key(i); + fn(read$2(key), key); + } + } + + function remove$2(key) { + return sessionStorage().removeItem(key) + } + + function clearAll$2() { + return sessionStorage().clear() + } + + // session store with watch + // @1.5.0 stop using the expired plugin and deal it ourself + // import expiredPlugin from 'store/plugins/expire' + + var storages$1 = [sessionStorage_1, cookieStorage]; + var plugins$1 = [defaults, compression]; + + var sessionStore = storeEngine.createStore(storages$1, plugins$1); + + // export store interface + + // export back the raw version for development purposes + var localStore$1 = localStore; + var sessionStore$1 = sessionStore; + + // ported from jsonql-params-validator + + /** + * @param {*} args arguments to send + *@return {object} formatted payload + */ + var formatPayload = function (args) { + var obj; + + return ( + ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) + ); + }; + + /** + * Get name from the payload (ported back from jsonql-koa) + * @param {*} payload to extract from + * @return {string} name + */ + function getNameFromPayload(payload) { + return Object.keys(payload)[0] + } + + /** + * wrapper method to add the timestamp as well + * @param {string} resolverName + * @param {*} payload + * @return {object} delierable + */ + function createDeliverable(resolverName, payload) { + var obj; + + return ( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME] = [ timestamp$1() ], obj ) + } + + /** + * @param {string} resolverName name of function + * @param {array} [args=[]] from the ...args + * @param {boolean} [jsonp = false] add v1.3.0 to koa + * @return {object} formatted argument + */ + function createQuery(resolverName, args, jsonp) { + if ( args === void 0 ) args = []; + if ( jsonp === void 0 ) jsonp = false; + + if (isString(resolverName) && isArray(args)) { + var payload = formatPayload(args); + if (jsonp === true) { + return payload; + } + return createDeliverable(resolverName, payload) + } + throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) + } + + /** + * @param {string} resolverName name of function + * @param {*} payload to send + * @param {object} [condition={}] for what + * @param {boolean} [jsonp = false] add v1.3.0 to koa + * @return {object} formatted argument + */ + function createMutation(resolverName, payload, condition, jsonp) { + if ( condition === void 0 ) condition = {}; + if ( jsonp === void 0 ) jsonp = false; + + var _payload = {}; + _payload[PAYLOAD_PARAM_NAME] = payload; + _payload[CONDITION_PARAM_NAME] = condition; + if (jsonp === true) { + return _payload; + } + if (isString(resolverName)) { + return createDeliverable(resolverName, _payload) + } + throw new JsonqlValidationError("[createMutation] expect resolverName to be string!", { resolverName: resolverName, payload: payload, condition: condition }) + } + + /** + * @return {object} _cb as key with timestamp + */ + var cacheBurst = function () { return ({ _cb: timestamp$1() }); }; + + // break up from node-middleware + + // ported from http-client + + /** + * handle the return data + * @TODO how to handle the return timestamp and calculate the diff? + * @param {object} result return from server + * @return {object} strip the data part out, or if the error is presented + */ + var resultHandler = function (result) { return ( + (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result + ); }; + + // new 1.5.0 + + // this becomes the base class instead of the HttpCls + var StoreClass = function StoreClass(opts) { + this.opts = opts; + // make it a string + this.instanceKey = hashCode$1(this.opts.hostname); + // pass this store for use later + this.localStore = localStore$1; + this.sessionStore = sessionStore$1; + /* + if (this.opts.debugOn) { // reuse this to clear out the data + this.log('clear all stores') + localStore.clearAll() + sessionStore.clearAll() + + localStore.set('TEST', Date.now()) + sessionStore.set('TEST', Date.now()) + } + */ + }; + + var prototypeAccessors = { lset: { configurable: true },lget: { configurable: true },sset: { configurable: true },sget: { configurable: true } }; + // store in local storage id by the instanceKey + // values should be an object so with key so we just merge + // into the existing store without going through the keys + StoreClass.prototype.__setMethod = function __setMethod (storeType, values) { + var obj; + + var store = this[storeType]; + var data = this.__getMethod(storeType); + var skey = this.opts.storageKey; + var ikey = this.instanceKey; + store.set(skey, ( obj = {}, obj[ikey] = data ? merge({}, data, values) : values, obj )); + }; + // return the data id by the instaceKey + StoreClass.prototype.__getMethod = function __getMethod (storeType) { + var store = this[storeType]; + var data = store.get(this.opts.storageKey); + return data ? data[this.instanceKey] : false + }; + // remove from local store id by instanceKey + StoreClass.prototype.__delMethod = function __delMethod (storeType, key) { + var data = this.__getMethod(storeType); + if (data) { + var store = {}; + for (var k in data) { + if (k !== key) { + store[k] = data[k]; + } + } + this.__setMethod(storeType, store); + } + }; + // clear everything by this instanceKey + StoreClass.prototype.__clearMethod = function __clearMethod (storeKey) { + var skey = this.opts.storageKey; + var store = this[storeKey]; + var data = store.get(skey); + if (data) { + var _store = {}; + for (var k in data) { + if (k !== this.instanceKey) { + _store[k] = data[k]; + } + } + store.set(skey, _store); + } + }; + // Alias for different store + prototypeAccessors.lset.set = function (values) { + return this.__setMethod(CLS_LOCAL_STORE_NAME, values) + }; + + prototypeAccessors.lget.get = function () { + return this.__getMethod(CLS_LOCAL_STORE_NAME) + }; + + StoreClass.prototype.ldel = function ldel (key) { + return this.__delMethod(CLS_LOCAL_STORE_NAME, key) + }; + + StoreClass.prototype.lclear = function lclear () { + return this.__clearMethod(CLS_LOCAL_STORE_NAME) + }; + + // store in session store id by the instanceKey + prototypeAccessors.sset.set = function (values) { + // this.log('--- sset ---', values) + return this.__setMethod(CLS_SESS_STORE_NAME, values) + }; + + prototypeAccessors.sget.get = function () { + return this.__getMethod(CLS_SESS_STORE_NAME) + }; + + StoreClass.prototype.sdel = function sdel (key) { + return this.__delMethod(CLS_SESS_STORE_NAME, key) + }; + + StoreClass.prototype.sclear = function sclear () { + return this.__clearMethod(CLS_SESS_STORE_NAME) + }; + + Object.defineProperties( StoreClass.prototype, prototypeAccessors ); + + // base HttpClass + /** + * It will ONLY have our own jsonql specific implement check + * @param {object} result the server return result + * @return {object} this will just throw error + */ + function clientErrorsHandler$1(result) { + if (isObjectHasKey(result, 'error')) { + var error = result.error; + var className = error.className; + var name = error.name; + var errorName = className || name; + // just throw the whole thing back + var msg = error.message || NO_ERROR_MSG; + var detail = error.detail || error; + console.info('--- errorName ---', errorName, errors$1); + + if (errorName && errors$1[errorName]) { + throw new errors$1[className](msg, detail) + } + throw new JsonqlError(msg, detail) + } + // pass through to the next + return result; + } + + + + // extract the one we need + var POST = API_REQUEST_METHODS[0]; + var PUT = API_REQUEST_METHODS[1]; + + var HttpClass = /*@__PURE__*/(function (StoreClass) { + function HttpClass(opts) { + StoreClass.call(this, opts); + // change the way how we init Fly + // flyio now become external depedencies and it makes it easier to switch + // @BUG should we run test to check if we have the windows object? + // this.log(opts) + // this.fly = opts.Fly ? new opts.Fly() : new Fly() + // to a different environment like WeChat mini app + + this.extraHeader = {}; + // @1.2.1 for adding query to the call on the fly + this.extraParams = {}; + // this.log('start up opts', opts); + this.reqInterceptor(); + this.resInterceptor(); + } + + if ( StoreClass ) HttpClass.__proto__ = StoreClass; + HttpClass.prototype = Object.create( StoreClass && StoreClass.prototype ); + HttpClass.prototype.constructor = HttpClass; + + var prototypeAccessors = { headers: { configurable: true } }; + + // set headers for that one call + prototypeAccessors.headers.set = function (header) { + this.extraHeader = header; + }; + + /** + * Create the reusage request method + * @param {object} payload jsonql payload + * @param {object} options extra options add the request + * @param {object} headers extra headers add to the call + * @return {object} the fly request instance + */ + HttpClass.prototype.request = function request (payload, options, headers) { + var obj; + + if ( options === void 0 ) options = {}; + if ( headers === void 0 ) headers = {}; + this.headers = headers; + var params = merge({}, cacheBurst(), this.extraParams); + // @TODO need to add a jsonp url and payload + if (this.opts.enableJsonp) { + var resolverName = getNameFromPayload(payload); + params = merge({}, params, ( obj = {}, obj[JSONP_CALLBACK_NAME] = resolverName, obj )); + payload = payload[resolverName]; + } + // double up the url param and see what happen @TODO remove later + var reqParams = merge({}, { method: POST, params: params }, options); + this.log('request params', reqParams, this.jsonqlEndpoint); + + return this.fly.request(this.jsonqlEndpoint, payload, reqParams) + }; + + /** + * This will replace the create baseRequest method + * + */ + HttpClass.prototype.reqInterceptor = function reqInterceptor () { + var this$1 = this; + + this.fly.interceptors.request.use( + function (req) { + var headers = this$1.getHeaders(); + this$1.log('request interceptor call', headers); + + for (var key in headers) { + req.headers[key] = headers[key]; + } + return req; + } + ); + }; + + // @TODO + HttpClass.prototype.processJsonp = function processJsonp (result) { + return resultHandler(result) + }; + + /** + * This will be replacement of the first then call + * + */ + HttpClass.prototype.resInterceptor = function resInterceptor () { + var this$1 = this; + + var self = this; + var jsonp = self.opts.enableJsonp; + this.fly.interceptors.response.use( + function (res) { + this$1.log('response interceptor call', res); + self.cleanUp(); + // now more processing here + // there is a problem if we throw the result.error here + // the original data is lost, so we need to do what we did before + // deal with that error in the first then instead + var result = isString$1(res.data) ? JSON.parse(res.data) : res.data; + if (jsonp) { + return self.processJsonp(result) + } + return resultHandler(result) + }, + // this get call when it's not 200 + function (err) { + self.cleanUp(); + console.error(err); + throw new JsonqlServerError('Server side error', err) + } + ); + }; + + /** + * Get the headers inject into the call + * @return {object} headers + */ + HttpClass.prototype.getHeaders = function getHeaders () { + if (this.opts.enableAuth) { + return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader) + } + return merge({}, DEFAULT_HEADER, this.extraHeader) + }; + + /** + * Post http call operation to clean up things we need + */ + HttpClass.prototype.cleanUp = function cleanUp () { + this.extraHeader = {}; + this.extraParams = {}; + }; + + /** + * GET for contract only + * @return {promise} resolve the contract + */ + HttpClass.prototype.getRemoteContract = function getRemoteContract () { + var this$1 = this; + + if (this.opts.showContractDesc) { + this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM); + } + return this.request({}, {method: 'GET'}, this.contractHeader) + .then(clientErrorsHandler$1) + .then(function (result) { + this$1.log('get contract result', result); + // when refresh the window the result is different! + // @TODO need to check the Koa side about why is that + // also it should set a flag if we want the description or not + if (result.cache && result.contract) { + return result.contract; + } + // just the normal result + return result + }) + .catch(function (err) { + console.error('getRemoteContract err', err); + throw new JsonqlServerError('getRemoteContract', err) + }) + }; + + /** + * POST to server - query + * @param {object} name of the resolver + * @param {array} args arguments + * @return {object} promise resolve to the resolver return + */ + HttpClass.prototype.query = function query (name, args) { + if ( args === void 0 ) args = []; + + return this.request(createQuery(name, args)) + .then(clientErrorsHandler$1) + }; + + /** + * PUT to server - mutation + * @param {string} name of resolver + * @param {object} payload what it said + * @param {object} conditions what it said + * @return {object} promise resolve to the resolver return + */ + HttpClass.prototype.mutation = function mutation (name, payload, conditions) { + if ( payload === void 0 ) payload = {}; + if ( conditions === void 0 ) conditions = {}; + + return this.request(createMutation(name, payload, conditions), {method: PUT}) + .then(clientErrorsHandler$1) + }; + + Object.defineProperties( HttpClass.prototype, prototypeAccessors ); + + return HttpClass; + }(StoreClass)); + + // all the contract related methods will be here + + // export + var ContractClass = /*@__PURE__*/(function (HttpClass) { + function ContractClass(opts) { + HttpClass.call(this, opts); + } + + if ( HttpClass ) ContractClass.__proto__ = HttpClass; + ContractClass.prototype = Object.create( HttpClass && HttpClass.prototype ); + ContractClass.prototype.constructor = ContractClass; + + var prototypeAccessors = { contractHeader: { configurable: true } }; + + /** + * return the contract public api + * @return {object} contract + */ + ContractClass.prototype.getContract = function getContract () { + var contract = this.readContract(); + this.log('getContract first call', contract); + return contract ? Promise.resolve(contract) + : this.getRemoteContract().then(this.storeContract.bind(this)) + }; + + /** + * We are changing the way how to auth to get the contract.json + * Instead of in the url, we will be putting that key value in the header + * @return {object} header + */ + prototypeAccessors.contractHeader.get = function () { + var base = {}; + if (this.opts.contractKey !== false) { + base[this.opts.contractKeyName] = this.opts.contractKey; + } + return base; + }; + + /** + * Save the contract to local store + * @param {object} contract to save + * @return {object|boolean} false when its not a contract or contract on OK + */ + ContractClass.prototype.storeContract = function storeContract (contract) { + var obj; + + // first need to check if the contract is a contract + if (!isContract(contract)) { + throw new JsonqlValidationError("Contract is malformed!") + //return false; + } + /* @TODO need to rethink how to expired the contract + let args = [contract] + if (this.opts.contractExpired) { + let expired = parseFloat(this.opts.contractExpired) + if (!isNaN(expired) && expired > 0) { + args.push(expired) + } + } + // calling the setter + this.jsonqlContract = args; + */ + this.lset = ( obj = {}, obj[CLS_CONTRACT_NAME] = contract, obj ); + // return it + this.log('storeContract return result', contract); + return contract; + }; + + /** + * return the contract from options or localStore + * @return {object|boolean} false on not found + */ + ContractClass.prototype.readContract = function readContract () { + var contract = isContract(this.opts.contract); + if (contract !== false) { + return contract; + } + var data = this.lget; + if (data) { + return data[CLS_CONTRACT_NAME] + } + return false; + }; + + Object.defineProperties( ContractClass.prototype, prototypeAccessors ); + + return ContractClass; + }(HttpClass)); + + // this is the new auth class that integrate with the jsonql-jwt + // export + var AuthClass = /*@__PURE__*/(function (ContractClass) { + function AuthClass(opts) { + ContractClass.call(this, opts); + if (opts.enableAuth) { + this.setDecoder = jwtDecode; + } + } + + if ( ContractClass ) AuthClass.__proto__ = ContractClass; + AuthClass.prototype = Object.create( ContractClass && ContractClass.prototype ); + AuthClass.prototype.constructor = AuthClass; + + var prototypeAccessors = { profileIndex: { configurable: true },setDecoder: { configurable: true },saveProfile: { configurable: true },readProfile: { configurable: true },jsonqlToken: { configurable: true },jsonqlUserdata: { configurable: true } }; + + /** + * for overwrite + * @param {string} token stored token + * @return {string} token + */ + AuthClass.prototype.decoder = function decoder (token) { + return token; + }; + + /** + * set the profile index + * @param {number} idx + */ + prototypeAccessors.profileIndex.set = function (idx) { + var obj; + + var key = CLS_PROFILE_IDX; + if (isNumber$1(idx)) { + this[key] = idx; + if (this.opts.persistToken) { + this.lset = ( obj = {}, obj[key] = idx, obj ); + } + return; + } + throw new JsonqlValidationError('profileIndex', ("Expect idx to be number but got " + (typeof idx))) + }; + + /** + * get the profile index + * @return {number} idx + */ + prototypeAccessors.profileIndex.get = function () { + var key = CLS_PROFILE_IDX; + if (this.opts.persistToken) { + var data = this.lget; + if (data[key]) { + return data[key] + } + } + return this[key] ? this[key] : ZERO_IDX + }; + + /** + * Return the token from session store + * @param {number} [idx=false] profile index + * @return {string} token + */ + AuthClass.prototype.rawAuthToken = function rawAuthToken (idx) { + if ( idx === void 0 ) idx = false; + + if (idx !== false) { + this.profileIndex = idx; + } + // this should return from the base + return this.jsonqlToken; // see base-cls + }; + + /** + * Setter to add a decoder when retrieve user token + * @param {function} d a decoder + */ + prototypeAccessors.setDecoder.set = function (d) { + if (typeof d === 'function') { + this.decoder = d; + } + }; + + /** + * getter to return the session or local store set method + * @param {*} data to save + * @return {object} set method + */ + prototypeAccessors.saveProfile.set = function (data) { + if (this.opts.persistToken) { + // this.log('--- saveProfile lset ---', data) + this.lset = data; + } else { + // this.log('--- saveProfile sset ---', data) + this.sset = data; + } + }; + + /** + * getter to return the session or local store get method + * @return {object} get method + */ + prototypeAccessors.readProfile.get = function () { + return this.opts.persistToken ? this.lget : this.sget + }; + + // these were in the base class before but it should be here + /** + * save token + * @param {string} token to store + * @return {string|boolean} false on failed + */ + prototypeAccessors.jsonqlToken.set = function (token) { + var obj; + + var data = this.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + // @TODO also have to make sure the token is not already existed! + var tokens = (data && data[key]) ? data[key] : []; + tokens.push(token); + this.saveProfile = ( obj = {}, obj[key] = tokens, obj ); + // store the userdata + this.jsonqlUserdata = this.decoder(token); + }; + + /** + * Jsonql token getter + * 1.5.1 each token associate with the same profileIndex + * @return {string|boolean} false when failed + */ + prototypeAccessors.jsonqlToken.get = function () { + var data = this.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + if (data && data[key]) { + this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex]); + return data[key][this.profileIndex] + } + return false + }; + + /** + * this one will use the sessionStore + * basically we hook this onto the token store and decode it to store here + * we only store one decoded user data at a time, but the token can be multiple + */ + prototypeAccessors.jsonqlUserdata.set = function (userdata) { + var obj; + + this.sset = ( obj = {}, obj[USERDATA_TABLE] = userdata, obj ); + }; + + /** + * this one store in the session store + * get login userdata decoded jwt + * 1.5.1 each userdata associate with the same profileIndex + * @return {object|null} + */ + prototypeAccessors.jsonqlUserdata.get = function () { + var data = this.sget; + return data ? data[USERDATA_TABLE] : false + }; + + /** + * Construct the auth header + * @return {object} header + */ + AuthClass.prototype.getAuthHeader = function getAuthHeader () { + var obj; + + var token = this.jsonqlToken; // only call the getter to get the default one + return token ? ( obj = {}, obj[this.opts.AUTH_HEADER] = (BEARER + " " + token), obj ) : {}; + }; + + /** + * return all the stored token and decode it + * @param {number} [idx=false] profile index + * @return {array|boolean|string} false not found or array + */ + AuthClass.prototype.getProfiles = function getProfiles (idx) { + if ( idx === void 0 ) idx = false; + + var self = this; // just in case the scope problem + var data = self.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + if (data && data[key]) { + if (idx !== false && isNumber$1(idx)) { + return data[key][idx] || false + } + return data[key].map(self.decoder.bind(self)) + } + return false + }; + + /** + * call after the login + * @param {string} token return from server + * @return {object} decoded token to userdata object + */ + AuthClass.prototype.postLoginAction = function postLoginAction (token) { + this.jsonqlToken = token; + return token + }; + + /** + * call after the logout @TODO + */ + AuthClass.prototype.postLogoutAction = function postLogoutAction () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + console.info("postLogoutAction", args); + }; + + Object.defineProperties( AuthClass.prototype, prototypeAccessors ); + + return AuthClass; + }(ContractClass)); + + // this the core of the internal storage management + + // This class will only focus on the storage system + var JsonqlBaseClient = /*@__PURE__*/(function (AuthCls) { + function JsonqlBaseClient(fly, opts) { + // change at 1.4.10 pass it directly without init it + this.fly = fly; + AuthCls.call(this, opts); + } + + if ( AuthCls ) JsonqlBaseClient.__proto__ = AuthCls; + JsonqlBaseClient.prototype = Object.create( AuthCls && AuthCls.prototype ); + JsonqlBaseClient.prototype.constructor = JsonqlBaseClient; + + var prototypeAccessors = { jsonqlEndpoint: { configurable: true } }; + + /** + * construct the end point + * @return {string} the end point to call + */ + prototypeAccessors.jsonqlEndpoint.get = function () { + var baseUrl = this.opts.hostname || ''; + return [baseUrl, this.opts.jsonqlPath].join('/') + }; + + /** + * simple log + */ + JsonqlBaseClient.prototype.log = function log () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (this.opts.debugOn === true) { + Reflect.apply(console.info, console, args); + } + }; + + Object.defineProperties( JsonqlBaseClient.prototype, prototypeAccessors ); + + return JsonqlBaseClient; + }(AuthClass)); + + // export interface + + /** + * using just the map reduce to chain multiple functions together + * @param {function} mainFn the init function + * @param {array} moreFns as many as you want to take the last value and return a new one + * @return {function} accept value for the mainFn + */ + var chainFns = function (mainFn) { + var moreFns = [], len = arguments.length - 1; + while ( len-- > 0 ) moreFns[ len ] = arguments[ len + 1 ]; + + return ( + function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return ( + moreFns.reduce(function (value, nextFn) { return ( + // change here to check if the return value is array then we spread it + Reflect.apply(nextFn, null, toArray(value)) + ); }, Reflect.apply(mainFn, null, args)) + ); + } + ); + }; + + /** + * check if the object has name property + * @param {object} obj the object to check + * @param {string} name the prop name + * @return {*} the value or undefined + */ + function objHasProp(obj, name) { + var prop = Object.getOwnPropertyDescriptor(obj, name); + return prop !== undefined && prop.value ? prop.value : prop; + } + + /** + * 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 {string} name the name of the object to get inject also for checking + * @param {object} data to inject into the function static interface + * @param {boolean} [overwrite=false] if we want to overwrite the existing data + * @return {function} added property resolver + */ + function injectToFn(resolver, name, data, overwrite) { + if ( overwrite === void 0 ) overwrite = false; + + var check = objHasProp(resolver, name); + if (overwrite === false && check !== undefined) { + // console.info(`NOT INJECTED`) + return resolver; + } + /* this will throw error! + if (overwrite === true && check !== undefined) { + delete resolver[name] // delete this property + } + */ + // console.info(`INJECTED`) + Object.defineProperty(resolver, name, { + value: data, + writable: overwrite // if its set to true then we should able to overwrite it + }); + + return resolver; + } + + // breaking out the inner methods generator in here + + /** + * generate authorisation specific methods + * @param {object} jsonqlInstance instance of this + * @param {string} name of method + * @param {object} opts configuration + * @param {object} contract to match + * @return {function} for use + */ + var authMethodGenerator = function (jsonqlInstance, name, opts, contract) { + return function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var params = contract.auth[name].params; + var values = params.map(function (p, i) { return args[i]; }); + var header = args[params.length] || {}; + return validateAsync$1(args, params) + .then(function () { return jsonqlInstance + .query + .apply(jsonqlInstance, [name, values, header]); } + ) + .catch(finalCatch) + } + }; + + /** + * Break up the different type each - create query methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createQueryMethods = function (obj, jsonqlInstance, ee, config, contract) { + var query = {}; + var loop = function ( queryFn ) { + // to keep it clean we use a param to id the auth method + // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; + // generate the query method + query = injectToFn(query, queryFn, function queryFnHandler() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var params = contract.query[queryFn].params; + var _args = params.map(function (param, i) { return args[i]; }); + // debug('query', queryFn, _params); + // @TODO this need to change to a different way to add an extra header + var header = {}; + // @TODO validate against the type + return validateAsync$1(_args, params) + .then(function () { return jsonqlInstance + .query + .apply(jsonqlInstance, [queryFn, _args, header]); } + ) + .catch(finalCatch) + }); + }; + + for (var queryFn in contract.query) loop( queryFn ); + obj.query = query; + // create an alias to the helloWorld method + obj.helloWorld = query.helloWorld; + return [ obj, jsonqlInstance, ee, config, contract ] + }; + + /** + * create mutation methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createMutationMethods = function (obj, jsonqlInstance, ee, config, contract) { + var mutation = {}; + // process the mutation, the reason the mutation has a fixed number of parameters + // there is only the payload, and conditions parameters + // plus a header at the end + var loop = function ( mutationFn ) { + mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header) { + if ( header === void 0 ) header = {}; + + var args = [payload, conditions]; + var params = contract.mutation[mutationFn].params; + return validateAsync$1(args, params) + .then(function () { return jsonqlInstance + .mutation + .apply(jsonqlInstance, [mutationFn, payload, conditions, header]); } + ) + .catch(function (e) { + console.error('--- mutation fn catch ---', e); + return finalCatch(e) + }) + }); + }; + + for (var mutationFn in contract.mutation) loop( mutationFn ); + obj.mutation = mutation; + return [ obj, jsonqlInstance, ee, config, contract ] + }; + + /** + * create auth methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createAuthMethods = function (obj, jsonqlInstance, ee, config, contract) { + if (config.enableAuth && contract.auth) { + var auth = {}; // v1.3.1 add back the auth prop name in contract + var loginHandlerName = config.loginHandlerName; + var logoutHandlerName = config.logoutHandlerName; + if (contract.auth[loginHandlerName]) { + // changing to the name the config specify + auth[loginHandlerName] = function loginHandlerFn() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract); + return fn.apply(null, args) + .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance)) + .then(function (token) { + ee.$trigger(LOGIN_NAME, token); + return token; + }) + }; + } + // @TODO allow to logout one particular profile or all of them + if (contract.auth[logoutHandlerName]) { + auth[logoutHandlerName] = function logoutHandlerFn() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract); + return fn.apply(null, args) + .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance)) + .then(function (r) { + ee.$trigger(LOGOUT_NAME, r); + return r; + }) + }; + } else { + auth[logoutHandlerName] = function logoutHandlerFn() { + jsonqlInstance.postLogoutAction(KEY_WORD); + ee.$trigger(LOGOUT_NAME, KEY_WORD); + }; + } + obj.auth = auth; + } + + return obj; + }; + + /** + * Here just generate the methods calls + * @param {object} jsonqlInstance what it said + * @param {object} ee event emitter + * @param {object} config configuration + * @param {object} contract the map + * @return {object} with mapped methods + */ + function methodsGenerator(jsonqlInstance, ee, config, contract) { + var obj = {}; + var executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods); + return executor(obj, jsonqlInstance, ee, config, contract) + } + + // Generate the resolver for developer to use + + /** + * @param {object} jsonqlInstance jsonql class instance + * @param {object} config options + * @param {object} contract the contract + * @param {object} ee eventEmitter + * @return {object} constructed functions call + */ + var generator = function (jsonqlInstance, config, contract, ee) { + // V1.3.0 - now everything wrap inside this method + var client = methodsGenerator(jsonqlInstance, ee, config, contract); + // create the rest of the methods + if (config.enableAuth) { + /** + * new method to allow retrieve the current login user data + * @TODO allow to pass an id to switch to different userdata + * @return {*} userdata + */ + client.userdata = function () { return jsonqlInstance.jsonqlUserdata; }; + // allow getting the token for valdiate agains the socket + // if it's not require auth there is no point of calling getToken + client.getToken = function (idx) { + if ( idx === void 0 ) idx = false; + + return jsonqlInstance.rawAuthToken(idx); + }; + // switch profile or read back what is the currenct index + client.profileIndex = function (idx) { + if ( idx === void 0 ) idx = false; + + if (idx === false) { + return jsonqlInstance.profileIndex + } + jsonqlInstance.profileIndex = idx; + }; + // new in 1.5.1 to return different profiles + client.getProfiles = function (idx) { + if ( idx === void 0 ) idx = false; + + return jsonqlInstance.getProfiles(idx); + }; + } + // this will pass to the ws-client if needed + // client.eventEmitter = ee; + // this will require a param + if (config.exposeContract) { + // 1.4.0 change from the get (raw) to the getContract cache and raw version + client.getContract = function () { return jsonqlInstance.getContract(); }; + } + // allow developer to access the store api + if (config.exposeStore) { + // @TODO in 1.5.2 + client.tmpSave = function (data) {}; + client.tmpGet = function (key) { + }; + client.tmpDel = function (key) { + }; + + client.persistSave = function (data) {}; + client.persistGet = function (key) { + }; + client.persistDel = function (key) { + }; + } + // this is for the ws to use later - but this could be dangerous because it's expose the internal + client.eventEmitter = ee; + client.version = '1.5.1'; + // use this method then we can hook into the debugOn at the same time + client.log = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return Reflect.apply(jsonqlInstance.log, jsonqlInstance, ['[DEV DEBUG]'].concat(args)); + }; + // output + return client; + }; + + // all the client configuration options here + var constProps = { + contract: false, + MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong? + CONTENT_TYPE: CONTENT_TYPE, + BEARER: BEARER, + AUTH_HEADER: AUTH_HEADER + }; + + // grab the localhost name and put into the hostname as default + var getHostName = function () { + try { + return [window.location.protocol, window.location.host].join('//') + } catch(e) { + return null + } + }; + + var appProps$1 = { + + hostname: createConfig$1(getHostName(), [STRING_TYPE]), // required the hostname + jsonqlPath: createConfig$1(JSONQL_PATH, [STRING_TYPE]), // The path on the server + + loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), + logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), + // add to koa v1.3.0 - this might remove in the future + enableJsonp: createConfig$1(false, [BOOLEAN_TYPE]), + enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), + // enable useJwt by default @TODO replace with something else and remove them later + useJwt: createConfig$1(true, [BOOLEAN_TYPE]), + // when true then store infinity or pass a time in seconds then we check against + // the token date of creation + persistToken: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE]), + // the header + // v1.2.0 we are using this option during the dev + // so it won't save anything to the localstorage and fetch a new contract + // whenever the browser reload + useLocalstorage: createConfig$1(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage + storageKey: createConfig$1(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage + authKey: createConfig$1(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage + contractExpired: createConfig$1(0, [NUMBER_TYPE]),// -1 always fetch contract, + // 0 never expired, + // > 0 then compare the timestamp with the current one to see if we need to get contract again + // useful during development + keepContract: createConfig$1(true, [BOOLEAN_TYPE]), + exposeContract: createConfig$1(false, [BOOLEAN_TYPE]), + exposeStore: createConfig$1(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn + // @1.2.1 new option for the contract-console to fetch the contract with description + showContractDesc: createConfig$1(false, [BOOLEAN_TYPE]), + contractKey: createConfig$1(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this + contractKeyName: createConfig$1(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs + enableTimeout: createConfig$1(false, [BOOLEAN_TYPE]), // @TODO + timeout: createConfig$1(5000, [NUMBER_TYPE]), // 5 seconds + returnInstance: createConfig$1(false, [BOOLEAN_TYPE]), + allowReturnRawToken: createConfig$1(false, [BOOLEAN_TYPE]), + debugOn: createConfig$1(false, [BOOLEAN_TYPE]) + }; + + // we must ensure the user passing the correct options + + function checkOptionsAsync$1(config) { + var contract = config.contract; + return checkConfigAsync$1(config, appProps$1, constProps) + .then(function (opts) { + opts.contract = contract; + return opts; + }) + } + + // export interface + /** + * 1.5.0 overload the orginal functions to pass over the check + */ + function checkOptionsAsync$2(config) { + return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsync$1(config) + } + + // this is new for the flyio and normalize the name from now on + + /** + * Main interface for jsonql fetch api + * @param {object} ee EventEmitter + * @param {object} config + * @param {object} fly this is really pain in the backside ... long story + * @return {object} jsonql client + */ + function jsonqlAsync(ee, config, fly) { + if ( config === void 0 ) config = {}; + + return checkOptionsAsync$2(config) + .then(function (opts) { return ( + { + baseClient: new JsonqlBaseClient(fly, opts), + opts: opts + } + ); }) + .then( function (ref) { + var baseClient = ref.baseClient; + var opts = ref.opts; + + return ( + getContractFromConfig(baseClient, opts.contract) + .then(function (contract) { return generator(baseClient, opts, contract, ee); }) + ); + } + ) + } + + var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); + var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); + + // making all the functionality on it's own + // import { WatchClass } from './watch' + + var SuspendClass = function SuspendClass() { + // suspend, release and queue + this.__suspend__ = null; + this.queueStore = new Set(); + /* + this.watch('suspend', function(value, prop, oldValue) { + this.logger(`${prop} set from ${oldValue} to ${value}`) + // it means it set the suspend = true then release it + if (oldValue === true && value === false) { + // we want this happen after the return happens + setTimeout(() => { + this.release() + }, 1) + } + return value; // we need to return the value to store it + }) + */ + }; + + var prototypeAccessors$1 = { $suspend: { configurable: true },$queues: { configurable: true } }; + + /** + * setter to set the suspend and check if it's boolean value + * @param {boolean} value to trigger + */ + prototypeAccessors$1.$suspend.set = function (value) { + var this$1 = this; + + if (typeof value === 'boolean') { + var lastValue = this.__suspend__; + this.__suspend__ = value; + this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); + if (lastValue === true && value === false) { + setTimeout(function () { + this$1.release(); + }, 1); + } + } else { + throw new Error("$suspend only accept Boolean value!") + } + }; + + /** + * queuing call up when it's in suspend mode + * @param {any} value + * @return {Boolean} true when added or false when it's not + */ + SuspendClass.prototype.$queue = function $queue () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (this.__suspend__ === true) { + this.logger('($queue)', 'added to $queue', args); + // there shouldn't be any duplicate ... + this.queueStore.add(args); + } + return this.__suspend__; + }; + + /** + * a getter to get all the store queue + * @return {array} Set turn into Array before return + */ + prototypeAccessors$1.$queues.get = function () { + var size = this.queueStore.size; + this.logger('($queues)', ("size: " + size)); + if (size > 0) { + return Array.from(this.queueStore) + } + return [] + }; + + /** + * Release the queue + * @return {int} size if any + */ + SuspendClass.prototype.release = function release () { + var this$1 = this; + + var size = this.queueStore.size; + this.logger('(release)', ("Release was called " + size)); + if (size > 0) { + var queue = Array.from(this.queueStore); + this.queueStore.clear(); + this.logger('queue', queue); + queue.forEach(function (args) { + this$1.logger(args); + Reflect.apply(this$1.$trigger, this$1, args); + }); + this.logger(("Release size " + (this.queueStore.size))); + } + }; + + Object.defineProperties( SuspendClass.prototype, prototypeAccessors$1 ); + + // break up the main file because its getting way too long + + var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { + function NbEventServiceBase(config) { + if ( config === void 0 ) config = {}; + + SuspendClass.call(this); + if (config.logger && typeof config.logger === 'function') { + this.logger = config.logger; + } + this.keep = config.keep; + // for the $done setter + this.result = config.keep ? [] : null; + // we need to init the store first otherwise it could be a lot of checking later + this.normalStore = new Map(); + this.lazyStore = new Map(); + } + + if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; + NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); + NbEventServiceBase.prototype.constructor = NbEventServiceBase; + + var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; + + /** + * validate the event name(s) + * @param {string[]} evt event name + * @return {boolean} true when OK + */ + NbEventServiceBase.prototype.validateEvt = function validateEvt () { + var this$1 = this; + var evt = [], len = arguments.length; + while ( len-- ) evt[ len ] = arguments[ len ]; + + evt.forEach(function (e) { + if (typeof e !== 'string') { + this$1.logger('(validateEvt)', e); + throw new Error("event name must be string type!") + } + }); + return true; + }; + + /** + * Simple quick check on the two main parameters + * @param {string} evt event name + * @param {function} callback function to call + * @return {boolean} true when OK + */ + NbEventServiceBase.prototype.validate = function validate (evt, callback) { + if (this.validateEvt(evt)) { + if (typeof callback === 'function') { + return true; + } + } + throw new Error("callback required to be function type!") + }; + + /** + * Check if this type is correct or not added in V1.5.0 + * @param {string} type for checking + * @return {boolean} true on OK + */ + NbEventServiceBase.prototype.validateType = function validateType (type) { + var types = ['on', 'only', 'once', 'onlyOnce']; + return !!types.filter(function (t) { return type === t; }).length; + }; + + /** + * Run the callback + * @param {function} callback function to execute + * @param {array} payload for callback + * @param {object} ctx context or null + * @return {void} the result store in $done + */ + NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { + this.logger('(run)', callback, payload, ctx); + this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); + }; + + /** + * Take the content out and remove it from store id by the name + * @param {string} evt event name + * @param {string} [storeName = lazyStore] name of store + * @return {object|boolean} content or false on not found + */ + NbEventServiceBase.prototype.takeFromStore = function takeFromStore (evt, storeName) { + if ( storeName === void 0 ) storeName = 'lazyStore'; + + var store = this[storeName]; // it could be empty at this point + if (store) { + this.logger('(takeFromStore)', storeName, store); + if (store.has(evt)) { + var content = store.get(evt); + this.logger('(takeFromStore)', ("has " + evt), content); + store.delete(evt); + return content; + } + return false; + } + throw new Error((storeName + " is not supported!")) + }; + + /** + * The add to store step is similar so make it generic for resuse + * @param {object} store which store to use + * @param {string} evt event name + * @param {spread} args because the lazy store and normal store store different things + * @return {array} store and the size of the store + */ + NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { + var args = [], len = arguments.length - 2; + while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; + + var fnSet; + if (store.has(evt)) { + this.logger('(addToStore)', (evt + " existed")); + fnSet = store.get(evt); + } else { + this.logger('(addToStore)', ("create new Set for " + evt)); + // this is new + fnSet = new Set(); + } + // lazy only store 2 items - this is not the case in V1.6.0 anymore + // we need to check the first parameter is string or not + if (args.length > 2) { + if (Array.isArray(args[0])) { // lazy store + // check if this type of this event already register in the lazy store + var t = args[2]; + if (!this.checkTypeInLazyStore(evt, t)) { + fnSet.add(args); + } + } else { + if (!this.checkContentExist(args, fnSet)) { + this.logger('(addToStore)', "insert new", args); + fnSet.add(args); + } + } + } else { // add straight to lazy store + fnSet.add(args); + } + store.set(evt, fnSet); + return [store, fnSet.size] + }; + + /** + * @param {array} args for compare + * @param {object} fnSet A Set to search from + * @return {boolean} true on exist + */ + NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { + var list = Array.from(fnSet); + return !!list.filter(function (l) { + var hash = l[0]; + if (hash === args[0]) { + return true; + } + return false; + }).length; + }; + + /** + * get the existing type to make sure no mix type add to the same store + * @param {string} evtName event name + * @param {string} type the type to check + * @return {boolean} true you can add, false then you can't add this type + */ + NbEventServiceBase.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { + this.validateEvt(evtName, type); + var all = this.$get(evtName, true); + if (all === false) { + // pristine it means you can add + return true; + } + // it should only have ONE type in ONE event store + return !all.filter(function (list) { + var t = list[3]; + return type !== t; + }).length; + }; + + /** + * This is checking just the lazy store because the structure is different + * therefore we need to use a new method to check it + */ + NbEventServiceBase.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { + this.validateEvt(evtName, type); + var store = this.lazyStore.get(evtName); + this.logger('(checkTypeInLazyStore)', store); + if (store) { + return !!Array + .from(store) + .filter(function (l) { + var t = l[2]; + return t !== type; + }).length + } + return false; + }; + + /** + * wrapper to re-use the addToStore, + * V1.3.0 add extra check to see if this type can add to this evt + * @param {string} evt event name + * @param {string} type on or once + * @param {function} callback function + * @param {object} context the context the function execute in or null + * @return {number} size of the store + */ + NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { + if ( context === void 0 ) context = null; + + this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); + // @TODO we need to check the existing store for the type first! + if (this.checkTypeInStore(evt, type)) { + this.logger('(addToNormalStore)', (type + " can add to " + evt + " normal store")); + var key = this.hashFnToKey(callback); + var args = [this.normalStore, evt, key, callback, context, type]; + var ref = Reflect.apply(this.addToStore, this, args); + var _store = ref[0]; + var size = ref[1]; + this.normalStore = _store; + return size; + } + return false; + }; + + /** + * Add to lazy store this get calls when the callback is not register yet + * so we only get a payload object or even nothing + * @param {string} evt event name + * @param {array} payload of arguments or empty if there is none + * @param {object} [context=null] the context the callback execute in + * @param {string} [type=false] register a type so no other type can add to this evt + * @return {number} size of the store + */ + NbEventServiceBase.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { + if ( payload === void 0 ) payload = []; + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = false; + + // this is add in V1.6.0 + // when there is type then we will need to check if this already added in lazy store + // and no other type can add to this lazy store + var args = [this.lazyStore, evt, this.toArray(payload), context]; + if (type) { + args.push(type); + } + var ref = Reflect.apply(this.addToStore, this, args); + var _store = ref[0]; + var size = ref[1]; + this.lazyStore = _store; + return size; + }; + + /** + * make sure we store the argument correctly + * @param {*} arg could be array + * @return {array} make sured + */ + NbEventServiceBase.prototype.toArray = function toArray (arg) { + return Array.isArray(arg) ? arg : [arg]; + }; + + /** + * setter to store the Set in private + * @param {object} obj a Set + */ + prototypeAccessors.normalStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); + }; + + /** + * @return {object} Set object + */ + prototypeAccessors.normalStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) + }; + + /** + * setter to store the Set in lazy store + * @param {object} obj a Set + */ + prototypeAccessors.lazyStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); + }; + + /** + * @return {object} the lazy store Set + */ + prototypeAccessors.lazyStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) + }; + + /** + * generate a hashKey to identify the function call + * The build-in store some how could store the same values! + * @param {function} fn the converted to string function + * @return {string} hashKey + */ + NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { + return hashCode(fn.toString()) + ''; + }; + + Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); + + return NbEventServiceBase; + }(SuspendClass)); + + // The top level + // export + var EventService = /*@__PURE__*/(function (NbStoreService) { + function EventService(config) { + if ( config === void 0 ) config = {}; + + NbStoreService.call(this, config); + } + + if ( NbStoreService ) EventService.__proto__ = NbStoreService; + EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); + EventService.prototype.constructor = EventService; + + var prototypeAccessors = { $done: { configurable: true } }; + + /** + * logger function for overwrite + */ + EventService.prototype.logger = function logger () {}; + + ////////////////////////// + // PUBLIC METHODS // + ////////////////////////// + + /** + * Register your evt handler, note we don't check the type here, + * we expect you to be sensible and know what you are doing. + * @param {string} evt name of event + * @param {function} callback bind method --> if it's array or not + * @param {object} [context=null] to execute this call in + * @return {number} the size of the store + */ + EventService.prototype.$on = function $on (evt , callback , context) { + var this$1 = this; + if ( context === void 0 ) context = null; + + var type = 'on'; + this.validate(evt, callback); + // first need to check if this evt is in lazy store + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register first then call later + if (lazyStoreContent === false) { + this.logger('($on)', (evt + " callback is not in lazy store")); + // @TODO we need to check if there was other listener to this + // event and are they the same type then we could solve that + // register the different type to the same event name + + return this.addToNormalStore(evt, type, callback, context) + } + this.logger('($on)', (evt + " found in lazy store")); + // this is when they call $trigger before register this callback + var size = 0; + lazyStoreContent.forEach(function (content) { + var payload = content[0]; + var ctx = content[1]; + var t = content[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this$1.logger("($on)", ("call run on " + evt)); + this$1.run(callback, payload, context || ctx); + size += this$1.addToNormalStore(evt, type, callback, context || ctx); + }); + return size; + }; + + /** + * once only registered it once, there is no overwrite option here + * @NOTE change in v1.3.0 $once can add multiple listeners + * but once the event fired, it will remove this event (see $only) + * @param {string} evt name + * @param {function} callback to execute + * @param {object} [context=null] the handler execute in + * @return {boolean} result + */ + EventService.prototype.$once = function $once (evt , callback , context) { + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'once'; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (lazyStoreContent === false) { + this.logger('($once)', (evt + " not in the lazy store")); + // v1.3.0 $once now allow to add multiple listeners + return this.addToNormalStore(evt, type, callback, context) + } else { + // now this is the tricky bit + // there is a potential bug here that cause by the developer + // if they call $trigger first, the lazy won't know it's a once call + // so if in the middle they register any call with the same evt name + // then this $once call will be fucked - add this to the documentation + this.logger('($once)', lazyStoreContent); + var list = Array.from(lazyStoreContent); + // should never have more than 1 + var ref = list[0]; + var payload = ref[0]; + var ctx = ref[1]; + var t = ref[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this.logger('($once)', ("call run for " + evt)); + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); + } + }; + + /** + * This one event can only bind one callbackback + * @param {string} evt event name + * @param {function} callback event handler + * @param {object} [context=null] the context the event handler execute in + * @return {boolean} true bind for first time, false already existed + */ + EventService.prototype.$only = function $only (evt, callback, context) { + var this$1 = this; + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'only'; + var added = false; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (!nStore.has(evt)) { + this.logger("($only)", (evt + " add to store")); + added = this.addToNormalStore(evt, type, callback, context); + } + if (lazyStoreContent !== false) { + // there are data store in lazy store + this.logger('($only)', (evt + " found data in lazy store to execute")); + var list = Array.from(lazyStoreContent); + // $only allow to trigger this multiple time on the single handler + list.forEach( function (l) { + var payload = l[0]; + var ctx = l[1]; + var t = l[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this$1.logger("($only)", ("call run for " + evt)); + this$1.run(callback, payload, context || ctx); + }); + } + return added; + }; + + /** + * $only + $once this is because I found a very subtile bug when we pass a + * resolver, rejecter - and it never fire because that's OLD added in v1.4.0 + * @param {string} evt event name + * @param {function} callback to call later + * @param {object} [context=null] exeucte context + * @return {void} + */ + EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'onlyOnce'; + var added = false; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (!nStore.has(evt)) { + this.logger("($onlyOnce)", (evt + " add to store")); + added = this.addToNormalStore(evt, type, callback, context); + } + if (lazyStoreContent !== false) { + // there are data store in lazy store + this.logger('($onlyOnce)', lazyStoreContent); + var list = Array.from(lazyStoreContent); + // should never have more than 1 + var ref = list[0]; + var payload = ref[0]; + var ctx = ref[1]; + var t = ref[2]; + if (t && t !== 'onlyOnce') { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this.logger("($onlyOnce)", ("call run for " + evt)); + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); + } + return added; + }; + + /** + * This is a shorthand of $off + $on added in V1.5.0 + * @param {string} evt event name + * @param {function} callback to exeucte + * @param {object} [context = null] or pass a string as type + * @param {string} [type=on] what type of method to replace + * @return {} + */ + EventService.prototype.$replace = function $replace (evt, callback, context, type) { + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = 'on'; + + if (this.validateType(type)) { + this.$off(evt); + var method = this['$' + type]; + this.logger("($replace)", evt, callback); + return Reflect.apply(method, this, [evt, callback, context]) + } + throw new Error((type + " is not supported!")) + }; + + /** + * trigger the event + * @param {string} evt name NOT allow array anymore! + * @param {mixed} [payload = []] pass to fn + * @param {object|string} [context = null] overwrite what stored + * @param {string} [type=false] if pass this then we need to add type to store too + * @return {number} if it has been execute how many times + */ + EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { + if ( payload === void 0 ) payload = []; + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = false; + + this.validateEvt(evt); + var found = 0; + // first check the normal store + var nStore = this.normalStore; + this.logger('($trigger)', 'normalStore', nStore); + if (nStore.has(evt)) { + // @1.8.0 to add the suspend queue + var added = this.$queue(evt, payload, context, type); + this.logger('($trigger)', evt, 'found; add to queue: ', added); + if (added === true) { + this.logger('($trigger)', evt, 'not executed. Exit now.'); + return false; // not executed + } + var nSet = Array.from(nStore.get(evt)); + var ctn = nSet.length; + var hasOnce = false; + for (var i=0; i < ctn; ++i) { + ++found; + // this.logger('found', found) + var ref = nSet[i]; + var _ = ref[0]; + var callback = ref[1]; + var ctx = ref[2]; + var type$1 = ref[3]; + this.logger("($trigger)", ("call run for " + evt)); + this.run(callback, payload, context || ctx); + if (type$1 === 'once' || type$1 === 'onlyOnce') { + hasOnce = true; + } + } + if (hasOnce) { + nStore.delete(evt); + } + return found; + } + // now this is not register yet + this.addToLazyStore(evt, payload, context, type); + return found; + }; + + /** + * this is an alias to the $trigger + * @NOTE breaking change in V1.6.0 we swap the parameter around + * @param {string} evt event name + * @param {*} params pass to the callback + * @param {string} type of call + * @param {object} context what context callback execute in + * @return {*} from $trigger + */ + EventService.prototype.$call = function $call (evt, params, type, context) { + if ( type === void 0 ) type = false; + if ( context === void 0 ) context = null; + + var args = [evt, params, context, type]; + return Reflect.apply(this.$trigger, this, args) + }; + + /** + * remove the evt from all the stores + * @param {string} evt name + * @return {boolean} true actually delete something + */ + EventService.prototype.$off = function $off (evt) { + var this$1 = this; + + this.validateEvt(evt); + var stores = [ this.lazyStore, this.normalStore ]; + var found = false; + stores.forEach(function (store) { + if (store.has(evt)) { + found = true; + this$1.logger('($off)', evt); + store.delete(evt); + } + }); + return found; + }; + + /** + * return all the listener from the event + * @param {string} evtName event name + * @param {boolean} [full=false] if true then return the entire content + * @return {array|boolean} listerner(s) or false when not found + */ + EventService.prototype.$get = function $get (evt, full) { + if ( full === void 0 ) full = false; + + this.validateEvt(evt); + var store = this.normalStore; + if (store.has(evt)) { + return Array + .from(store.get(evt)) + .map( function (l) { + if (full) { + return l; + } + var key = l[0]; + var callback = l[1]; + return callback; + }) + } + return false; + }; + + /** + * store the return result from the run + * @param {*} value whatever return from callback + */ + prototypeAccessors.$done.set = function (value) { + this.logger('($done)', 'value: ', value); + if (this.keep) { + this.result.push(value); + } else { + this.result = value; + } + }; + + /** + * @TODO is there any real use with the keep prop? + * getter for $done + * @return {*} whatever last store result + */ + prototypeAccessors.$done.get = function () { + if (this.keep) { + this.logger('(get $done)', this.result); + return this.result[this.result.length - 1] + } + return this.result; + }; + + Object.defineProperties( EventService.prototype, prototypeAccessors ); + + return EventService; + }(NbEventServiceBase)); + + // default + + // this will generate a event emitter and will be use everywhere + // output + function getEventEmitter(debugOn) { + var logger = debugOn ? function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + args.unshift('[NBS]'); + console.log.apply(null, args); + }: undefined; + return new EventService({ logger: logger }) + } + + // main export interface + /** + * When pass a static contract then it return a static interface + * otherwise it will become the async interface + * @param {object} fly the http engine - already init object not the class! + * @param {object} config configuration + * @return {object} jsonqlClient + */ + function jsonqlClient(fly, config) { + var ee = getEventEmitter(config.debugOn); + return jsonqlAsync(ee, config, fly) + } + + // this one will bring the fly.js in + + function full(config) { + if ( config === void 0 ) config = {}; + + return jsonqlClient(new Fly(), config) + } + + return full; + +}))); //# sourceMappingURL=jsonql-client.umd.js.map diff --git a/packages/http-client/dist/jsonql-client.umd.js.map b/packages/http-client/dist/jsonql-client.umd.js.map index 020e341a..904c3af6 100644 --- a/packages/http-client/dist/jsonql-client.umd.js.map +++ b/packages/http-client/dist/jsonql-client.umd.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client.umd.js","sources":["../node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"457CAAA"} \ No newline at end of file +{"version":3,"file":"jsonql-client.umd.js","sources":["../node_modules/lodash-es/isArray.js","../node_modules/rollup-plugin-node-globals/src/global.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/lodash-es/_arrayMap.js","../node_modules/lodash-es/_baseSlice.js","../node_modules/lodash-es/_baseFindIndex.js","../node_modules/lodash-es/_baseIsNaN.js","../node_modules/lodash-es/_strictIndexOf.js","../node_modules/lodash-es/_asciiToArray.js","../node_modules/lodash-es/_hasUnicode.js","../node_modules/lodash-es/_unicodeToArray.js","../node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-errors/src/get-error-by-status.js","../node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-errors/src/resolver-not-found-error.js","../node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-errors/src/index.js","../node_modules/jsonql-errors/src/client-errors-handler.js","../node_modules/jsonql-errors/src/get-error-name-by-instance.js","../node_modules/jsonql-errors/index.js","../node_modules/jsonql-utils/src/contract.js","../node_modules/nb-event-service/src/hash-code.js","../src/utils.js","../node_modules/jwt-decode/lib/atob.js","../node_modules/jsonql-params-validator/src/string.js","../node_modules/jsonql-jwt/src/client/decode-token/decode-token.js","../node_modules/jsonql-params-validator/src/number.js","../node_modules/jsonql-params-validator/src/boolean.js","../node_modules/jsonql-params-validator/src/any.js","../node_modules/jsonql-params-validator/src/constants.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/_listCacheClear.js","../node_modules/lodash-es/eq.js","../node_modules/lodash-es/_stackDelete.js","../node_modules/lodash-es/_stackGet.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-params-validator/src/validator.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/negate.js","../node_modules/lodash-es/_baseFindKey.js","../node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-params-validator/src/options/check-options-async.js","../node_modules/jsonql-params-validator/src/options/construct-config.js","../node_modules/jsonql-params-validator/src/options/index.js","../node_modules/jsonql-params-validator/index.js","../node_modules/jsonql-utils/src/timestamp.js","../node_modules/store/plugins/defaults.js","../src/stores/local-store.js","../src/stores/session-store.js","../src/stores/index.js","../node_modules/jsonql-utils/src/params-api.js","../node_modules/jsonql-utils/src/results.js","../src/base/store-cls.js","../src/base/http-cls.js","../src/base/contract-cls.js","../src/base/auth-cls.js","../src/base/base-cls.js","../src/base/index.js","../src/core/methods-generator.js","../src/core/jsonql-api-generator.js","../src/options/base-options.js","../src/options/check-options-async.js","../src/options/index.js","../src/jsonql-async.js","../node_modules/nb-event-service/src/suspend.js","../node_modules/nb-event-service/src/store-service.js","../node_modules/nb-event-service/src/event-service.js","../node_modules/nb-event-service/index.js","../src/ee.js","../index.js","../full.js"],"sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length;\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg];\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @return {*} json object on success\n */\nconst parse = function(n) {\n try {\n return JSON.parse(n)\n } catch(e) {\n return n;\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false;\n /*\n console.info('obj', obj)\n console.error(e)\n throw new Error(e)\n */\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = (n) => {\n if (typeof n === 'string') {\n return parse(n)\n }\n return JSON.parse(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== '';\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n","// just a simple util method to return the error based on the status code\n/**\n * @param {number} statusCode to check\n * @param {boolean} contract if this is a contract call or not\n * @return {string} the error name\n */\nexport default function getErrorByStatus(statusCode, contract = false) {\n switch (statusCode) {\n case 401:\n return contract ? 'JsonqlContractAuthError' : 'JsonqlAuthorisationError';\n case 403:\n return 'JsonqlForbiddenError';\n case 404:\n return 'JsonqlResolverNotFoundError';\n case 406:\n return 'Jsonql406Error';\n case 500:\n return 'Jsonql500Error';\n default:\n return 'JsonqlError';\n }\n}\n","/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error)\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","/**\n * This is a custom error to throw when could not find the resolver\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class JsonqlResolverNotFoundError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlResolverNotFoundError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlResolverNotFoundError);\n }\n }\n\n static get statusCode() {\n return 404;\n }\n\n static get name() {\n return 'JsonqlResolverNotFoundError';\n }\n}\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError);\n }\n }\n\n static get name() {\n return 'JsonqlEnumError';\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlTypeError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError);\n }\n }\n\n static get name() {\n return 'JsonqlTypeError';\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args)\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError)\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError';\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError';\n }\n}\n","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message)\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// server side\nimport Jsonql406Error from './406-error';\nimport Jsonql500Error from './500-error';\nimport JsonqlAuthorisationError from './authorisation-error';\nimport JsonqlContractAuthError from './contract-auth-error';\nimport JsonqlResolverAppError from './resolver-app-error';\nimport JsonqlResolverNotFoundError from './resolver-not-found-error';\n\n// check options error\nimport JsonqlEnumError from './enum-error';\nimport JsonqlTypeError from './type-error';\nimport JsonqlCheckerError from './checker-error';\n// share\nimport JsonqlValidationError from './validation-error';\nimport JsonqlError from './error';\n\nimport JsonqlServerError from './server-error';\n\nexport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n};\n","// this will add directly to the then call in each http call\n\nimport * as errors from './index';\nimport getErrorByStatus from './get-error-by-status';\nimport { NO_ERROR_MSG } from 'jsonql-constants';\nconst { JsonqlError } = errors;\n\n/**\n * We can not just check something like result.data what if the result if false?\n * @param {object} obj the result object\n * @param {string} key we want to check if its exist or not\n * @return {boolean} true on found\n */\nconst isObjectHasKey = (obj, key) => {\n const keys = Object.keys(obj)\n return !!keys.filter(k => key === k).length;\n}\n\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nexport default function clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n","// get error name by instance\nconst UNKNOWN_ERROR = 'unknown'\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {array} filtered with name as value\n */\nfunction mapErrToName(errs, e) {\n return errs.filter(err => e instanceof err)\n .map(err => err.name)\n}\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {string} name of the error object\n */\nfunction getErrorNameByInstance(errs, e) {\n let error = mapErrToName(errs, e)\n return error.length ? error[0] : UNKNOWN_ERROR\n}\n\n/**\n * the same as above with a default JsonqlError as default\n * @param {array} errs same\n * @param {object} e error itself\n * @return {string} the name of the error\n */\nfunction getErrorNameByInstanceWithDefault(errs, e) {\n let name = getErrorNameByInstance(errs, e)\n return name === UNKNOWN_ERROR ? 'JsonqlError' : name;\n}\n\n\nexport {\n getErrorNameByInstanceWithDefault,\n getErrorNameByInstance,\n UNKNOWN_ERROR\n}\n","// jsonql-errors main interface\nimport getErrorByStatus from './src/get-error-by-status'\nimport clientErrorsHandler from './src/client-errors-handler'\nimport {\n getErrorNameByInstance,\n getErrorNameByInstanceWithDefault,\n UNKNOWN_ERROR\n} from './src/get-error-name-by-instance'\nimport finalCatch from './src/final-catch.js'\nconst JSONQL_ERRORS_INFO = '__PLACEHOLDER__'\nimport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n JsonqlValidationError,\n JsonqlError,\n JsonqlServerError\n} from './src'\n// export\nexport {\n JSONQL_ERRORS_INFO,\n UNKNOWN_ERROR,\n\n getErrorByStatus,\n clientErrorsHandler,\n finalCatch,\n getErrorNameByInstance,\n getErrorNameByInstanceWithDefault,\n\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n}\n","// split the contract into the node side and the generic side\nimport { isObjectHasKey } from './generic'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n SOCKET_NAME,\n QUERY_ARG_NAME,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlResolverNotFoundError } from 'jsonql-errors'\n/**\n * Check if the json is a contract file or not\n * @param {object} contract json object\n * @return {boolean} true\n */\nexport function checkIsContract(contract) {\n return isPlainObject(contract)\n && (\n isObjectHasKey(contract, QUERY_NAME)\n || isObjectHasKey(contract, MUTATION_NAME)\n || isObjectHasKey(contract, SOCKET_NAME)\n )\n}\n\n/**\n * Wrapper method that check if it's contract then return the contract or false\n * @param {object} contract the object to check\n * @return {boolean | object} false when it's not\n */\nexport function isContract(contract) {\n return checkIsContract(contract) ? contract : false;\n}\n\n/**\n * Ported from jsonql-params-validator but different\n * if we don't find the socket part then return false\n * @param {object} contract the contract object\n * @return {object|boolean} false on failed\n */\nexport function extractSocketPart(contract) {\n if (isObjectHasKey(contract, 'socket')) {\n return contract.socket;\n }\n return false;\n}\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @param {boolean} [fallback=false] this is a fall back option for old code\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport function groupByNamespace(contract, fallback = false) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n if (fallback) {\n return contract; // just return the whole contract\n }\n throw new JsonqlError(`socket not found in contract!`)\n }\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\n}\n\n/**\n * @NOTE ported from jsonql-ws-client\n * Got to make sure the connection order otherwise\n * it will hang\n * @param {object} nspSet contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspSet, publicNamespace) {\n let names = []; // need to make sure the order!\n for (let namespace in nspSet) {\n if (namespace === publicNamespace) {\n names[1] = namespace;\n } else {\n names[0] = namespace;\n }\n }\n return names;\n}\n\n\n/**\n * Extract the args from the payload\n * @param {object} payload to work with\n * @param {string} type of call\n * @return {array} args\n */\nexport function extractArgsFromPayload(payload, type) {\n switch (type) {\n case QUERY_NAME:\n return payload[QUERY_ARG_NAME];\n case MUTATION_NAME:\n return [\n payload[PAYLOAD_PARAM_NAME],\n payload[CONDITION_PARAM_NAME]\n ];\n default:\n throw new JsonqlError(`Unknown ${type} to extract argument from!`)\n }\n}\n\n/**\n * Like what the name said\n * @param {object} contract the contract json\n * @param {string} type query|mutation\n * @param {string} name of the function\n * @return {object} the params part of the contract\n */\nexport function extractParamsFromContract(contract, type, name) {\n try {\n const result = contract[type][name];\n // debug('extractParamsFromContract', result)\n if (!result) {\n // debug(name, type, contract)\n throw new JsonqlResolverNotFoundError(name, type)\n }\n return result;\n } catch(e) {\n throw new JsonqlResolverNotFoundError(name, e)\n }\n}\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport default function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n","// take only the module part which is what we use here\n// and export it again to use through out the client\n// this way we avoid those that we don't want node.js module got build into the code\nimport { isContract } from 'jsonql-utils/src/contract'\nimport hashCodeFn from 'nb-event-service/src/hash-code'\n/**\n * @param {object} jsonqlInstance the init instance of jsonql client\n * @param {object} contract the static contract\n * @return {object} contract may be from server\n */\nconst getContractFromConfig = function(jsonqlInstance, contract = {}) {\n if (isContract(contract)) {\n return Promise.resolve(contract)\n }\n return jsonqlInstance.getContract()\n}\n// wrapper method to make sure it's a string\nconst hashCode = str => hashCodeFn(str) + ''\n\n// simple util to check if an object has any properties\n// const hasProp = obj => isObject(obj) && Object.keys(obj).length\n\n// export some constants as well\n// since it's only use here there is no point of adding it to the constants module\n// or may be we add it back later\nconst ENDPOINT_TABLE = 'endpoint' // not in use anymore delete later @TODO\nconst USERDATA_TABLE = 'userdata'\nconst CLS_LOCAL_STORE_NAME = 'localStore'\nconst CLS_SESS_STORE_NAME = 'sessionStore'\nconst CLS_CONTRACT_NAME = 'contract'\nconst CLS_PROFILE_IDX = 'prof_idx'\nconst ZERO_IDX = 0\n// export\nexport {\n hashCode,\n getContractFromConfig,\n ENDPOINT_TABLE,\n USERDATA_TABLE,\n CLS_LOCAL_STORE_NAME,\n CLS_SESS_STORE_NAME,\n CLS_CONTRACT_NAME,\n CLS_PROFILE_IDX,\n ZERO_IDX\n}\n","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\nfunction polyfill (input) {\n var str = String(input).replace(/=+$/, '');\n if (str.length % 4 == 1) {\n throw new InvalidCharacterError(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = '';\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n return output;\n}\n\n\nmodule.exports = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill;\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false;\n}\n\nexport default checkIsString\n","// when the user is login with the jwt\n// we use call this to decode the token and then add the payload\n// to the resolver so the user can call ResolverName.userdata\n// and get back the payload\nimport jwt_decode from 'jwt-decode'\nimport isString from 'jsonql-params-validator/src/string'\nimport JsonqlError from 'jsonql-errors/src/error'\n\nconst timestamp = function (sec = false) {\n var time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n\n/**\n * We only check the nbf and exp\n * @param {object} token for checking\n * @return {object} token on success\n */\nfunction validate(token) {\n const start = token.iat || timestamp(true)\n // we only check the exp for the time being\n if (token.exp) {\n if (start >= token.exp) {\n const expired = new Date(token.exp).toISOString()\n throw new JsonqlError(`Token has expired on ${expired}`, token)\n }\n }\n return token;\n}\n\n/**\n * The browser client version it has far fewer options and it doesn't verify it\n * because it couldn't this is the job for the server\n * @TODO we need to add some extra proessing here to check for the exp field\n * @param {string} token to decrypted\n * @return {object} decrypted object\n */\nexport default function jwtDecode(token) {\n if (isString(token)) {\n const t = jwt_decode(token)\n return validate(t)\n }\n throw new JsonqlError('Token must be a string!')\n}\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nexport const ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\n","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber;\n case STRING_TYPE:\n return checkIsString;\n case BOOLEAN_TYPE:\n return checkIsBoolean;\n default:\n return checkIsAny;\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false;\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false;\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p;\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length;\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length;\n}\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport filter from 'lodash-es/filter'\n\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true;\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (_value !== undefined) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true;\n }).length)\n }).length;\n }\n }\n return false;\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p;\n let _args = [arg];\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return Reflect.apply(checkIsObject, null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\n\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n checkIsObject,\n combineFn,\n notEmpty\n} from './index'\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params;\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false;\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (arg !== undefined) {\n return arg;\n }\n return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ))\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ))\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ))\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length:\n let ctn = params.length;\n // this happens when we have those array. type\n let _type = [ DEFAULT_TYPE ]\n // we only looking at the first one, this might be a @BUG\n /*\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n } */\n // if we use the params as guide then the rest will get throw out\n // which is not what we want, instead, anything without the param\n // will get a any type and optional flag\n return args.map((arg, i) => {\n let optional = i >= ctn ? true : !!params[i].optional\n let param = params[i] || { type: _type, name: `_${i}` }\n return {\n arg: optional ? getOptionalValue(arg, param) : arg,\n index: i,\n param,\n optional\n }\n })\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n // v1.4.4 this fixed the problem, the root level optional is from the last fn\n if (p.optional === true || p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length;\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport isFunction from 'lodash-es/isFunction'\nimport merge from 'lodash-es/merge'\nimport mapValues from 'lodash-es/mapValues'\n\nimport JsonqlEnumError from 'jsonql-errors/src/enum-error'\nimport JsonqlTypeError from 'jsonql-errors/src/type-error'\nimport JsonqlCheckerError from 'jsonql-errors/src/checker-error'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true;\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // log('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n // log(ENUM_KEY, value[ENUM_KEY])\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n // log(CHECKER_KEY, value[CHECKER_KEY])\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args;\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","/// this is port back from the client to share across all projects\n\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:check-options-async')\n\n/**\n * Quick transform\n * @param {object} config that one\n * @param {object} appProps mutation configuration options\n * @return {object} put that arg into the args\n */\nconst configToArgs = (config, appProps) => {\n return Promise.resolve(\n prepareArgsForValidation(config, appProps)\n )\n}\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return configToArgs(config, appProps)\n .then(args1 => runValidation(args1, cb))\n // next if every thing good then pass to final merging\n .then(args2 => merge({}, args2, constProps))\n}\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\nimport checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n };\n if (optional === true) {\n base[OPTIONAL_KEY] = true;\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv;\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker;\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias;\n }\n return base;\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__';\n\n/**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n checkConfigAsync,\n checkConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nexport const inArray = isInArray;\nexport const isObjectHasKey = isObjectHasKeyFn;\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n","module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n","// sort of persist on the user side\nimport engine from 'store/src/store-engine'\n\nimport localStorage from 'store/storages/localStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// @1.5.0 stop using the expired plugin, and deal with it ourself\n// import expiredPlugin from 'store/plugins/expire'\nimport eventsPlugin from 'store/plugins/events'\nimport compressionPlugin from 'store/plugins/compression'\n\nconst storages = [localStorage, cookieStorage]\nconst plugins = [defaultPlugin, eventsPlugin, compressionPlugin]\n\nconst localStore = engine.createStore(storages, plugins)\n\nexport default localStore\n","// session store with watch\nimport engine from 'store/src/store-engine'\n\nimport sessionStorage from 'store/storages/sessionStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// start using compression in 1.5.0 \nimport compressionPlugin from 'store/plugins/compression'\n// @1.5.0 stop using the expired plugin and deal it ourself\n// import expiredPlugin from 'store/plugins/expire'\n\nconst storages = [sessionStorage, cookieStorage]\nconst plugins = [defaultPlugin, compressionPlugin]\n\nconst sessionStore = engine.createStore(storages, plugins)\n\nexport default sessionStore\n","// export store interface\n// @TODO need to figure out how to make this as a outside dependencies instead of built into it\nimport localStoreEngine from './local-store'\nimport sessionStoreEngine from './session-store'\n\n// export back the raw version for development purposes\nexport const localStore = localStoreEngine\nexport const sessionStore = sessionStoreEngine\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport isString from 'lodash-es/isString'\n\nimport { timestamp } from './timestamp'\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? JSON.parse(payload) : payload;\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName\n * @param {*} payload\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload) {\n return {\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload;\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload;\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getNameFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// break up from node-middleware\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n API_REQUEST_METHODS,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME ,\n QUERY_ARG_NAME,\n DATA_KEY,\n ERROR_KEY,\n INDEX_KEY,\n EXT,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport { isObjectHasKey } from './generic'\nimport { timestamp } from './timestamp'\nimport isArray from 'lodash-es/isArray'\nimport merge from 'lodash-es/merge'\n/**\n * getting what is calling after the above check\n * @param {string} method of call\n * @return {mixed} false on failed\n */\nexport const getCallMethod = method => {\n const [ POST, PUT ] = API_REQUEST_METHODS;\n switch (true) {\n case method === POST:\n return QUERY_NAME;\n case method === PUT:\n return MUTATION_NAME;\n default:\n return false;\n }\n}\n\n/**\n * wrapper method\n * @param {mixed} result of fn return\n * @param {boolean|array} [ts=false] when pass this then we append a new value to the end\n * @return {string} stringify data\n */\nexport const packResult = function(result, ts = false) {\n let payload = { [DATA_KEY]: result }\n if (ts && isArray(ts)) {\n ts.push(timestamp())\n payload[TIMESTAMP_PARAM_NAME] = ts\n }\n return JSON.stringify(payload)\n}\n\n/**\n * Check if the error object contain out custom key\n * @param {*} e object\n * @return {boolean} true\n */\nexport const isJsonqlErrorObj = e => {\n const searchFields = ['detail', 'className']\n const test = !!searchFields.filter(field => isObjectHasKey(e, field)).length\n if (test) {\n return ['className', 'message', 'statusCode']\n .filter(field => isObjectHasKey(e, field))\n .map(field => (\n {\n [field]: typeof e[field] === 'object' ? e[field].toString() : e[field]\n }\n ))\n .reduce(merge, {detail: e.toString()}) // can only get as much as possible\n }\n return false;\n}\n\n/**\n * wrapper method - the output is trying to match up the structure of the Error sub class\n * @param {mixed} detail of fn error\n * @param {string} [className=JsonqlError] the errorName\n * @param {number} [statusCode=500] the original error code\n * @return {string} stringify error\n */\nexport const packError = function(detail, className = 'JsonqlError', statusCode = 0, message = '') {\n let errorObj = { detail, className, statusCode, message }\n // we need to check the detail object to see if it has detail, className and message\n // if it has then we should merge the object instead\n return JSON.stringify({\n [ERROR_KEY]: isJsonqlErrorObj(detail) || errorObj,\n [TIMESTAMP_PARAM_NAME]: timestamp()\n })\n}\n\n// ported from http-client\n\n/**\n * handle the return data\n * @TODO how to handle the return timestamp and calculate the diff?\n * @param {object} result return from server\n * @return {object} strip the data part out, or if the error is presented\n */\nexport const resultHandler = result => (\n (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result\n)\n","// new 1.5.0\n// create a class method to handle all the saving and retriving data\n// using the instanceKey to id the data hence allow to use multiple instance\nimport merge from 'lodash-es/merge'\nimport { localStore, sessionStore } from '../stores'\nimport { CLS_SESS_STORE_NAME, CLS_LOCAL_STORE_NAME, hashCode } from '../utils'\n\n// this becomes the base class instead of the HttpCls\nexport default class StoreClass {\n\n constructor(opts) {\n this.opts = opts\n // make it a string\n this.instanceKey = hashCode(this.opts.hostname)\n // pass this store for use later\n this.localStore = localStore\n this.sessionStore = sessionStore\n /*\n if (this.opts.debugOn) { // reuse this to clear out the data\n this.log('clear all stores')\n localStore.clearAll()\n sessionStore.clearAll()\n\n localStore.set('TEST', Date.now())\n sessionStore.set('TEST', Date.now())\n }\n */\n }\n // store in local storage id by the instanceKey\n // values should be an object so with key so we just merge\n // into the existing store without going through the keys\n __setMethod(storeType, values) {\n let store = this[storeType]\n let data = this.__getMethod(storeType)\n const skey = this.opts.storageKey\n const ikey = this.instanceKey\n store.set(skey, {\n [ikey]: data ? merge({}, data, values) : values\n })\n }\n // return the data id by the instaceKey\n __getMethod(storeType) {\n let store = this[storeType]\n let data = store.get(this.opts.storageKey)\n return data ? data[this.instanceKey] : false\n }\n // remove from local store id by instanceKey\n __delMethod(storeType, key) {\n let data = this.__getMethod(storeType)\n if (data) {\n let store = {}\n for (let k in data) {\n if (k !== key) {\n store[k] = data[k]\n }\n }\n this.__setMethod(storeType, store)\n }\n }\n // clear everything by this instanceKey\n __clearMethod(storeKey) {\n const skey = this.opts.storageKey\n const store = this[storeKey]\n let data = store.get(skey)\n if (data) {\n let _store = {}\n for (let k in data) {\n if (k !== this.instanceKey) {\n _store[k] = data[k]\n }\n }\n store.set(skey, _store)\n }\n }\n // Alias for different store\n set lset(values) {\n return this.__setMethod(CLS_LOCAL_STORE_NAME, values)\n }\n\n get lget() {\n return this.__getMethod(CLS_LOCAL_STORE_NAME)\n }\n\n ldel(key) {\n return this.__delMethod(CLS_LOCAL_STORE_NAME, key)\n }\n\n lclear() {\n return this.__clearMethod(CLS_LOCAL_STORE_NAME)\n }\n\n // store in session store id by the instanceKey\n set sset(values) {\n // this.log('--- sset ---', values)\n return this.__setMethod(CLS_SESS_STORE_NAME, values)\n }\n\n get sget() {\n return this.__getMethod(CLS_SESS_STORE_NAME)\n }\n\n sdel(key) {\n return this.__delMethod(CLS_SESS_STORE_NAME, key)\n }\n\n sclear() {\n return this.__clearMethod(CLS_SESS_STORE_NAME)\n }\n\n\n}\n","// base HttpClass\nimport merge from 'lodash-es/merge'\nimport {\n createQuery,\n createMutation,\n getNameFromPayload\n} from 'jsonql-utils/src/params-api'\nimport { cacheBurst, urlParams } from 'jsonql-utils/src/urls'\nimport { resultHandler } from 'jsonql-utils/src/results'\nimport { isObject, isString } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlServerError,\n JsonqlError,\n // clientErrorsHandler\n} from 'jsonql-errors'\nimport {\n API_REQUEST_METHODS,\n DEFAULT_HEADER,\n JSONP_CALLBACK_NAME,\n SHOW_CONTRACT_DESC_PARAM\n} from 'jsonql-constants'\n\n// @DEBUG\nimport * as errors from 'jsonql-errors'\nimport { isObjectHasKey } from 'jsonql-utils/src/generic'\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nfunction clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n console.info('--- errorName ---', errorName, errors)\n\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n\n\n\n// extract the one we need\nconst [ POST, PUT ] = API_REQUEST_METHODS\n\nimport StoreClass from './store-cls'\n\nexport default class HttpClass extends StoreClass {\n /**\n * The opts has been check at the init stage\n * @param {object} opts configuration options\n */\n constructor(opts) {\n super(opts)\n // change the way how we init Fly\n // flyio now become external depedencies and it makes it easier to switch\n // @BUG should we run test to check if we have the windows object?\n // this.log(opts)\n // this.fly = opts.Fly ? new opts.Fly() : new Fly()\n // to a different environment like WeChat mini app\n\n this.extraHeader = {};\n // @1.2.1 for adding query to the call on the fly\n this.extraParams = {};\n // this.log('start up opts', opts);\n this.reqInterceptor()\n this.resInterceptor()\n }\n\n // set headers for that one call\n set headers(header) {\n this.extraHeader = header;\n }\n\n /**\n * Create the reusage request method\n * @param {object} payload jsonql payload\n * @param {object} options extra options add the request\n * @param {object} headers extra headers add to the call\n * @return {object} the fly request instance\n */\n request(payload, options = {}, headers = {}) {\n this.headers = headers;\n let params = merge({}, cacheBurst(), this.extraParams)\n // @TODO need to add a jsonp url and payload\n if (this.opts.enableJsonp) {\n let resolverName = getNameFromPayload(payload)\n params = merge({}, params, {[JSONP_CALLBACK_NAME]: resolverName})\n payload = payload[resolverName]\n }\n // double up the url param and see what happen @TODO remove later\n const reqParams = merge({}, { method: POST, params }, options)\n this.log('request params', reqParams, this.jsonqlEndpoint)\n\n return this.fly.request(this.jsonqlEndpoint, payload, reqParams)\n }\n\n /**\n * This will replace the create baseRequest method\n *\n */\n reqInterceptor() {\n this.fly.interceptors.request.use(\n req => {\n const headers = this.getHeaders()\n this.log('request interceptor call', headers)\n\n for (let key in headers) {\n req.headers[key] = headers[key]\n }\n return req;\n }\n )\n }\n\n // @TODO\n processJsonp(result) {\n return resultHandler(result)\n }\n\n /**\n * This will be replacement of the first then call\n *\n */\n resInterceptor() {\n const self = this;\n const jsonp = self.opts.enableJsonp;\n this.fly.interceptors.response.use(\n res => {\n this.log('response interceptor call', res)\n self.cleanUp()\n // now more processing here\n // there is a problem if we throw the result.error here\n // the original data is lost, so we need to do what we did before\n // deal with that error in the first then instead\n const result = isString(res.data) ? JSON.parse(res.data) : res.data;\n if (jsonp) {\n return self.processJsonp(result)\n }\n return resultHandler(result)\n },\n // this get call when it's not 200\n err => {\n self.cleanUp()\n console.error(err)\n throw new JsonqlServerError('Server side error', err)\n }\n )\n }\n\n /**\n * Get the headers inject into the call\n * @return {object} headers\n */\n getHeaders() {\n if (this.opts.enableAuth) {\n return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader)\n }\n return merge({}, DEFAULT_HEADER, this.extraHeader)\n }\n\n /**\n * Post http call operation to clean up things we need\n */\n cleanUp() {\n this.extraHeader = {}\n this.extraParams = {}\n }\n\n /**\n * GET for contract only\n * @return {promise} resolve the contract\n */\n getRemoteContract() {\n if (this.opts.showContractDesc) {\n this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM)\n }\n return this.request({}, {method: 'GET'}, this.contractHeader)\n .then(clientErrorsHandler)\n .then(result => {\n this.log('get contract result', result)\n // when refresh the window the result is different!\n // @TODO need to check the Koa side about why is that\n // also it should set a flag if we want the description or not\n if (result.cache && result.contract) {\n return result.contract;\n }\n // just the normal result\n return result\n })\n .catch(err => {\n console.error('getRemoteContract err', err)\n throw new JsonqlServerError('getRemoteContract', err)\n })\n }\n\n /**\n * POST to server - query\n * @param {object} name of the resolver\n * @param {array} args arguments\n * @return {object} promise resolve to the resolver return\n */\n query(name, args = []) {\n return this.request(createQuery(name, args))\n .then(clientErrorsHandler)\n }\n\n /**\n * PUT to server - mutation\n * @param {string} name of resolver\n * @param {object} payload what it said\n * @param {object} conditions what it said\n * @return {object} promise resolve to the resolver return\n */\n mutation(name, payload = {}, conditions = {}) {\n return this.request(createMutation(name, payload, conditions), {method: PUT})\n .then(clientErrorsHandler)\n }\n\n}\n","// all the contract related methods will be here\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { timestamp } from 'jsonql-utils/src/timestamp'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { ENDPOINT_TABLE, CLS_CONTRACT_NAME } from '../utils'\nimport { localStore } from '../stores'\nimport HttpClass from './http-cls'\n\n// export\nexport default class ContractClass extends HttpClass {\n\n constructor(opts) {\n super(opts)\n }\n\n /**\n * return the contract public api\n * @return {object} contract\n */\n getContract() {\n const contract = this.readContract()\n this.log('getContract first call', contract)\n return contract ? Promise.resolve(contract)\n : this.getRemoteContract().then(this.storeContract.bind(this))\n }\n\n /**\n * We are changing the way how to auth to get the contract.json\n * Instead of in the url, we will be putting that key value in the header\n * @return {object} header\n */\n get contractHeader() {\n let base = {};\n if (this.opts.contractKey !== false) {\n base[this.opts.contractKeyName] = this.opts.contractKey;\n }\n return base;\n }\n\n /**\n * Save the contract to local store\n * @param {object} contract to save\n * @return {object|boolean} false when its not a contract or contract on OK\n */\n storeContract(contract) {\n // first need to check if the contract is a contract\n if (!isContract(contract)) {\n throw new JsonqlValidationError(`Contract is malformed!`)\n //return false;\n }\n /* @TODO need to rethink how to expired the contract\n let args = [contract]\n if (this.opts.contractExpired) {\n let expired = parseFloat(this.opts.contractExpired)\n if (!isNaN(expired) && expired > 0) {\n args.push(expired)\n }\n }\n // calling the setter\n this.jsonqlContract = args;\n */\n this.lset = {[CLS_CONTRACT_NAME]: contract}\n // return it\n this.log('storeContract return result', contract)\n return contract;\n }\n\n /**\n * return the contract from options or localStore\n * @return {object|boolean} false on not found\n */\n readContract() {\n let contract = isContract(this.opts.contract)\n if (contract !== false) {\n return contract;\n }\n let data = this.lget\n if (data) {\n return data[CLS_CONTRACT_NAME]\n }\n return false;\n }\n}\n","// this is the new auth class that integrate with the jsonql-jwt\n// all the auth related methods will be here\nimport { decodeToken } from 'jsonql-jwt/src/client'\nimport { isNumber } from 'jsonql-params-validator'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { CREDENTIAL_STORAGE_KEY, AUTH_HEADER, BEARER } from 'jsonql-constants'\nimport { CLS_PROFILE_IDX, ZERO_IDX, USERDATA_TABLE } from '../utils'\nimport ContractClass from './contract-cls'\n// export\nexport default class AuthClass extends ContractClass {\n\n constructor(opts) {\n super(opts)\n if (opts.enableAuth) {\n this.setDecoder = decodeToken;\n }\n }\n\n /**\n * for overwrite\n * @param {string} token stored token\n * @return {string} token\n */\n decoder(token) {\n return token;\n }\n\n /**\n * set the profile index\n * @param {number} idx\n */\n set profileIndex(idx) {\n const key = CLS_PROFILE_IDX\n if (isNumber(idx)) {\n this[key] = idx;\n if (this.opts.persistToken) {\n this.lset = {[key]: idx}\n }\n return;\n }\n throw new JsonqlValidationError('profileIndex', `Expect idx to be number but got ${typeof idx}`)\n }\n\n /**\n * get the profile index\n * @return {number} idx\n */\n get profileIndex() {\n const key = CLS_PROFILE_IDX\n if (this.opts.persistToken) {\n const data = this.lget;\n if (data[key]) {\n return data[key]\n }\n }\n return this[key] ? this[key] : ZERO_IDX\n }\n\n /**\n * Return the token from session store\n * @param {number} [idx=false] profile index\n * @return {string} token\n */\n rawAuthToken(idx = false) {\n if (idx !== false) {\n this.profileIndex = idx;\n }\n // this should return from the base\n return this.jsonqlToken; // see base-cls\n }\n\n /**\n * Setter to add a decoder when retrieve user token\n * @param {function} d a decoder\n */\n set setDecoder(d) {\n if (typeof d === 'function') {\n this.decoder = d;\n }\n }\n\n /**\n * getter to return the session or local store set method\n * @param {*} data to save\n * @return {object} set method\n */\n set saveProfile(data) {\n if (this.opts.persistToken) {\n // this.log('--- saveProfile lset ---', data)\n this.lset = data\n } else {\n // this.log('--- saveProfile sset ---', data)\n this.sset = data\n }\n }\n\n /**\n * getter to return the session or local store get method\n * @return {object} get method\n */\n get readProfile() {\n return this.opts.persistToken ? this.lget : this.sget\n }\n\n // these were in the base class before but it should be here\n /**\n * save token\n * @param {string} token to store\n * @return {string|boolean} false on failed\n */\n set jsonqlToken(token) {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n // @TODO also have to make sure the token is not already existed!\n let tokens = (data && data[key]) ? data[key] : []\n tokens.push(token)\n this.saveProfile = {[key]: tokens}\n // store the userdata\n this.jsonqlUserdata = this.decoder(token)\n }\n\n /**\n * Jsonql token getter\n * 1.5.1 each token associate with the same profileIndex\n * @return {string|boolean} false when failed\n */\n get jsonqlToken() {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex])\n return data[key][this.profileIndex]\n }\n return false\n }\n\n /**\n * this one will use the sessionStore\n * basically we hook this onto the token store and decode it to store here\n * we only store one decoded user data at a time, but the token can be multiple\n */\n set jsonqlUserdata(userdata) {\n this.sset = {[USERDATA_TABLE]: userdata}\n }\n\n /**\n * this one store in the session store\n * get login userdata decoded jwt\n * 1.5.1 each userdata associate with the same profileIndex\n * @return {object|null}\n */\n get jsonqlUserdata() {\n const data = this.sget\n return data ? data[USERDATA_TABLE] : false\n }\n\n /**\n * Construct the auth header\n * @return {object} header\n */\n getAuthHeader() {\n const token = this.jsonqlToken // only call the getter to get the default one\n return token ? {[this.opts.AUTH_HEADER]: `${BEARER} ${token}`} : {};\n }\n\n /**\n * return all the stored token and decode it\n * @param {number} [idx=false] profile index\n * @return {array|boolean|string} false not found or array\n */\n getProfiles(idx = false) {\n const self = this; // just in case the scope problem\n const data = self.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n if (idx !== false && isNumber(idx)) {\n return data[key][idx] || false\n }\n return data[key].map(self.decoder.bind(self))\n }\n return false\n }\n\n /**\n * call after the login\n * @param {string} token return from server\n * @return {object} decoded token to userdata object\n */\n postLoginAction(token) {\n this.jsonqlToken = token\n return token\n }\n\n /**\n * call after the logout @TODO\n */\n postLogoutAction(...args) {\n console.info(`postLogoutAction`, args)\n }\n}\n","// this the core of the internal storage management\nimport { CREDENTIAL_STORAGE_KEY } from 'jsonql-constants'\n// import { isObject, isArray } from 'jsonql-params-validator'\n// import { JsonqlValidationError } from 'jsonql-errors'\n// import { timestamp } from 'jsonql-utils/src/timestamp'\n// import { inArray } from 'jsonql-utils/src/generic'\nimport { USERDATA_TABLE } from '../utils'\nimport AuthCls from './auth-cls'\n\n// This class will only focus on the storage system\nexport default class JsonqlBaseClient extends AuthCls {\n // change the order of the interface in 1.4.10 to match up the top level\n constructor(fly, opts) {\n // change at 1.4.10 pass it directly without init it\n this.fly = fly;\n super(opts)\n }\n\n /**\n * construct the end point\n * @return {string} the end point to call\n */\n get jsonqlEndpoint() {\n const baseUrl = this.opts.hostname || ''\n return [baseUrl, this.opts.jsonqlPath].join('/')\n }\n\n /**\n * simple log\n */\n log(...args) {\n if (this.opts.debugOn === true) {\n Reflect.apply(console.info, console, args)\n }\n }\n\n}\n","// export interface\n// @public\nimport JsonqlBaseClient from './base-cls'\n\nexport default JsonqlBaseClient\n","// breaking out the inner methods generator in here\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { LOGOUT_NAME, LOGIN_NAME, KEY_WORD } from 'jsonql-constants'\nimport { chainFns } from 'jsonql-utils/src/chain-fns'\nimport { injectToFn } from 'jsonql-utils/src/obj-define-props'\n\n/**\n * generate authorisation specific methods\n * @param {object} jsonqlInstance instance of this\n * @param {string} name of method\n * @param {object} opts configuration\n * @param {object} contract to match\n * @return {function} for use\n */\nconst authMethodGenerator = (jsonqlInstance, name, opts, contract) => {\n return (...args) => {\n const params = contract.auth[name].params;\n const values = params.map((p, i) => args[i])\n const header = args[params.length] || {};\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [name, values, header])\n )\n .catch(finalCatch)\n }\n}\n\n/**\n * Break up the different type each - create query methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let query = {}\n for (let queryFn in contract.query) {\n // to keep it clean we use a param to id the auth method\n // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn;\n // generate the query method\n query = injectToFn(query, queryFn, function queryFnHandler(...args) {\n const params = contract.query[queryFn].params;\n const _args = params.map((param, i) => args[i])\n // debug('query', queryFn, _params);\n // @TODO this need to change to a different way to add an extra header\n const header = {}\n // @TODO validate against the type\n return validateAsync(_args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [queryFn, _args, header])\n )\n .catch(finalCatch)\n })\n }\n obj.query = query;\n // create an alias to the helloWorld method\n obj.helloWorld = query.helloWorld;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create mutation methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let mutation = {}\n // process the mutation, the reason the mutation has a fixed number of parameters\n // there is only the payload, and conditions parameters\n // plus a header at the end\n for (let mutationFn in contract.mutation) {\n mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header = {}) {\n const args = [payload, conditions];\n const params = contract.mutation[mutationFn].params;\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .mutation\n .apply(jsonqlInstance, [mutationFn, payload, conditions, header])\n )\n .catch(e => {\n console.error('--- mutation fn catch ---', e)\n return finalCatch(e)\n })\n })\n }\n obj.mutation = mutation;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create auth methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createAuthMethods = (obj, jsonqlInstance, ee, config, contract) => {\n if (config.enableAuth && contract.auth) {\n let auth = {} // v1.3.1 add back the auth prop name in contract\n const { loginHandlerName, logoutHandlerName } = config;\n if (contract.auth[loginHandlerName]) {\n // changing to the name the config specify\n auth[loginHandlerName] = function loginHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance))\n .then(token => {\n ee.$trigger(LOGIN_NAME, token)\n return token;\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) {\n auth[logoutHandlerName] = function logoutHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance))\n .then(r => {\n ee.$trigger(LOGOUT_NAME, r)\n return r;\n })\n }\n } else {\n auth[logoutHandlerName] = function logoutHandlerFn() {\n jsonqlInstance.postLogoutAction(KEY_WORD)\n ee.$trigger(LOGOUT_NAME, KEY_WORD)\n }\n }\n obj.auth = auth;\n }\n\n return obj;\n}\n\n/**\n * Here just generate the methods calls\n * @param {object} jsonqlInstance what it said\n * @param {object} ee event emitter\n * @param {object} config configuration\n * @param {object} contract the map\n * @return {object} with mapped methods\n */\nexport function methodsGenerator(jsonqlInstance, ee, config, contract) {\n let obj = {}\n const executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods)\n return executor(obj, jsonqlInstance, ee, config, contract)\n}\n","// Generate the resolver for developer to use\n\n// @TODO when enableAuth we need to add one extra check\n// before the resolver call make it to the core\n// which is checking the login state, if the developer\n// is calling a private method without logging in\n// then we should throw the JsonqlForbiddenError at this point\n// instead of making a round trip to the server\nimport { LOGOUT_NAME, ISSUER_NAME, KEY_WORD } from 'jsonql-constants'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\n\nimport { methodsGenerator } from './methods-generator'\n\n/**\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} config options\n * @param {object} contract the contract\n * @param {object} ee eventEmitter\n * @return {object} constructed functions call\n */\nconst generator = (jsonqlInstance, config, contract, ee) => {\n // V1.3.0 - now everything wrap inside this method\n let client = methodsGenerator(jsonqlInstance, ee, config, contract)\n // create the rest of the methods\n if (config.enableAuth) {\n /**\n * new method to allow retrieve the current login user data\n * @TODO allow to pass an id to switch to different userdata\n * @return {*} userdata\n */\n client.userdata = () => jsonqlInstance.jsonqlUserdata;\n // allow getting the token for valdiate agains the socket\n // if it's not require auth there is no point of calling getToken\n client.getToken = (idx = false) => jsonqlInstance.rawAuthToken(idx);\n // switch profile or read back what is the currenct index\n client.profileIndex = (idx = false) => {\n if (idx === false) {\n return jsonqlInstance.profileIndex\n }\n jsonqlInstance.profileIndex = idx\n }\n // new in 1.5.1 to return different profiles\n client.getProfiles = (idx = false) => jsonqlInstance.getProfiles(idx);\n }\n // this will pass to the ws-client if needed\n // client.eventEmitter = ee;\n // this will require a param\n if (config.exposeContract) {\n // 1.4.0 change from the get (raw) to the getContract cache and raw version\n client.getContract = () => jsonqlInstance.getContract()\n }\n // allow developer to access the store api\n if (config.exposeStore) {\n // @TODO in 1.5.2\n client.tmpSave = data => {}\n client.tmpGet = (key = false) => {}\n client.tmpDel = (key = false) => {}\n\n client.persistSave = data => {}\n client.persistGet = (key = false) => {}\n client.persistDel = (key = false) => {}\n }\n // this is for the ws to use later - but this could be dangerous because it's expose the internal\n client.eventEmitter = ee;\n client.version = '__VERSION__';\n // use this method then we can hook into the debugOn at the same time\n client.log = (...args) => Reflect.apply(jsonqlInstance.log, jsonqlInstance, ['[DEV DEBUG]'].concat(args))\n // output\n return client;\n}\n// export\nexport default generator\n","// all the client configuration options here\nimport {\n JSONQL_PATH,\n CONTENT_TYPE,\n BEARER,\n CLIENT_STORAGE_KEY,\n CLIENT_AUTH_KEY,\n CONTRACT_KEY_NAME,\n AUTH_HEADER,\n ISSUER_NAME,\n LOGOUT_NAME,\n BOOLEAN_TYPE,\n STRING_TYPE,\n NUMBER_TYPE,\n DEFAULT_HEADER\n} from 'jsonql-constants'\nimport { createConfig } from 'jsonql-params-validator'\nexport const constProps = {\n contract: false,\n MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong?\n CONTENT_TYPE,\n BEARER,\n AUTH_HEADER\n}\n\n// grab the localhost name and put into the hostname as default\nconst getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n return null\n }\n}\n\nexport const appProps = {\n\n hostname: createConfig(getHostName(), [STRING_TYPE]), // required the hostname\n jsonqlPath: createConfig(JSONQL_PATH, [STRING_TYPE]), // The path on the server\n\n loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]),\n logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]),\n // add to koa v1.3.0 - this might remove in the future\n enableJsonp: createConfig(false, [BOOLEAN_TYPE]),\n enableAuth: createConfig(false, [BOOLEAN_TYPE]),\n // enable useJwt by default @TODO replace with something else and remove them later\n useJwt: createConfig(true, [BOOLEAN_TYPE]),\n // when true then store infinity or pass a time in seconds then we check against\n // the token date of creation\n persistToken: createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE]),\n // the header\n // v1.2.0 we are using this option during the dev\n // so it won't save anything to the localstorage and fetch a new contract\n // whenever the browser reload\n useLocalstorage: createConfig(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage\n storageKey: createConfig(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage\n authKey: createConfig(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage\n contractExpired: createConfig(0, [NUMBER_TYPE]),// -1 always fetch contract,\n // 0 never expired,\n // > 0 then compare the timestamp with the current one to see if we need to get contract again\n // useful during development\n keepContract: createConfig(true, [BOOLEAN_TYPE]),\n exposeContract: createConfig(false, [BOOLEAN_TYPE]),\n exposeStore: createConfig(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn \n // @1.2.1 new option for the contract-console to fetch the contract with description\n showContractDesc: createConfig(false, [BOOLEAN_TYPE]),\n contractKey: createConfig(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this\n contractKeyName: createConfig(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs\n enableTimeout: createConfig(false, [BOOLEAN_TYPE]), // @TODO\n timeout: createConfig(5000, [NUMBER_TYPE]), // 5 seconds\n returnInstance: createConfig(false, [BOOLEAN_TYPE]),\n allowReturnRawToken: createConfig(false, [BOOLEAN_TYPE]),\n debugOn: createConfig(false, [BOOLEAN_TYPE])\n}\n","// we must ensure the user passing the correct options\n// therefore we need to validate against the properties as well\n\nimport { appProps, constProps } from './base-options'\nimport { checkConfigAsync } from 'jsonql-params-validator'\n\nexport default function checkOptionsAsync(config) {\n let { contract } = config;\n return checkConfigAsync(config, appProps, constProps)\n .then(opts => {\n opts.contract = contract;\n return opts;\n })\n}\n","// export interface\nimport checkOptionsAsyncLocal from './check-options-async'\nimport checkOptionsLocal from './check-options'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport { objHasProp } from 'jsonql-utils/src/obj-define-props'\n/**\n * 1.5.0 overload the orginal functions to pass over the check\n */\nfunction checkOptionsAsync(config) {\n return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsyncLocal(config)\n}\n\n// sync version without needing the promise\nfunction checkOptions(config) {\n return objHasProp(config, CHECKED_KEY) ? config : checkOptionsLocal(config)\n}\n\nexport {\n checkOptionsAsync,\n checkOptions\n}\n","// this is new for the flyio and normalize the name from now on\nimport JsonqlBaseClient from './base'\nimport generator from './core/jsonql-api-generator'\nimport { checkOptionsAsync } from './options'\nimport { getContractFromConfig } from './utils'\n\n/**\n * Main interface for jsonql fetch api\n * @param {object} ee EventEmitter\n * @param {object} config\n * @param {object} fly this is really pain in the backside ... long story\n * @return {object} jsonql client\n */\nexport default function(ee, config = {}, fly) {\n return checkOptionsAsync(config)\n .then(opts => (\n {\n baseClient: new JsonqlBaseClient(fly, opts),\n opts: opts\n }\n ))\n .then( ({baseClient, opts}) => (\n getContractFromConfig(baseClient, opts.contract)\n .then(contract => generator(baseClient, opts, contract, ee))\n )\n )\n}\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n\nexport default class SuspendClass {\n\n constructor() {\n // suspend, release and queue\n this.__suspend__ = null;\n this.queueStore = new Set()\n /*\n this.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n })\n */\n }\n\n /**\n * setter to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n set $suspend(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend__;\n this.__suspend__ = value;\n this.logger('($suspend)', `Change from ${lastValue} --> ${value}`)\n if (lastValue === true && value === false) {\n setTimeout(() => {\n this.release()\n }, 1)\n }\n } else {\n throw new Error(`$suspend only accept Boolean value!`)\n }\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {any} value\n * @return {Boolean} true when added or false when it's not\n */\n $queue(...args) {\n if (this.__suspend__ === true) {\n this.logger('($queue)', 'added to $queue', args)\n // there shouldn't be any duplicate ...\n this.queueStore.add(args)\n }\n return this.__suspend__;\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size;\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n release() {\n let size = this.queueStore.size\n this.logger('(release)', `Release was called ${size}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('queue', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport genHaskKey from './hash-code'\nimport SuspendClass from './suspend'\n\nexport default class NbEventServiceBase extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger;\n }\n this.keep = config.keep;\n // for the $done setter\n this.result = config.keep ? [] : null;\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (typeof e !== 'string') {\n this.logger('(validateEvt)', e)\n throw new Error(`event name must be string type!`)\n }\n })\n return true;\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n return true;\n }\n }\n throw new Error(`callback required to be function type!`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n const types = ['on', 'only', 'once', 'onlyOnce']\n return !!types.filter(t => type === t).length;\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run)', callback, payload, ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName]; // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger('(takeFromStore)', `has ${evt}`, content)\n store.delete(evt)\n return content;\n }\n return false;\n }\n throw new Error(`${storeName} is not supported!`)\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n let fnSet;\n if (store.has(evt)) {\n this.logger('(addToStore)', `${evt} existed`)\n fnSet = store.get(evt)\n } else {\n this.logger('(addToStore)', `create new Set for ${evt}`)\n // this is new\n fnSet = new Set()\n }\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args;\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger('(addToStore)', `insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(l => {\n let [hash,] = l;\n if (hash === args[0]) {\n return true;\n }\n return false;\n }).length;\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true;\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list;\n return type !== t;\n }).length;\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n this.logger('(checkTypeInLazyStore)', store)\n if (store) {\n return !!Array\n .from(store)\n .filter(l => {\n let [,,t] = l;\n return t !== type;\n }).length\n }\n return false;\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger('(addToNormalStore)', evt, type, 'try to add to normal store')\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n this.logger('(addToNormalStore)', `${type} can add to ${evt} normal store`)\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store;\n return size;\n }\n return false;\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store;\n return size;\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg];\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n return genHaskKey(fn.toString()) + '';\n }\n}\n","// The top level\nimport NbStoreService from './store-service'\n// export\nexport default class EventService extends NbStoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on';\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger('($on)', `${evt} callback is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger('($on)', `${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0;\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($on)`, `call run on ${evt}`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n return size;\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n const type = 'once';\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (lazyStoreContent === false) {\n this.logger('($once)', `${evt} not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, type, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger('($once)', `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'only';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($only)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($only)', `${evt} found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( l => {\n const [ payload, ctx, t ] = l;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($only)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n })\n }\n return added;\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD added in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'onlyOnce';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== 'onlyOnce') {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($onlyOnce)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added;\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {}\n */\n $replace(evt, callback, context = null, type = 'on') {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n this.logger(`($replace)`, evt, callback)\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0;\n // first check the normal store\n let nStore = this.normalStore;\n this.logger('($trigger)', 'normalStore', nStore)\n if (nStore.has(evt)) {\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n this.logger('($trigger)', evt, 'found; add to queue: ', added)\n if (added === true) {\n this.logger('($trigger)', evt, 'not executed. Exit now.')\n return false; // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length;\n let hasOnce = false;\n let hasOnly = false;\n for (let i=0; i < ctn; ++i) {\n ++found;\n // this.logger('found', found)\n let [ _, callback, ctx, type ] = nSet[i]\n this.logger(`($trigger)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n if (type === 'once' || type === 'onlyOnce') {\n hasOnce = true;\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found;\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found;\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter around\n * @param {string} evt event name\n * @param {*} params pass to the callback\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, params, type = false, context = null) {\n let args = [evt, params, context, type]\n return Reflect.apply(this.$trigger, this, args)\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n let found = false;\n stores.forEach(store => {\n if (store.has(evt)) {\n found = true;\n this.logger('($off)', evt)\n store.delete(evt)\n }\n })\n return found;\n }\n\n /**\n * return all the listener from the event\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n this.validateEvt(evt)\n let store = this.normalStore;\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l;\n }\n let [key, callback, ] = l;\n return callback;\n })\n }\n return false;\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done)', 'value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value;\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n if (this.keep) {\n this.logger('(get $done)', this.result)\n return this.result[this.result.length - 1]\n }\n return this.result;\n }\n\n\n}\n","// default\nimport NBEventService from './src/event-service'\n\nexport default NBEventService\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// output\nexport default function(debugOn) {\n let logger = debugOn ? (...args) => {\n args.unshift('[NBS]')\n console.log.apply(null, args)\n }: undefined;\n return new NBEventService({ logger })\n}\n","// main export interface\nimport {\n jsonqlAsync,\n ee as getEventEmitter\n} from './src'\n/**\n * When pass a static contract then it return a static interface\n * otherwise it will become the async interface\n * @param {object} fly the http engine - already init object not the class!\n * @param {object} config configuration\n * @return {object} jsonqlClient\n */\nexport default function jsonqlClient(fly, config) {\n const ee = getEventEmitter(config.debugOn)\n return jsonqlAsync(ee, config, fly)\n}\n","// this one will bring the fly.js in\n// also the built jsonql-client.umd.js together\n// init it @TODO placeholder this Fly import and switch using the NODE_ENV\n// because we are going to create one for wechat and one for node\n\nimport Fly from 'flyio/dist/npm/fly'\nimport jsonqlClient from './index'\n\nexport default function(config = {}) {\n return jsonqlClient(new Fly(), config)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/packages/http-client/package.json b/packages/http-client/package.json index ba268f61..4b047b50 100755 --- a/packages/http-client/package.json +++ b/packages/http-client/package.json @@ -68,7 +68,7 @@ "jsonql-errors": "^1.1.8", "jsonql-jwt": "^1.3.6", "jsonql-params-validator": "^1.5.0", - "jsonql-utils": "^0.9.0", + "jsonql-utils": "^0.9.2", "lodash-es": "^4.17.15", "nb-event-service": "^1.8.5", "store": "^2.0.12" @@ -79,7 +79,7 @@ "debug": "^4.1.1", "esm": "^3.2.25", "glob": "^7.1.6", - "jsonql-koa": "^1.4.22", + "jsonql-koa": "^1.5.0", "koa-favicon": "^2.0.1", "nyc": "^14.1.1", "promise-polyfill": "8.1.3", diff --git a/packages/http-client/src/base/http-cls.js b/packages/http-client/src/base/http-cls.js index ac56e1e3..4604534b 100644 --- a/packages/http-client/src/base/http-cls.js +++ b/packages/http-client/src/base/http-cls.js @@ -11,7 +11,8 @@ import { isObject, isString } from 'jsonql-params-validator' import { JsonqlValidationError, JsonqlServerError, - clientErrorsHandler + JsonqlError, + // clientErrorsHandler } from 'jsonql-errors' import { API_REQUEST_METHODS, @@ -20,6 +21,35 @@ import { SHOW_CONTRACT_DESC_PARAM } from 'jsonql-constants' +// @DEBUG +import * as errors from 'jsonql-errors' +import { isObjectHasKey } from 'jsonql-utils/src/generic' +/** + * It will ONLY have our own jsonql specific implement check + * @param {object} result the server return result + * @return {object} this will just throw error + */ +function clientErrorsHandler(result) { + if (isObjectHasKey(result, 'error')) { + const { error } = result; + const { className, name } = error; + const errorName = className || name; + // just throw the whole thing back + const msg = error.message || NO_ERROR_MSG; + const detail = error.detail || error; + console.info('--- errorName ---', errorName, errors) + + if (errorName && errors[errorName]) { + throw new errors[className](msg, detail) + } + throw new JsonqlError(msg, detail) + } + // pass through to the next + return result; +} + + + // extract the one we need const [ POST, PUT ] = API_REQUEST_METHODS diff --git a/packages/http-client/src/core/methods-generator.js b/packages/http-client/src/core/methods-generator.js index dd6a0df3..1fa16aa4 100644 --- a/packages/http-client/src/core/methods-generator.js +++ b/packages/http-client/src/core/methods-generator.js @@ -91,7 +91,10 @@ const createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => { .mutation .apply(jsonqlInstance, [mutationFn, payload, conditions, header]) ) - .catch(finalCatch) + .catch(e => { + console.error('--- mutation fn catch ---', e) + return finalCatch(e) + }) }) } obj.mutation = mutation; diff --git a/packages/http-client/static.js b/packages/http-client/static.js index 3a6f3e04..d99694af 100644 --- a/packages/http-client/static.js +++ b/packages/http-client/static.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClientStatic=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b="onResult",_="onError",m=Array.isArray,w="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},j="object"==typeof w&&w&&w.Object===Object&&w,S="object"==typeof self&&self&&self.Object===Object&&self,O=j||S||Function("return this")(),k=O.Symbol,A=Object.prototype,E=A.hasOwnProperty,T=A.toString,x=k?k.toStringTag:void 0;var P=Object.prototype.toString;var q="[object Null]",C="[object Undefined]",$=k?k.toStringTag:void 0;function z(t){return null==t?void 0===t?C:q:$&&$ in Object(t)?function(t){var e=E.call(t,x),r=t[x];try{t[x]=void 0;var n=!0}catch(t){}var o=T.call(t);return n&&(e?t[x]=r:delete t[x]),o}(t):function(t){return P.call(t)}(t)}function N(t,e){return function(r){return t(e(r))}}var M=N(Object.getPrototypeOf,Object);function R(t){return null!=t&&"object"==typeof t}var I="[object Object]",F=Function.prototype,J=Object.prototype,U=F.toString,H=J.hasOwnProperty,L=U.call(Object);function D(t){if(!R(t)||z(t)!=I)return!1;var e=M(t);if(null===e)return!0;var r=H.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&U.call(r)==L}var K=function(t){return m(t)?t:[t]},B=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},V=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},G=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),W=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),Y=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),Q=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),X=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),Z=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),rt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),nt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),it=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),at=Object.freeze({__proto__:null,Jsonql406Error:G,Jsonql500Error:W,JsonqlAuthorisationError:Y,JsonqlContractAuthError:Q,JsonqlResolverAppError:X,JsonqlResolverNotFoundError:Z,JsonqlEnumError:tt,JsonqlTypeError:et,JsonqlCheckerError:rt,JsonqlValidationError:nt,JsonqlError:ot,JsonqlServerError:it}),ut=ot,ct=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function st(t){if(ct(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&at[o])throw new at[r](i,a);throw new ut(i,a)}return t}function ft(t){if(Array.isArray(t))throw new nt("",t);var e=t.message||y,r=t.detail||t;switch(!0){case t instanceof G:throw new G(e,r);case t instanceof W:throw new W(e,r);case t instanceof Y:throw new Y(e,r);case t instanceof Q:throw new Q(e,r);case t instanceof X:throw new X(e,r);case t instanceof Z:throw new Z(e,r);case t instanceof tt:throw new tt(e,r);case t instanceof et:throw new et(e,r);case t instanceof rt:throw new rt(e,r);case t instanceof nt:throw new nt(e,r);case t instanceof it:throw new it(e,r);default:throw new ot(e,r)}}function lt(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&mt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var Mt=function(t){return!!m(t)||null!=t&&""!==Nt(t)},Rt="[object Number]";function It(t){return function(t){return"number"==typeof t||R(t)&&z(t)==Rt}(t)&&t!=+t}var Ft="[object String]";function Jt(t){return"string"==typeof t||!m(t)&&R(t)&&z(t)==Ft}var Ut=function(t){return!Jt(t)&&!It(parseFloat(t))},Ht=function(t){return""!==Nt(t)&&Jt(t)},Lt=function(t){return null!=t&&"boolean"==typeof t},Dt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==Nt(t)&&(!1===e||!0===e&&null!==t)},Kt=s,Bt=f,Vt=l,Gt=p,Wt=h,Yt=d,Qt="continue",Xt=function(t){switch(t){case"number":return Ut;case"string":return Ht;case"boolean":return Lt;default:return Dt}},Zt=function(t,e){return void 0===e&&(e=""),!!m(t)&&(""===e||""===Nt(e)||!(t.filter((function(t){return!Xt(e)(t)})).length>0))},te=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ee=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!Xt(e)(t)})).length)})).length:e.length>e.filter((function(t){return!Zt(r,t)})).length};var re,ne=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[re?a:++n];if(!1===e(o[u],u,o))break}return t};var oe="[object Arguments]";function ie(t){return R(t)&&z(t)==oe}var ae=Object.prototype,ue=ae.hasOwnProperty,ce=ae.propertyIsEnumerable,se=ie(function(){return arguments}())?ie:function(t){return R(t)&&ue.call(t,"callee")&&!ce.call(t,"callee")};var fe="object"==typeof exports&&exports&&!exports.nodeType&&exports,le=fe&&"object"==typeof module&&module&&!module.nodeType&&module,pe=le&&le.exports===fe?O.Buffer:void 0,he=(pe?pe.isBuffer:void 0)||function(){return!1},de=9007199254740991,ve=/^(?:0|[1-9]\d*)$/;function ge(t,e){var r=typeof t;return!!(e=null==e?de:e)&&("number"==r||"symbol"!=r&&ve.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=ye}var _e={};_e["[object Float32Array]"]=_e["[object Float64Array]"]=_e["[object Int8Array]"]=_e["[object Int16Array]"]=_e["[object Int32Array]"]=_e["[object Uint8Array]"]=_e["[object Uint8ClampedArray]"]=_e["[object Uint16Array]"]=_e["[object Uint32Array]"]=!0,_e["[object Arguments]"]=_e["[object Array]"]=_e["[object ArrayBuffer]"]=_e["[object Boolean]"]=_e["[object DataView]"]=_e["[object Date]"]=_e["[object Error]"]=_e["[object Function]"]=_e["[object Map]"]=_e["[object Number]"]=_e["[object Object]"]=_e["[object RegExp]"]=_e["[object Set]"]=_e["[object String]"]=_e["[object WeakMap]"]=!1;var me,we="object"==typeof exports&&exports&&!exports.nodeType&&exports,je=we&&"object"==typeof module&&module&&!module.nodeType&&module,Se=je&&je.exports===we&&j.process,Oe=function(){try{var t=je&&je.require&&je.require("util").types;return t||Se&&Se.binding&&Se.binding("util")}catch(t){}}(),ke=Oe&&Oe.isTypedArray,Ae=ke?(me=ke,function(t){return me(t)}):function(t){return R(t)&&be(t.length)&&!!_e[z(t)]},Ee=Object.prototype.hasOwnProperty;function Te(t,e){var r=m(t),n=!r&&se(t),o=!r&&!n&&he(t),i=!r&&!n&&!o&&Ae(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},Ke.prototype.set=function(t,e){var r=this.__data__,n=Le(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var Be,Ve=O["__core-js_shared__"],Ge=(Be=/[^.]+$/.exec(Ve&&Ve.keys&&Ve.keys.IE_PROTO||""))?"Symbol(src)_1."+Be:"";var We=Function.prototype.toString;function Ye(t){if(null!=t){try{return We.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Qe=/^\[object .+?Constructor\]$/,Xe=Function.prototype,Ze=Object.prototype,tr=Xe.toString,er=Ze.hasOwnProperty,rr=RegExp("^"+tr.call(er).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function nr(t){return!(!$e(t)||function(t){return!!Ge&&Ge in t}(t))&&(Ie(t)?rr:Qe).test(Ye(t))}function or(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return nr(r)?r:void 0}var ir=or(O,"Map"),ar=or(Object,"create");var ur="__lodash_hash_undefined__",cr=Object.prototype.hasOwnProperty;var sr=Object.prototype.hasOwnProperty;var fr="__lodash_hash_undefined__";function lr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&mr?new yr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=te(t))?!ee({arg:r},e):!Xt(t)(r))})).length)})).length}return!1},Un=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Jn,null,a);case"array"===t:return!Zt(e.arg);case!1!==(r=te(t)):return!ee(e,r);default:return!Xt(t)(e.arg)}},Hn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Ln=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!Zt(e))throw new ot("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!Zt(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==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Hn(t,a):t,index:r,param:a,optional:i}}));default:throw new ot("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Mt(e)&&!(r.type.length>r.type.filter((function(e){return Un(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Un(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Dn=function(){try{var t=or(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function Kn(t,e,r){"__proto__"==e&&Dn?Dn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function Bn(t,e,r){(void 0===r||He(t[e],r))&&(void 0!==r||e in t)||Kn(t,e,r)}var Vn="object"==typeof exports&&exports&&!exports.nodeType&&exports,Gn=Vn&&"object"==typeof module&&module&&!module.nodeType&&module,Wn=Gn&&Gn.exports===Vn?O.Buffer:void 0,Yn=Wn?Wn.allocUnsafe:void 0;function Qn(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new jr(n).set(new jr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var Xn=Object.create,Zn=function(){function t(){}return function(e){if(!$e(e))return{};if(Xn)return Xn(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function to(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var eo=Object.prototype.hasOwnProperty;function ro(t,e,r){var n=t[e];eo.call(t,e)&&He(n,r)&&(void 0!==r||e in t)||Kn(t,e,r)}var no=Object.prototype.hasOwnProperty;function oo(t){if(!$e(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Pe(t),r=[];for(var n in t)("constructor"!=n||!e&&no.call(t,n))&&r.push(n);return r}function io(t){return Fe(t)?Te(t,!0):oo(t)}function ao(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=po)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(lo);function yo(t,e){return go(function(t,e,r){return e=fo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=fo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=bo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!$e(r))return!1;var n=typeof e;return!!("number"==n?Fe(r)&&ge(e,r.length):"string"==n&&e in r)&&He(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,K(t))}),Reflect.apply(t,null,r))}};function Lo(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function Do(t,e,r,n){void 0===n&&(n=!1);var o=Lo(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var Ko=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return Fo(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch(ft)}},Bo=function(t,e,r,n,o){var i={},a=function(t){i=Do(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return Fo(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch(ft)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},Vo=function(t,e,r,n,o){var i={},a=function(t){i=Do(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return Fo(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch(ft)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Go=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Ko(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Ko(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var Wo=function(t,e){return function(r){for(var n=[],o=arguments.length-1;o-- >0;)n[o]=arguments[o+1];return new Promise((function(o,i){t.$only(V(e,r,b),o),t.$only(V(e,r,_),i),t.$trigger(e,{resolverName:r,args:n})}))}},Yo=function(t,e,r){var n=t.$queues,o=r.debugOn;o&&console.info("(validateRegisteredEvents)","storedEvt",n),n.forEach((function(t){var r=t[0],n=t[1].resolverName;if(o&&console.info("(validateRegisteredEvents)",r,n),!e[r][n])throw new Error(r+"."+n+" not existed in contract!")}))};function Qo(t,e,r,n){var o=function(t,e,r,n){return Ho(Bo,Vo,Go)({},t,e,r,n)}(t,e,r,n);Yo(e,n,r);var i=function(t){e.$only(t,(function(r){var n=r.resolverName,i=r.args;o[t][n]?Reflect.apply(o[t][n],null,i).then((function(r){e.$trigger(V(t,n,b),r)})).catch((function(r){e.$trigger(V(t,n,_),r)})):console.error(n+" is not defined in the contract!")}))};for(var a in o)i(a);setTimeout((function(){e.$suspend=!1}),1)}var Xo=function(t,e,r,n){n.$suspend=!0,r.then((function(r){Qo(t,n,e,r)}));var o={query:Wo(n,"query"),mutation:Wo(n,"mutation"),auth:Wo(n,"auth"),getToken:function(){return t.rawAuthToken}};return e.exposeContract&&(o.getContract=function(){return t.get()}),e.enableAuth&&(o.userdata=function(){return t.userdata}),o.version="1.5.1",o};function Zo(t){return!!function(t){return D(t)&&(B(t,r)||B(t,n)||B(t,o))}(t)&&t}function ti(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var ei=function(t,e){return void 0===e&&(e={}),Zo(e)?Promise.resolve(e):t.getContract()},ri="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function ni(t){this.message=t}ni.prototype=new Error,ni.prototype.name="InvalidCharacterError";var oi="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new ni("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=ri.indexOf(n);return a};var ii=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(oi(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return oi(e)}};function ai(t){this.message=t}ai.prototype=new Error,ai.prototype.name="InvalidTokenError";var ui=function(t,e){if("string"!=typeof t)throw new ai("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(ii(t.split(".")[r]))}catch(t){throw new ai("Invalid token specified: "+t.message)}},ci=ai;ui.InvalidTokenError=ci;var si,fi,li,pi,hi,di,vi,gi,yi,bi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function _i(t){if(Ht(t))return function(t){var e=t.iat||bi(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new ot("Token has expired on "+r,t)}return t}(ui(t));throw new ot("Token must be a string!")}Jo("HS256",["string"]),Jo(!1,["boolean","number","string"],((si={})[d]="exp",si[f]=!0,si)),Jo(!1,["boolean","number","string"],((fi={})[d]="nbf",fi[f]=!0,fi)),Jo(!1,["boolean","string"],((li={})[d]="iss",li[f]=!0,li)),Jo(!1,["boolean","string"],((pi={})[d]="sub",pi[f]=!0,pi)),Jo(!1,["boolean","string"],((hi={})[d]="iss",hi[f]=!0,hi)),Jo(!1,["boolean"],((di={})[f]=!0,di)),Jo(!1,["boolean","string"],((vi={})[f]=!0,vi)),Jo(!1,["boolean","string"],((gi={})[f]=!0,gi)),Jo(!1,["boolean"],((yi={})[f]=!0,yi));var mi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},wi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var ji=Object.assign?Object.assign:function(t,e,r,n){for(var o=arguments,i=1;i=0;e--){var r=Di().key(e);t(Ki(r),r)}},remove:function(t){return Di().removeItem(t)},clearAll:function(){return Di().clear()}};function Di(){return Hi.localStorage}function Ki(t){return Di().getItem(t)}var Bi=Ai.trim,Vi={name:"cookieStorage",read:function(t){if(!t||!Qi(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Gi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Gi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Wi,remove:Yi,clearAll:function(){Wi((function(t,e){Yi(e)}))}},Gi=Ai.Global.document;function Wi(t){for(var e=Gi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Bi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Yi(t){t&&Qi(t)&&(Gi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Qi(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Gi.cookie)}var Xi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Zi=Ai.bind,ta=Ai.each,ea=Ai.create,ra=Ai.slice,na=function(){var t=ea(oa,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Zi(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Zi(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),ta(r,(function(e,r){t.fire(r,void 0,e)}))}}};var oa={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Zi(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=ra(arguments,1);ta(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},ia=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),aa=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=ia.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=ia.compress(this._serialize(r));t(e,n)}}};var ua=[Li,Vi],ca=[Xi,na,aa],sa=Fi.createStore(ua,ca),fa=Ai.Global;function la(){return fa.sessionStorage}function pa(t){return la().getItem(t)}var ha=[{name:"sessionStorage",read:pa,write:function(t,e){return la().setItem(t,e)},each:function(t){for(var e=la().length-1;e>=0;e--){var r=la().key(e);t(pa(r),r)}},remove:function(t){return la().removeItem(t)},clearAll:function(){return la().clear()}},Vi],da=[Xi,aa],va=Fi.createStore(ha,da),ga=sa,ya=va,ba=function(t){var e;return(e={}).args=t,e};function _a(t,e){var r;return(r={})[t]=e,r[u]=[mi()],r}var ma=function(t){return B(t,"data")&&!B(t,"error")?t.data:t},wa=function(t){this.opts=t,this.instanceKey=ti(this.opts.hostname)+"",this.localStore=ga,this.sessionStore=ya},ja={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};wa.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?_o({},o,e):e,r))},wa.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},wa.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},wa.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},ja.lset.set=function(t){return this.__setMethod("localStore",t)},ja.lget.get=function(){return this.__getMethod("localStore")},wa.prototype.ldel=function(t){return this.__delMethod("localStore",t)},wa.prototype.lclear=function(){return this.__clearMethod("localStore")},ja.sset.set=function(t){return this.__setMethod("sessionStore",t)},ja.sget.get=function(){return this.__getMethod("sessionStore")},wa.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},wa.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(wa.prototype,ja);var Sa=c[0],Oa=c[1],ka=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];!0===this.opts.debugOn&&Reflect.apply(console.info,console,t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=_i)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(Io(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new nt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&Io(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!Zo(t))throw new nt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=Zo(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=_o({},{_cb:mi()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=_o({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=_o({},{method:Sa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return ma(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=Ro(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ma(o)}),(function(t){throw e.cleanUp(),console.error(t),new it("Server side error",t)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?_o({},e,this.getAuthHeader(),this.extraHeader):_o({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=_o({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(st).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(t){throw console.error("getRemoteContract err",t),new it("getRemoteContract",t)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Jt(t)&&m(e)){var n=ba(e);return!0===r?n:_a(t,n)}throw new nt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(st)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Jt(t))return _a(t,o);throw new nt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:Oa}).then(st)},Object.defineProperties(r.prototype,n),r}(wa)))),Aa={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Ea={hostname:Jo(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:Jo("jsonql",["string"]),loginHandlerName:Jo("login",["string"]),logoutHandlerName:Jo("logout",["string"]),enableJsonp:Jo(!1,["boolean"]),enableAuth:Jo(!1,["boolean"]),useJwt:Jo(!0,["boolean"]),persistToken:Jo(!1,["boolean","number"]),useLocalstorage:Jo(!0,["boolean"]),storageKey:Jo("jsonqlstore",["string"]),authKey:Jo("jsonqlauthkey",["string"]),contractExpired:Jo(0,["number"]),keepContract:Jo(!0,["boolean"]),exposeContract:Jo(!1,["boolean"]),exposeStore:Jo(!1,["boolean"]),showContractDesc:Jo(!1,["boolean"]),contractKey:Jo(!1,["boolean"]),contractKeyName:Jo("X-JSONQL-CV-KEY",["string"]),enableTimeout:Jo(!1,["boolean"]),timeout:Jo(5e3,["number"]),returnInstance:Jo(!1,["boolean"]),allowReturnRawToken:Jo(!1,["boolean"]),debugOn:Jo(!1,["boolean"])};function Ta(t){return Lo(t,v)?t:function(t){return Uo(t,Ea,Aa)}(t)}var xa=new WeakMap,Pa=new WeakMap,qa=function(){this.__suspend__=null,this.queueStore=new Set},Ca={$suspend:{configurable:!0},$queues:{configurable:!0}};Ca.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},qa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ca.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},qa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(qa.prototype,Ca);var $a=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){xa.set(this,t)},r.normalStore.get=function(){return xa.get(this)},r.lazyStore.set=function(t){Pa.set(this,t)},r.lazyStore.get=function(){return Pa.get(this)},e.prototype.hashFnToKey=function(t){return ti(t.toString())+""},Object.defineProperties(e.prototype,r),e}(qa));return function(t,e){void 0===e&&(e={});var r,n=e.contract,o=Ta(e),i=new ka(t,o),a=ei(i,n),u=(r=o.debugOn,new $a({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),c=Xo(i,o,a,u);return c.eventEmitter=u,c}})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClientStatic=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b="onResult",_="onError",m=Array.isArray,w="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},j="object"==typeof w&&w&&w.Object===Object&&w,S="object"==typeof self&&self&&self.Object===Object&&self,O=j||S||Function("return this")(),k=O.Symbol,A=Object.prototype,E=A.hasOwnProperty,T=A.toString,x=k?k.toStringTag:void 0;var P=Object.prototype.toString;var q="[object Null]",C="[object Undefined]",$=k?k.toStringTag:void 0;function z(t){return null==t?void 0===t?C:q:$&&$ in Object(t)?function(t){var e=E.call(t,x),r=t[x];try{t[x]=void 0;var n=!0}catch(t){}var o=T.call(t);return n&&(e?t[x]=r:delete t[x]),o}(t):function(t){return P.call(t)}(t)}function N(t,e){return function(r){return t(e(r))}}var M=N(Object.getPrototypeOf,Object);function R(t){return null!=t&&"object"==typeof t}var I="[object Object]",F=Function.prototype,J=Object.prototype,U=F.toString,H=J.hasOwnProperty,L=U.call(Object);function D(t){if(!R(t)||z(t)!=I)return!1;var e=M(t);if(null===e)return!0;var r=H.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&U.call(r)==L}function K(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&tt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var gt=function(t){return m(t)?t:[t]},yt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},bt=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},_t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),mt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),xt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),Pt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),qt=Object.freeze({__proto__:null,Jsonql406Error:_t,Jsonql500Error:mt,JsonqlAuthorisationError:wt,JsonqlContractAuthError:jt,JsonqlResolverAppError:St,JsonqlResolverNotFoundError:Ot,JsonqlEnumError:kt,JsonqlTypeError:At,JsonqlCheckerError:Et,JsonqlValidationError:Tt,JsonqlError:xt,JsonqlServerError:Pt}),Ct=xt,$t=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function zt(t){if($t(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&qt[o])throw new qt[r](i,a);throw new Ct(i,a)}return t}function Nt(t){if(Array.isArray(t))throw new Tt("",t);var e=t.message||y,r=t.detail||t;switch(!0){case t instanceof _t:throw new _t(e,r);case t instanceof mt:throw new mt(e,r);case t instanceof wt:throw new wt(e,r);case t instanceof jt:throw new jt(e,r);case t instanceof St:throw new St(e,r);case t instanceof Ot:throw new Ot(e,r);case t instanceof kt:throw new kt(e,r);case t instanceof At:throw new At(e,r);case t instanceof Et:throw new Et(e,r);case t instanceof Tt:throw new Tt(e,r);case t instanceof Pt:throw new Pt(e,r);default:throw new xt(e,r)}}var Mt=function(t){return!!m(t)||null!=t&&""!==vt(t)},Rt="[object Number]";function It(t){return function(t){return"number"==typeof t||R(t)&&z(t)==Rt}(t)&&t!=+t}var Ft="[object String]";function Jt(t){return"string"==typeof t||!m(t)&&R(t)&&z(t)==Ft}var Ut=function(t){return!Jt(t)&&!It(parseFloat(t))},Ht=function(t){return""!==vt(t)&&Jt(t)},Lt=function(t){return null!=t&&"boolean"==typeof t},Dt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==vt(t)&&(!1===e||!0===e&&null!==t)},Kt=s,Bt=f,Vt=l,Gt=p,Wt=h,Yt=d,Qt="continue",Xt=function(t){switch(t){case"number":return Ut;case"string":return Ht;case"boolean":return Lt;default:return Dt}},Zt=function(t,e){return void 0===e&&(e=""),!!m(t)&&(""===e||""===vt(e)||!(t.filter((function(t){return!Xt(e)(t)})).length>0))},te=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ee=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!Xt(e)(t)})).length)})).length:e.length>e.filter((function(t){return!Zt(r,t)})).length};var re,ne=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[re?a:++n];if(!1===e(o[u],u,o))break}return t};var oe="[object Arguments]";function ie(t){return R(t)&&z(t)==oe}var ae=Object.prototype,ue=ae.hasOwnProperty,ce=ae.propertyIsEnumerable,se=ie(function(){return arguments}())?ie:function(t){return R(t)&&ue.call(t,"callee")&&!ce.call(t,"callee")};var fe="object"==typeof exports&&exports&&!exports.nodeType&&exports,le=fe&&"object"==typeof module&&module&&!module.nodeType&&module,pe=le&&le.exports===fe?O.Buffer:void 0,he=(pe?pe.isBuffer:void 0)||function(){return!1},de=9007199254740991,ve=/^(?:0|[1-9]\d*)$/;function ge(t,e){var r=typeof t;return!!(e=null==e?de:e)&&("number"==r||"symbol"!=r&&ve.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=ye}var _e={};_e["[object Float32Array]"]=_e["[object Float64Array]"]=_e["[object Int8Array]"]=_e["[object Int16Array]"]=_e["[object Int32Array]"]=_e["[object Uint8Array]"]=_e["[object Uint8ClampedArray]"]=_e["[object Uint16Array]"]=_e["[object Uint32Array]"]=!0,_e["[object Arguments]"]=_e["[object Array]"]=_e["[object ArrayBuffer]"]=_e["[object Boolean]"]=_e["[object DataView]"]=_e["[object Date]"]=_e["[object Error]"]=_e["[object Function]"]=_e["[object Map]"]=_e["[object Number]"]=_e["[object Object]"]=_e["[object RegExp]"]=_e["[object Set]"]=_e["[object String]"]=_e["[object WeakMap]"]=!1;var me,we="object"==typeof exports&&exports&&!exports.nodeType&&exports,je=we&&"object"==typeof module&&module&&!module.nodeType&&module,Se=je&&je.exports===we&&j.process,Oe=function(){try{var t=je&&je.require&&je.require("util").types;return t||Se&&Se.binding&&Se.binding("util")}catch(t){}}(),ke=Oe&&Oe.isTypedArray,Ae=ke?(me=ke,function(t){return me(t)}):function(t){return R(t)&&be(t.length)&&!!_e[z(t)]},Ee=Object.prototype.hasOwnProperty;function Te(t,e){var r=m(t),n=!r&&se(t),o=!r&&!n&&he(t),i=!r&&!n&&!o&&Ae(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},Ke.prototype.set=function(t,e){var r=this.__data__,n=Le(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var Be,Ve=O["__core-js_shared__"],Ge=(Be=/[^.]+$/.exec(Ve&&Ve.keys&&Ve.keys.IE_PROTO||""))?"Symbol(src)_1."+Be:"";var We=Function.prototype.toString;function Ye(t){if(null!=t){try{return We.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Qe=/^\[object .+?Constructor\]$/,Xe=Function.prototype,Ze=Object.prototype,tr=Xe.toString,er=Ze.hasOwnProperty,rr=RegExp("^"+tr.call(er).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function nr(t){return!(!$e(t)||function(t){return!!Ge&&Ge in t}(t))&&(Ie(t)?rr:Qe).test(Ye(t))}function or(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return nr(r)?r:void 0}var ir=or(O,"Map"),ar=or(Object,"create");var ur="__lodash_hash_undefined__",cr=Object.prototype.hasOwnProperty;var sr=Object.prototype.hasOwnProperty;var fr="__lodash_hash_undefined__";function lr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&mr?new yr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=te(t))?!ee({arg:r},e):!Xt(t)(r))})).length)})).length}return!1},Un=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Jn,null,a);case"array"===t:return!Zt(e.arg);case!1!==(r=te(t)):return!ee(e,r);default:return!Xt(t)(e.arg)}},Hn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Ln=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!Zt(e))throw new xt("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!Zt(t))throw new xt("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Hn(t,a):t,index:r,param:a,optional:i}}));default:throw new xt("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Mt(e)&&!(r.type.length>r.type.filter((function(e){return Un(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Un(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Dn=function(){try{var t=or(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function Kn(t,e,r){"__proto__"==e&&Dn?Dn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function Bn(t,e,r){(void 0===r||He(t[e],r))&&(void 0!==r||e in t)||Kn(t,e,r)}var Vn="object"==typeof exports&&exports&&!exports.nodeType&&exports,Gn=Vn&&"object"==typeof module&&module&&!module.nodeType&&module,Wn=Gn&&Gn.exports===Vn?O.Buffer:void 0,Yn=Wn?Wn.allocUnsafe:void 0;function Qn(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new jr(n).set(new jr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var Xn=Object.create,Zn=function(){function t(){}return function(e){if(!$e(e))return{};if(Xn)return Xn(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function to(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var eo=Object.prototype.hasOwnProperty;function ro(t,e,r){var n=t[e];eo.call(t,e)&&He(n,r)&&(void 0!==r||e in t)||Kn(t,e,r)}var no=Object.prototype.hasOwnProperty;function oo(t){if(!$e(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Pe(t),r=[];for(var n in t)("constructor"!=n||!e&&no.call(t,n))&&r.push(n);return r}function io(t){return Fe(t)?Te(t,!0):oo(t)}function ao(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=po)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(lo);function yo(t,e){return go(function(t,e,r){return e=fo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=fo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=bo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!$e(r))return!1;var n=typeof e;return!!("number"==n?Fe(r)&&ge(e,r.length):"string"==n&&e in r)&&He(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,gt(t))}),Reflect.apply(t,null,r))}};function Lo(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function Do(t,e,r,n){void 0===n&&(n=!1);var o=Lo(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var Ko=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return Fo(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch(Nt)}},Bo=function(t,e,r,n,o){var i={},a=function(t){i=Do(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return Fo(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch(Nt)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},Vo=function(t,e,r,n,o){var i={},a=function(t){i=Do(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return Fo(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch(Nt)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Go=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Ko(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Ko(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var Wo=function(t,e){return function(r){for(var n=[],o=arguments.length-1;o-- >0;)n[o]=arguments[o+1];return new Promise((function(o,i){t.$only(bt(e,r,b),o),t.$only(bt(e,r,_),i),t.$trigger(e,{resolverName:r,args:n})}))}},Yo=function(t,e,r){var n=t.$queues,o=r.debugOn;o&&console.info("(validateRegisteredEvents)","storedEvt",n),n.forEach((function(t){var r=t[0],n=t[1].resolverName;if(o&&console.info("(validateRegisteredEvents)",r,n),!e[r][n])throw new Error(r+"."+n+" not existed in contract!")}))};function Qo(t,e,r,n){var o=function(t,e,r,n){return Ho(Bo,Vo,Go)({},t,e,r,n)}(t,e,r,n);Yo(e,n,r);var i=function(t){e.$only(t,(function(r){var n=r.resolverName,i=r.args;o[t][n]?Reflect.apply(o[t][n],null,i).then((function(r){e.$trigger(bt(t,n,b),r)})).catch((function(r){e.$trigger(bt(t,n,_),r)})):console.error(n+" is not defined in the contract!")}))};for(var a in o)i(a);setTimeout((function(){e.$suspend=!1}),1)}var Xo=function(t,e,r,n){n.$suspend=!0,r.then((function(r){Qo(t,n,e,r)}));var o={query:Wo(n,"query"),mutation:Wo(n,"mutation"),auth:Wo(n,"auth"),getToken:function(){return t.rawAuthToken}};return e.exposeContract&&(o.getContract=function(){return t.get()}),e.enableAuth&&(o.userdata=function(){return t.userdata}),o.version="1.5.1",o};function Zo(t){return!!function(t){return D(t)&&(yt(t,r)||yt(t,n)||yt(t,o))}(t)&&t}function ti(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var ei=function(t,e){return void 0===e&&(e={}),Zo(e)?Promise.resolve(e):t.getContract()},ri="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function ni(t){this.message=t}ni.prototype=new Error,ni.prototype.name="InvalidCharacterError";var oi="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new ni("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=ri.indexOf(n);return a};var ii=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(oi(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return oi(e)}};function ai(t){this.message=t}ai.prototype=new Error,ai.prototype.name="InvalidTokenError";var ui=function(t,e){if("string"!=typeof t)throw new ai("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(ii(t.split(".")[r]))}catch(t){throw new ai("Invalid token specified: "+t.message)}},ci=ai;ui.InvalidTokenError=ci;var si,fi,li,pi,hi,di,vi,gi,yi,bi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function _i(t){if(Ht(t))return function(t){var e=t.iat||bi(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new xt("Token has expired on "+r,t)}return t}(ui(t));throw new xt("Token must be a string!")}Jo("HS256",["string"]),Jo(!1,["boolean","number","string"],((si={})[d]="exp",si[f]=!0,si)),Jo(!1,["boolean","number","string"],((fi={})[d]="nbf",fi[f]=!0,fi)),Jo(!1,["boolean","string"],((li={})[d]="iss",li[f]=!0,li)),Jo(!1,["boolean","string"],((pi={})[d]="sub",pi[f]=!0,pi)),Jo(!1,["boolean","string"],((hi={})[d]="iss",hi[f]=!0,hi)),Jo(!1,["boolean"],((di={})[f]=!0,di)),Jo(!1,["boolean","string"],((vi={})[f]=!0,vi)),Jo(!1,["boolean","string"],((gi={})[f]=!0,gi)),Jo(!1,["boolean"],((yi={})[f]=!0,yi));var mi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},wi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var ji=Object.assign?Object.assign:function(t,e,r,n){for(var o=arguments,i=1;i=0;e--){var r=Di().key(e);t(Ki(r),r)}},remove:function(t){return Di().removeItem(t)},clearAll:function(){return Di().clear()}};function Di(){return Hi.localStorage}function Ki(t){return Di().getItem(t)}var Bi=Ai.trim,Vi={name:"cookieStorage",read:function(t){if(!t||!Qi(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Gi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Gi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Wi,remove:Yi,clearAll:function(){Wi((function(t,e){Yi(e)}))}},Gi=Ai.Global.document;function Wi(t){for(var e=Gi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Bi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Yi(t){t&&Qi(t)&&(Gi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Qi(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Gi.cookie)}var Xi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Zi=Ai.bind,ta=Ai.each,ea=Ai.create,ra=Ai.slice,na=function(){var t=ea(oa,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Zi(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Zi(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),ta(r,(function(e,r){t.fire(r,void 0,e)}))}}};var oa={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Zi(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=ra(arguments,1);ta(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},ia=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),aa=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=ia.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=ia.compress(this._serialize(r));t(e,n)}}};var ua=[Li,Vi],ca=[Xi,na,aa],sa=Fi.createStore(ua,ca),fa=Ai.Global;function la(){return fa.sessionStorage}function pa(t){return la().getItem(t)}var ha=[{name:"sessionStorage",read:pa,write:function(t,e){return la().setItem(t,e)},each:function(t){for(var e=la().length-1;e>=0;e--){var r=la().key(e);t(pa(r),r)}},remove:function(t){return la().removeItem(t)},clearAll:function(){return la().clear()}},Vi],da=[Xi,aa],va=Fi.createStore(ha,da),ga=sa,ya=va,ba=function(t){var e;return(e={}).args=t,e};function _a(t,e){var r;return(r={})[t]=e,r[u]=[mi()],r}var ma=function(t){return yt(t,"data")&&!yt(t,"error")?t.data:t},wa=function(t){this.opts=t,this.instanceKey=ti(this.opts.hostname)+"",this.localStore=ga,this.sessionStore=ya},ja={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};wa.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?_o({},o,e):e,r))},wa.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},wa.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},wa.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},ja.lset.set=function(t){return this.__setMethod("localStore",t)},ja.lget.get=function(){return this.__getMethod("localStore")},wa.prototype.ldel=function(t){return this.__delMethod("localStore",t)},wa.prototype.lclear=function(){return this.__clearMethod("localStore")},ja.sset.set=function(t){return this.__setMethod("sessionStore",t)},ja.sget.get=function(){return this.__getMethod("sessionStore")},wa.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},wa.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(wa.prototype,ja);var Sa=c[0],Oa=c[1],ka=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];!0===this.opts.debugOn&&Reflect.apply(console.info,console,t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=_i)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(Io(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new Tt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&Io(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!Zo(t))throw new Tt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=Zo(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=_o({},{_cb:mi()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=_o({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=_o({},{method:Sa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return ma(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=Ro(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ma(o)}),(function(t){throw e.cleanUp(),console.error(t),new Pt("Server side error",t)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?_o({},e,this.getAuthHeader(),this.extraHeader):_o({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=_o({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(zt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(t){throw console.error("getRemoteContract err",t),new Pt("getRemoteContract",t)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Jt(t)&&m(e)){var n=ba(e);return!0===r?n:_a(t,n)}throw new Tt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(zt)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Jt(t))return _a(t,o);throw new Tt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:Oa}).then(zt)},Object.defineProperties(r.prototype,n),r}(wa)))),Aa={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Ea={hostname:Jo(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:Jo("jsonql",["string"]),loginHandlerName:Jo("login",["string"]),logoutHandlerName:Jo("logout",["string"]),enableJsonp:Jo(!1,["boolean"]),enableAuth:Jo(!1,["boolean"]),useJwt:Jo(!0,["boolean"]),persistToken:Jo(!1,["boolean","number"]),useLocalstorage:Jo(!0,["boolean"]),storageKey:Jo("jsonqlstore",["string"]),authKey:Jo("jsonqlauthkey",["string"]),contractExpired:Jo(0,["number"]),keepContract:Jo(!0,["boolean"]),exposeContract:Jo(!1,["boolean"]),exposeStore:Jo(!1,["boolean"]),showContractDesc:Jo(!1,["boolean"]),contractKey:Jo(!1,["boolean"]),contractKeyName:Jo("X-JSONQL-CV-KEY",["string"]),enableTimeout:Jo(!1,["boolean"]),timeout:Jo(5e3,["number"]),returnInstance:Jo(!1,["boolean"]),allowReturnRawToken:Jo(!1,["boolean"]),debugOn:Jo(!1,["boolean"])};function Ta(t){return Lo(t,v)?t:function(t){return Uo(t,Ea,Aa)}(t)}var xa=new WeakMap,Pa=new WeakMap,qa=function(){this.__suspend__=null,this.queueStore=new Set},Ca={$suspend:{configurable:!0},$queues:{configurable:!0}};Ca.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},qa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ca.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},qa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(qa.prototype,Ca);var $a=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){xa.set(this,t)},r.normalStore.get=function(){return xa.get(this)},r.lazyStore.set=function(t){Pa.set(this,t)},r.lazyStore.get=function(){return Pa.get(this)},e.prototype.hashFnToKey=function(t){return ti(t.toString())+""},Object.defineProperties(e.prototype,r),e}(qa));return function(t,e){void 0===e&&(e={});var r,n=e.contract,o=Ta(e),i=new ka(t,o),a=ei(i,n),u=(r=o.debugOn,new $a({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),c=Xo(i,o,a,u);return c.eventEmitter=u,c}})); //# sourceMappingURL=static.js.map diff --git a/packages/http-client/static.js.map b/packages/http-client/static.js.map index 11d1ecd8..802af841 100644 --- a/packages/http-client/static.js.map +++ b/packages/http-client/static.js.map @@ -1 +1 @@ -{"version":3,"file":"static.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"mg2CAAA"} \ No newline at end of file +{"version":3,"file":"static.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"6g2CAAA"} \ No newline at end of file diff --git a/packages/http-client/tests/qunit/tests/base-test.js b/packages/http-client/tests/qunit/tests/base-test.js index 1ec6751a..4b19b7ae 100644 --- a/packages/http-client/tests/qunit/tests/base-test.js +++ b/packages/http-client/tests/qunit/tests/base-test.js @@ -29,6 +29,7 @@ QUnit.test('jsonqlClient should able to connect to server', function(assert) { // call the mutation before login client.mutation.plus({a: '1', b: '1'}) .catch(err => { + console.error(`--- NOT LOGIN ERROR ---`, err) // @NOTE this is a cheat because the finalCatch from jsonql-errors not always able to catch the correct error assert.equal(err.className, 'JsonqlError', 'Not allow to call private method before login') done3() -- Gitee From 38e770a579a82873f399749d6220ae9f7bbbff41 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 18:46:42 +0800 Subject: [PATCH 2/7] jsonql-errors 1.1.9 --- packages/errors/dist/jsonql-errors.cjs.js | 2 +- packages/errors/dist/jsonql-errors.umd.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/errors/dist/jsonql-errors.cjs.js b/packages/errors/dist/jsonql-errors.cjs.js index cc187d79..c74b4c78 100644 --- a/packages/errors/dist/jsonql-errors.cjs.js +++ b/packages/errors/dist/jsonql-errors.cjs.js @@ -1,2 +1,2 @@ -!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,(function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),s=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(Error),c=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),i=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),u=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(Error),l="No message",f=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(t,e),t}(Error),h=function(r){function t(e,o){r.call(this,o),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),m=Object.freeze({__proto__:null,Jsonql406Error:t,Jsonql500Error:e,JsonqlAuthorisationError:o,JsonqlContractAuthError:n,JsonqlResolverAppError:a,JsonqlResolverNotFoundError:s,JsonqlEnumError:c,JsonqlTypeError:i,JsonqlCheckerError:u,JsonqlValidationError:p,JsonqlError:f,JsonqlServerError:h}),g=f,E=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};var d="unknown";function y(r,t){var e=function(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}(r,t);return e.length?e[0]:d}r.JSONQL_ERRORS_INFO="version: 1.1.8 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=o,r.JsonqlCheckerError=u,r.JsonqlContractAuthError=n,r.JsonqlEnumError=c,r.JsonqlError=f,r.JsonqlResolverAppError=a,r.JsonqlResolverNotFoundError=s,r.JsonqlServerError=h,r.JsonqlTypeError=i,r.JsonqlValidationError=p,r.UNKNOWN_ERROR=d,r.clientErrorsHandler=function(r){if(E(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||l,s=t.detail||t;if(n&&m[n])throw new m[e](a,s);throw new g(a,s)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new p("",r);var m=r.message||l,g=r.detail||r;switch(!0){case r instanceof t:throw new t(m,g);case r instanceof e:throw new e(m,g);case r instanceof o:throw new o(m,g);case r instanceof n:throw new n(m,g);case r instanceof a:throw new a(m,g);case r instanceof s:throw new s(m,g);case r instanceof c:throw new c(m,g);case r instanceof i:throw new i(m,g);case r instanceof u:throw new u(m,g);case r instanceof p:throw new p(m,g);case r instanceof h:throw new h(m,g);default:throw new f(m,g)}},r.getErrorByStatus=function(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}},r.getErrorNameByInstance=y,r.getErrorNameByInstanceWithDefault=function(r,t){var e=y(r,t);return e===d?"JsonqlError":e},Object.defineProperty(r,"__esModule",{value:!0})})); +!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,(function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 403},e.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(t,e),t}(Error),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),s=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),c=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(Error),i=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),u=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),l=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(Error),f="No message",h=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(t,e),t}(Error),m=function(r){function t(e,o){r.call(this,o),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),d=Object.freeze({__proto__:null,Jsonql406Error:t,Jsonql500Error:e,JsonqlForbiddenError:o,JsonqlAuthorisationError:n,JsonqlContractAuthError:a,JsonqlResolverAppError:s,JsonqlResolverNotFoundError:c,JsonqlEnumError:i,JsonqlTypeError:u,JsonqlCheckerError:p,JsonqlValidationError:l,JsonqlError:h,JsonqlServerError:m}),g=h,E=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};var y="unknown";function _(r,t){var e=function(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}(r,t);return e.length?e[0]:y}r.JSONQL_ERRORS_INFO="version: 1.1.9 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=n,r.JsonqlCheckerError=p,r.JsonqlContractAuthError=a,r.JsonqlEnumError=i,r.JsonqlError=h,r.JsonqlForbiddenError=o,r.JsonqlResolverAppError=s,r.JsonqlResolverNotFoundError=c,r.JsonqlServerError=m,r.JsonqlTypeError=u,r.JsonqlValidationError=l,r.UNKNOWN_ERROR=y,r.clientErrorsHandler=function(r){if(E(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||f,s=t.detail||t;if(n&&d[n])throw new d[e](a,s);throw new g(a,s)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new l("",r);var o=r.message||f,d=r.detail||r;switch(!0){case r instanceof t:throw new t(o,d);case r instanceof e:throw new e(o,d);case r instanceof n:throw new n(o,d);case r instanceof a:throw new a(o,d);case r instanceof s:throw new s(o,d);case r instanceof c:throw new c(o,d);case r instanceof i:throw new i(o,d);case r instanceof u:throw new u(o,d);case r instanceof p:throw new p(o,d);case r instanceof l:throw new l(o,d);case r instanceof m:throw new m(o,d);default:throw new h(o,d)}},r.getErrorByStatus=function(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}},r.getErrorNameByInstance=_,r.getErrorNameByInstanceWithDefault=function(r,t){var e=_(r,t);return e===y?"JsonqlError":e},Object.defineProperty(r,"__esModule",{value:!0})})); //# sourceMappingURL=jsonql-errors.cjs.js.map diff --git a/packages/errors/dist/jsonql-errors.umd.js b/packages/errors/dist/jsonql-errors.umd.js index 86022f54..3c928ff3 100644 --- a/packages/errors/dist/jsonql-errors.umd.js +++ b/packages/errors/dist/jsonql-errors.umd.js @@ -1,2 +1,2 @@ -!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,(function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),s=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(Error),c=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),i=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),u=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(Error),l="No message",f=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(t,e),t}(Error),h=function(r){function t(e,o){r.call(this,o),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),m=Object.freeze({__proto__:null,Jsonql406Error:t,Jsonql500Error:e,JsonqlAuthorisationError:o,JsonqlContractAuthError:n,JsonqlResolverAppError:a,JsonqlResolverNotFoundError:s,JsonqlEnumError:c,JsonqlTypeError:i,JsonqlCheckerError:u,JsonqlValidationError:p,JsonqlError:f,JsonqlServerError:h}),g=f,E=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};var d="unknown";function y(r,t){var e=function(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}(r,t);return e.length?e[0]:d}r.JSONQL_ERRORS_INFO="version: 1.1.8 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=o,r.JsonqlCheckerError=u,r.JsonqlContractAuthError=n,r.JsonqlEnumError=c,r.JsonqlError=f,r.JsonqlResolverAppError=a,r.JsonqlResolverNotFoundError=s,r.JsonqlServerError=h,r.JsonqlTypeError=i,r.JsonqlValidationError=p,r.UNKNOWN_ERROR=d,r.clientErrorsHandler=function(r){if(E(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||l,s=t.detail||t;if(n&&m[n])throw new m[e](a,s);throw new g(a,s)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new p("",r);var m=r.message||l,g=r.detail||r;switch(!0){case r instanceof t:throw new t(m,g);case r instanceof e:throw new e(m,g);case r instanceof o:throw new o(m,g);case r instanceof n:throw new n(m,g);case r instanceof a:throw new a(m,g);case r instanceof s:throw new s(m,g);case r instanceof c:throw new c(m,g);case r instanceof i:throw new i(m,g);case r instanceof u:throw new u(m,g);case r instanceof p:throw new p(m,g);case r instanceof h:throw new h(m,g);default:throw new f(m,g)}},r.getErrorByStatus=function(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}},r.getErrorNameByInstance=y,r.getErrorNameByInstanceWithDefault=function(r,t){var e=y(r,t);return e===d?"JsonqlError":e},Object.defineProperty(r,"__esModule",{value:!0})})); +!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,(function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 403},e.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(t,e),t}(Error),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),s=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),c=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(Error),i=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),u=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),l=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(Error),f="No message",h=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(t,e),t}(Error),m=function(r){function t(e,o){r.call(this,o),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),d=Object.freeze({__proto__:null,Jsonql406Error:t,Jsonql500Error:e,JsonqlForbiddenError:o,JsonqlAuthorisationError:n,JsonqlContractAuthError:a,JsonqlResolverAppError:s,JsonqlResolverNotFoundError:c,JsonqlEnumError:i,JsonqlTypeError:u,JsonqlCheckerError:p,JsonqlValidationError:l,JsonqlError:h,JsonqlServerError:m}),g=h,E=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};var y="unknown";function _(r,t){var e=function(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}(r,t);return e.length?e[0]:y}r.JSONQL_ERRORS_INFO="version: 1.1.9 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=n,r.JsonqlCheckerError=p,r.JsonqlContractAuthError=a,r.JsonqlEnumError=i,r.JsonqlError=h,r.JsonqlForbiddenError=o,r.JsonqlResolverAppError=s,r.JsonqlResolverNotFoundError=c,r.JsonqlServerError=m,r.JsonqlTypeError=u,r.JsonqlValidationError=l,r.UNKNOWN_ERROR=y,r.clientErrorsHandler=function(r){if(E(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||f,s=t.detail||t;if(n&&d[n])throw new d[e](a,s);throw new g(a,s)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new l("",r);var o=r.message||f,d=r.detail||r;switch(!0){case r instanceof t:throw new t(o,d);case r instanceof e:throw new e(o,d);case r instanceof n:throw new n(o,d);case r instanceof a:throw new a(o,d);case r instanceof s:throw new s(o,d);case r instanceof c:throw new c(o,d);case r instanceof i:throw new i(o,d);case r instanceof u:throw new u(o,d);case r instanceof p:throw new p(o,d);case r instanceof l:throw new l(o,d);case r instanceof m:throw new m(o,d);default:throw new h(o,d)}},r.getErrorByStatus=function(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}},r.getErrorNameByInstance=_,r.getErrorNameByInstanceWithDefault=function(r,t){var e=_(r,t);return e===y?"JsonqlError":e},Object.defineProperty(r,"__esModule",{value:!0})})); //# sourceMappingURL=jsonql-errors.umd.js.map -- Gitee From 9f2b4191308bba36ec6e9d449c04765a4e523d9f Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 18:47:31 +0800 Subject: [PATCH 3/7] update deps for jsonql-errors --- packages/errors/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/errors/package.json b/packages/errors/package.json index 516e1978..0c6eb581 100644 --- a/packages/errors/package.json +++ b/packages/errors/package.json @@ -33,7 +33,7 @@ "fs-extra": "^8.1.0", "koa": "^2.11.0", "koa-bodyparser": "^4.2.1", - "rollup": "^1.27.8", + "rollup": "^1.27.9", "rollup-plugin-alias": "^2.2.0", "rollup-plugin-async": "^1.2.0", "rollup-plugin-buble": "^0.19.8", @@ -76,6 +76,6 @@ "author": "Joel Chu ", "license": "ISC", "dependencies": { - "jsonql-constants": "^1.8.12" + "jsonql-constants": "^1.8.13" } } -- Gitee From 6be34f8e88070bdf013643a38ca47cf1ccb24c10 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 18:51:49 +0800 Subject: [PATCH 4/7] add back the missing forbidden error to the client error handler --- packages/errors/dist/jsonql-errors.cjs.js | 2 +- packages/errors/dist/jsonql-errors.umd.js | 2 +- packages/errors/package.json | 2 +- packages/errors/src/client-errors-handler.js | 8 +++--- packages/errors/src/final-catch.js | 29 +++++++++++--------- 5 files changed, 23 insertions(+), 20 deletions(-) diff --git a/packages/errors/dist/jsonql-errors.cjs.js b/packages/errors/dist/jsonql-errors.cjs.js index c74b4c78..3955a512 100644 --- a/packages/errors/dist/jsonql-errors.cjs.js +++ b/packages/errors/dist/jsonql-errors.cjs.js @@ -1,2 +1,2 @@ -!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,(function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 403},e.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(t,e),t}(Error),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),s=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),c=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(Error),i=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),u=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),l=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(Error),f="No message",h=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(t,e),t}(Error),m=function(r){function t(e,o){r.call(this,o),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),d=Object.freeze({__proto__:null,Jsonql406Error:t,Jsonql500Error:e,JsonqlForbiddenError:o,JsonqlAuthorisationError:n,JsonqlContractAuthError:a,JsonqlResolverAppError:s,JsonqlResolverNotFoundError:c,JsonqlEnumError:i,JsonqlTypeError:u,JsonqlCheckerError:p,JsonqlValidationError:l,JsonqlError:h,JsonqlServerError:m}),g=h,E=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};var y="unknown";function _(r,t){var e=function(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}(r,t);return e.length?e[0]:y}r.JSONQL_ERRORS_INFO="version: 1.1.9 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=n,r.JsonqlCheckerError=p,r.JsonqlContractAuthError=a,r.JsonqlEnumError=i,r.JsonqlError=h,r.JsonqlForbiddenError=o,r.JsonqlResolverAppError=s,r.JsonqlResolverNotFoundError=c,r.JsonqlServerError=m,r.JsonqlTypeError=u,r.JsonqlValidationError=l,r.UNKNOWN_ERROR=y,r.clientErrorsHandler=function(r){if(E(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||f,s=t.detail||t;if(n&&d[n])throw new d[e](a,s);throw new g(a,s)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new l("",r);var o=r.message||f,d=r.detail||r;switch(!0){case r instanceof t:throw new t(o,d);case r instanceof e:throw new e(o,d);case r instanceof n:throw new n(o,d);case r instanceof a:throw new a(o,d);case r instanceof s:throw new s(o,d);case r instanceof c:throw new c(o,d);case r instanceof i:throw new i(o,d);case r instanceof u:throw new u(o,d);case r instanceof p:throw new p(o,d);case r instanceof l:throw new l(o,d);case r instanceof m:throw new m(o,d);default:throw new h(o,d)}},r.getErrorByStatus=function(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}},r.getErrorNameByInstance=_,r.getErrorNameByInstanceWithDefault=function(r,t){var e=_(r,t);return e===y?"JsonqlError":e},Object.defineProperty(r,"__esModule",{value:!0})})); +!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,(function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 403},e.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(t,e),t}(Error),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),s=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),c=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(Error),i=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),u=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),l=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(Error),f="No message",h=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(t,e),t}(Error),m=function(r){function t(e,o){r.call(this,o),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),d=Object.freeze({__proto__:null,Jsonql406Error:t,Jsonql500Error:e,JsonqlForbiddenError:o,JsonqlAuthorisationError:n,JsonqlContractAuthError:a,JsonqlResolverAppError:s,JsonqlResolverNotFoundError:c,JsonqlEnumError:i,JsonqlTypeError:u,JsonqlCheckerError:p,JsonqlValidationError:l,JsonqlError:h,JsonqlServerError:m}),g=h,E=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};var y="unknown";function _(r,t){var e=function(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}(r,t);return e.length?e[0]:y}r.JSONQL_ERRORS_INFO="version: 1.1.10 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=n,r.JsonqlCheckerError=p,r.JsonqlContractAuthError=a,r.JsonqlEnumError=i,r.JsonqlError=h,r.JsonqlForbiddenError=o,r.JsonqlResolverAppError=s,r.JsonqlResolverNotFoundError=c,r.JsonqlServerError=m,r.JsonqlTypeError=u,r.JsonqlValidationError=l,r.UNKNOWN_ERROR=y,r.clientErrorsHandler=function(r){if(E(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||f,s=t.detail||t;if(n&&d[n])throw new d[e](a,s);throw new g(a,s)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new l("",r);var d=r.message||f,g=r.detail||r;switch(!0){case r instanceof t:throw new t(d,g);case r instanceof e:throw new e(d,g);case r instanceof o:throw new o(d,g);case r instanceof n:throw new n(d,g);case r instanceof a:throw new a(d,g);case r instanceof s:throw new s(d,g);case r instanceof c:throw new c(d,g);case r instanceof i:throw new i(d,g);case r instanceof u:throw new u(d,g);case r instanceof p:throw new p(d,g);case r instanceof l:throw new l(d,g);case r instanceof m:throw new m(d,g);default:throw new h(d,g)}},r.getErrorByStatus=function(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}},r.getErrorNameByInstance=_,r.getErrorNameByInstanceWithDefault=function(r,t){var e=_(r,t);return e===y?"JsonqlError":e},Object.defineProperty(r,"__esModule",{value:!0})})); //# sourceMappingURL=jsonql-errors.cjs.js.map diff --git a/packages/errors/dist/jsonql-errors.umd.js b/packages/errors/dist/jsonql-errors.umd.js index 3c928ff3..fe440838 100644 --- a/packages/errors/dist/jsonql-errors.umd.js +++ b/packages/errors/dist/jsonql-errors.umd.js @@ -1,2 +1,2 @@ -!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,(function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 403},e.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(t,e),t}(Error),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),s=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),c=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(Error),i=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),u=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),l=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(Error),f="No message",h=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(t,e),t}(Error),m=function(r){function t(e,o){r.call(this,o),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),d=Object.freeze({__proto__:null,Jsonql406Error:t,Jsonql500Error:e,JsonqlForbiddenError:o,JsonqlAuthorisationError:n,JsonqlContractAuthError:a,JsonqlResolverAppError:s,JsonqlResolverNotFoundError:c,JsonqlEnumError:i,JsonqlTypeError:u,JsonqlCheckerError:p,JsonqlValidationError:l,JsonqlError:h,JsonqlServerError:m}),g=h,E=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};var y="unknown";function _(r,t){var e=function(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}(r,t);return e.length?e[0]:y}r.JSONQL_ERRORS_INFO="version: 1.1.9 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=n,r.JsonqlCheckerError=p,r.JsonqlContractAuthError=a,r.JsonqlEnumError=i,r.JsonqlError=h,r.JsonqlForbiddenError=o,r.JsonqlResolverAppError=s,r.JsonqlResolverNotFoundError=c,r.JsonqlServerError=m,r.JsonqlTypeError=u,r.JsonqlValidationError=l,r.UNKNOWN_ERROR=y,r.clientErrorsHandler=function(r){if(E(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||f,s=t.detail||t;if(n&&d[n])throw new d[e](a,s);throw new g(a,s)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new l("",r);var o=r.message||f,d=r.detail||r;switch(!0){case r instanceof t:throw new t(o,d);case r instanceof e:throw new e(o,d);case r instanceof n:throw new n(o,d);case r instanceof a:throw new a(o,d);case r instanceof s:throw new s(o,d);case r instanceof c:throw new c(o,d);case r instanceof i:throw new i(o,d);case r instanceof u:throw new u(o,d);case r instanceof p:throw new p(o,d);case r instanceof l:throw new l(o,d);case r instanceof m:throw new m(o,d);default:throw new h(o,d)}},r.getErrorByStatus=function(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}},r.getErrorNameByInstance=_,r.getErrorNameByInstanceWithDefault=function(r,t){var e=_(r,t);return e===y?"JsonqlError":e},Object.defineProperty(r,"__esModule",{value:!0})})); +!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,(function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 403},e.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(t,e),t}(Error),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),s=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),c=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(Error),i=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),u=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),l=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(Error),f="No message",h=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(t,e),t}(Error),m=function(r){function t(e,o){r.call(this,o),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),d=Object.freeze({__proto__:null,Jsonql406Error:t,Jsonql500Error:e,JsonqlForbiddenError:o,JsonqlAuthorisationError:n,JsonqlContractAuthError:a,JsonqlResolverAppError:s,JsonqlResolverNotFoundError:c,JsonqlEnumError:i,JsonqlTypeError:u,JsonqlCheckerError:p,JsonqlValidationError:l,JsonqlError:h,JsonqlServerError:m}),g=h,E=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};var y="unknown";function _(r,t){var e=function(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}(r,t);return e.length?e[0]:y}r.JSONQL_ERRORS_INFO="version: 1.1.10 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=n,r.JsonqlCheckerError=p,r.JsonqlContractAuthError=a,r.JsonqlEnumError=i,r.JsonqlError=h,r.JsonqlForbiddenError=o,r.JsonqlResolverAppError=s,r.JsonqlResolverNotFoundError=c,r.JsonqlServerError=m,r.JsonqlTypeError=u,r.JsonqlValidationError=l,r.UNKNOWN_ERROR=y,r.clientErrorsHandler=function(r){if(E(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||f,s=t.detail||t;if(n&&d[n])throw new d[e](a,s);throw new g(a,s)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new l("",r);var d=r.message||f,g=r.detail||r;switch(!0){case r instanceof t:throw new t(d,g);case r instanceof e:throw new e(d,g);case r instanceof o:throw new o(d,g);case r instanceof n:throw new n(d,g);case r instanceof a:throw new a(d,g);case r instanceof s:throw new s(d,g);case r instanceof c:throw new c(d,g);case r instanceof i:throw new i(d,g);case r instanceof u:throw new u(d,g);case r instanceof p:throw new p(d,g);case r instanceof l:throw new l(d,g);case r instanceof m:throw new m(d,g);default:throw new h(d,g)}},r.getErrorByStatus=function(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}},r.getErrorNameByInstance=_,r.getErrorNameByInstanceWithDefault=function(r,t){var e=_(r,t);return e===y?"JsonqlError":e},Object.defineProperty(r,"__esModule",{value:!0})})); //# sourceMappingURL=jsonql-errors.umd.js.map diff --git a/packages/errors/package.json b/packages/errors/package.json index 0c6eb581..aa145afc 100644 --- a/packages/errors/package.json +++ b/packages/errors/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-errors", - "version": "1.1.9", + "version": "1.1.10", "description": "Jsonql js error classes use across the projects", "main": "dist/jsonql-errors.cjs.js", "module": "index.js", diff --git a/packages/errors/src/client-errors-handler.js b/packages/errors/src/client-errors-handler.js index f157fdd9..8e542ec7 100644 --- a/packages/errors/src/client-errors-handler.js +++ b/packages/errors/src/client-errors-handler.js @@ -1,9 +1,9 @@ // this will add directly to the then call in each http call -import * as errors from './index'; -import getErrorByStatus from './get-error-by-status'; -import { NO_ERROR_MSG } from 'jsonql-constants'; -const { JsonqlError } = errors; +import * as errors from './index' +import getErrorByStatus from './get-error-by-status' +import { NO_ERROR_MSG } from 'jsonql-constants' +const { JsonqlError } = errors /** * We can not just check something like result.data what if the result if false? diff --git a/packages/errors/src/final-catch.js b/packages/errors/src/final-catch.js index 0c849324..82ba8e40 100644 --- a/packages/errors/src/final-catch.js +++ b/packages/errors/src/final-catch.js @@ -1,25 +1,26 @@ -import Jsonql406Error from './406-error'; -import Jsonql500Error from './500-error'; -import JsonqlAuthorisationError from './authorisation-error'; -import JsonqlContractAuthError from './contract-auth-error'; -import JsonqlResolverAppError from './resolver-app-error'; -import JsonqlResolverNotFoundError from './resolver-not-found-error'; +import Jsonql406Error from './406-error' +import Jsonql500Error from './500-error' +import JsonqlForbiddenError from './forbidden-error' +import JsonqlAuthorisationError from './authorisation-error' +import JsonqlContractAuthError from './contract-auth-error' +import JsonqlResolverAppError from './resolver-app-error' +import JsonqlResolverNotFoundError from './resolver-not-found-error' // check options error -import JsonqlEnumError from './enum-error'; -import JsonqlTypeError from './type-error'; -import JsonqlCheckerError from './checker-error'; +import JsonqlEnumError from './enum-error' +import JsonqlTypeError from './type-error' +import JsonqlCheckerError from './checker-error' // share -import JsonqlValidationError from './validation-error'; +import JsonqlValidationError from './validation-error' import JsonqlError from './error'; -import JsonqlServerError from './server-error'; +import JsonqlServerError from './server-error' -import { NO_ERROR_MSG } from 'jsonql-constants'; +import { NO_ERROR_MSG } from 'jsonql-constants' /** * If using the instance of could not find the actual error then * we need to use a different way to analysis the error object to find the exact - * Error type + * Error type * @param {object} e error * @param {*} msg message * @param {*} detail the full detail @@ -55,6 +56,8 @@ export default function finalCatch(e) { throw new Jsonql406Error(msg, detail) case e instanceof Jsonql500Error: throw new Jsonql500Error(msg, detail) + case e instanceof JsonqlForbiddenError: + throw new JsonqlForbiddenError(msg, detail) case e instanceof JsonqlAuthorisationError: throw new JsonqlAuthorisationError(msg, detail) case e instanceof JsonqlContractAuthError: -- Gitee From 8a6be398816786de9e3ada8e067e3f1115cd78d4 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 19:05:29 +0800 Subject: [PATCH 5/7] update all the error handling --- packages/http-client/core.js | 2 +- packages/http-client/core.js.map | 2 +- .../http-client/dist/jsonql-client.static.js | 9650 +---------------- .../dist/jsonql-client.static.js.map | 2 +- .../http-client/dist/jsonql-client.umd.js | 9635 +--------------- .../http-client/dist/jsonql-client.umd.js.map | 2 +- packages/http-client/package.json | 2 +- packages/http-client/src/base/base-cls.js | 6 +- packages/http-client/src/base/contract-cls.js | 12 - packages/http-client/src/base/http-cls.js | 36 +- .../http-client/src/core/methods-generator.js | 8 +- packages/http-client/src/utils.js | 2 + packages/http-client/static.js | 2 +- packages/http-client/static.js.map | 2 +- 14 files changed, 21 insertions(+), 19342 deletions(-) diff --git a/packages/http-client/core.js b/packages/http-client/core.js index 7803868c..89827d0c 100644 --- a/packages/http-client/core.js +++ b/packages/http-client/core.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClient=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b=Array.isArray,_="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},m="object"==typeof _&&_&&_.Object===Object&&_,w="object"==typeof self&&self&&self.Object===Object&&self,j=m||w||Function("return this")(),S=j.Symbol,O=Object.prototype,k=O.hasOwnProperty,A=O.toString,E=S?S.toStringTag:void 0;var T=Object.prototype.toString;var x="[object Null]",P="[object Undefined]",q=S?S.toStringTag:void 0;function C(t){return null==t?void 0===t?P:x:q&&q in Object(t)?function(t){var e=k.call(t,E),r=t[E];try{t[E]=void 0;var n=!0}catch(t){}var o=A.call(t);return n&&(e?t[E]=r:delete t[E]),o}(t):function(t){return T.call(t)}(t)}function $(t,e){return function(r){return t(e(r))}}var z=$(Object.getPrototypeOf,Object);function N(t){return null!=t&&"object"==typeof t}var M="[object Object]",I=Function.prototype,R=Object.prototype,F=I.toString,J=R.hasOwnProperty,U=F.call(Object);function D(t){if(!N(t)||C(t)!=M)return!1;var e=z(t);if(null===e)return!0;var r=J.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&F.call(r)==U}function H(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&X(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var dt=function(t){return b(t)?t:[t]},vt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},gt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),yt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),bt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),_t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),mt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),Tt=Object.freeze({__proto__:null,Jsonql406Error:gt,Jsonql500Error:yt,JsonqlAuthorisationError:bt,JsonqlContractAuthError:_t,JsonqlResolverAppError:mt,JsonqlResolverNotFoundError:wt,JsonqlEnumError:jt,JsonqlTypeError:St,JsonqlCheckerError:Ot,JsonqlValidationError:kt,JsonqlError:At,JsonqlServerError:Et}),xt=At,Pt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function qt(t){if(Pt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&Tt[o])throw new Tt[r](i,a);throw new xt(i,a)}return t}function Ct(t){if(Array.isArray(t))throw new kt("",t);var e=t.message||y,r=t.detail||t;switch(!0){case t instanceof gt:throw new gt(e,r);case t instanceof yt:throw new yt(e,r);case t instanceof bt:throw new bt(e,r);case t instanceof _t:throw new _t(e,r);case t instanceof mt:throw new mt(e,r);case t instanceof wt:throw new wt(e,r);case t instanceof jt:throw new jt(e,r);case t instanceof St:throw new St(e,r);case t instanceof Ot:throw new Ot(e,r);case t instanceof kt:throw new kt(e,r);case t instanceof Et:throw new Et(e,r);default:throw new At(e,r)}}function $t(t){return!!function(t){return D(t)&&(vt(t,r)||vt(t,n)||vt(t,o))}(t)&&t}function zt(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var Nt=function(t,e){return void 0===e&&(e={}),$t(e)?Promise.resolve(e):t.getContract()},Mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function It(t){this.message=t}It.prototype=new Error,It.prototype.name="InvalidCharacterError";var Rt="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new It("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=Mt.indexOf(n);return a};var Ft=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Rt(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return Rt(e)}};function Jt(t){this.message=t}Jt.prototype=new Error,Jt.prototype.name="InvalidTokenError";var Ut=function(t,e){if("string"!=typeof t)throw new Jt("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(Ft(t.split(".")[r]))}catch(t){throw new Jt("Invalid token specified: "+t.message)}},Dt=Jt;Ut.InvalidTokenError=Dt;var Ht="[object String]";function Lt(t){return"string"==typeof t||!b(t)&&N(t)&&C(t)==Ht}var Bt=function(t){return""!==ht(t)&&Lt(t)},Kt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Gt(t){if(Bt(t))return function(t){var e=t.iat||Kt(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new At("Token has expired on "+r,t)}return t}(Ut(t));throw new At("Token must be a string!")}var Vt=function(t){return!!b(t)||null!=t&&""!==ht(t)},Wt="[object Number]";function Yt(t){return function(t){return"number"==typeof t||N(t)&&C(t)==Wt}(t)&&t!=+t}var Qt=function(t){return!Lt(t)&&!Yt(parseFloat(t))},Xt=function(t){return null!=t&&"boolean"==typeof t},Zt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==ht(t)&&(!1===e||!0===e&&null!==t)},te=s,ee=f,re=l,ne=p,oe=h,ie=d,ae="continue",ue=function(t){switch(t){case"number":return Qt;case"string":return Bt;case"boolean":return Xt;default:return Zt}},ce=function(t,e){return void 0===e&&(e=""),!!b(t)&&(""===e||""===ht(e)||!(t.filter((function(t){return!ue(e)(t)})).length>0))},se=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},fe=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ue(e)(t)})).length)})).length:e.length>e.filter((function(t){return!ce(r,t)})).length};var le,pe=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[le?a:++n];if(!1===e(o[u],u,o))break}return t};var he="[object Arguments]";function de(t){return N(t)&&C(t)==he}var ve=Object.prototype,ge=ve.hasOwnProperty,ye=ve.propertyIsEnumerable,be=de(function(){return arguments}())?de:function(t){return N(t)&&ge.call(t,"callee")&&!ye.call(t,"callee")};var _e="object"==typeof exports&&exports&&!exports.nodeType&&exports,me=_e&&"object"==typeof module&&module&&!module.nodeType&&module,we=me&&me.exports===_e?j.Buffer:void 0,je=(we?we.isBuffer:void 0)||function(){return!1},Se=9007199254740991,Oe=/^(?:0|[1-9]\d*)$/;function ke(t,e){var r=typeof t;return!!(e=null==e?Se:e)&&("number"==r||"symbol"!=r&&Oe.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=Ae}var Te={};Te["[object Float32Array]"]=Te["[object Float64Array]"]=Te["[object Int8Array]"]=Te["[object Int16Array]"]=Te["[object Int32Array]"]=Te["[object Uint8Array]"]=Te["[object Uint8ClampedArray]"]=Te["[object Uint16Array]"]=Te["[object Uint32Array]"]=!0,Te["[object Arguments]"]=Te["[object Array]"]=Te["[object ArrayBuffer]"]=Te["[object Boolean]"]=Te["[object DataView]"]=Te["[object Date]"]=Te["[object Error]"]=Te["[object Function]"]=Te["[object Map]"]=Te["[object Number]"]=Te["[object Object]"]=Te["[object RegExp]"]=Te["[object Set]"]=Te["[object String]"]=Te["[object WeakMap]"]=!1;var xe,Pe="object"==typeof exports&&exports&&!exports.nodeType&&exports,qe=Pe&&"object"==typeof module&&module&&!module.nodeType&&module,Ce=qe&&qe.exports===Pe&&m.process,$e=function(){try{var t=qe&&qe.require&&qe.require("util").types;return t||Ce&&Ce.binding&&Ce.binding("util")}catch(t){}}(),ze=$e&&$e.isTypedArray,Ne=ze?(xe=ze,function(t){return xe(t)}):function(t){return N(t)&&Ee(t.length)&&!!Te[C(t)]},Me=Object.prototype.hasOwnProperty;function Ie(t,e){var r=b(t),n=!r&&be(t),o=!r&&!n&&je(t),i=!r&&!n&&!o&&Ne(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},tr.prototype.set=function(t,e){var r=this.__data__,n=Xe(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var er,rr=j["__core-js_shared__"],nr=(er=/[^.]+$/.exec(rr&&rr.keys&&rr.keys.IE_PROTO||""))?"Symbol(src)_1."+er:"";var or=Function.prototype.toString;function ir(t){if(null!=t){try{return or.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ar=/^\[object .+?Constructor\]$/,ur=Function.prototype,cr=Object.prototype,sr=ur.toString,fr=cr.hasOwnProperty,lr=RegExp("^"+sr.call(fr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function pr(t){return!(!De(t)||function(t){return!!nr&&nr in t}(t))&&(Ge(t)?lr:ar).test(ir(t))}function hr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return pr(r)?r:void 0}var dr=hr(j,"Map"),vr=hr(Object,"create");var gr="__lodash_hash_undefined__",yr=Object.prototype.hasOwnProperty;var br=Object.prototype.hasOwnProperty;var _r="__lodash_hash_undefined__";function mr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&xr?new Ar:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=se(t))?!fe({arg:r},e):!ue(t)(r))})).length)})).length}return!1},Yn=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Wn,null,a);case"array"===t:return!ce(e.arg);case!1!==(r=se(t)):return!fe(e,r);default:return!ue(t)(e.arg)}},Qn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Xn=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!ce(e))throw new At("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!ce(t))throw new At("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Qn(t,a):t,index:r,param:a,optional:i}}));default:throw new At("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Vt(e)&&!(r.type.length>r.type.filter((function(e){return Yn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Yn(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Zn=function(){try{var t=hr(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function to(t,e,r){"__proto__"==e&&Zn?Zn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function eo(t,e,r){(void 0===r||Qe(t[e],r))&&(void 0!==r||e in t)||to(t,e,r)}var ro="object"==typeof exports&&exports&&!exports.nodeType&&exports,no=ro&&"object"==typeof module&&module&&!module.nodeType&&module,oo=no&&no.exports===ro?j.Buffer:void 0,io=oo?oo.allocUnsafe:void 0;function ao(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new qr(n).set(new qr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var uo=Object.create,co=function(){function t(){}return function(e){if(!De(e))return{};if(uo)return uo(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function so(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var fo=Object.prototype.hasOwnProperty;function lo(t,e,r){var n=t[e];fo.call(t,e)&&Qe(n,r)&&(void 0!==r||e in t)||to(t,e,r)}var po=Object.prototype.hasOwnProperty;function ho(t){if(!De(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Fe(t),r=[];for(var n in t)("constructor"!=n||!e&&po.call(t,n))&&r.push(n);return r}function vo(t){return Ve(t)?Ie(t,!0):ho(t)}function go(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=jo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(wo);function Ao(t,e){return ko(function(t,e,r){return e=mo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=mo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Eo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!De(r))return!1;var n=typeof e;return!!("number"==n?Ve(r)&&ke(e,r.length):"string"==n&&e in r)&&Qe(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=0;e--){var r=qi().key(e);t(Ci(r),r)}},remove:function(t){return qi().removeItem(t)},clearAll:function(){return qi().clear()}};function qi(){return xi.localStorage}function Ci(t){return qi().getItem(t)}var $i=hi.trim,zi={name:"cookieStorage",read:function(t){if(!t||!Ri(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Ni.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Ni.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Mi,remove:Ii,clearAll:function(){Mi((function(t,e){Ii(e)}))}},Ni=hi.Global.document;function Mi(t){for(var e=Ni.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if($i(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Ii(t){t&&Ri(t)&&(Ni.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Ri(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Ni.cookie)}var Fi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Ji=hi.bind,Ui=hi.each,Di=hi.create,Hi=hi.slice,Li=function(){var t=Di(Bi,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Ji(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Ji(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),Ui(r,(function(e,r){t.fire(r,void 0,e)}))}}};var Bi={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Ji(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Hi(arguments,1);Ui(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},Ki=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),Gi=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=Ki.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=Ki.compress(this._serialize(r));t(e,n)}}};var Vi=[Pi,zi],Wi=[Fi,Li,Gi],Yi=Ai.createStore(Vi,Wi),Qi=hi.Global;function Xi(){return Qi.sessionStorage}function Zi(t){return Xi().getItem(t)}var ta=[{name:"sessionStorage",read:Zi,write:function(t,e){return Xi().setItem(t,e)},each:function(t){for(var e=Xi().length-1;e>=0;e--){var r=Xi().key(e);t(Zi(r),r)}},remove:function(t){return Xi().removeItem(t)},clearAll:function(){return Xi().clear()}},zi],ea=[Fi,Gi],ra=Ai.createStore(ta,ea),na=Yi,oa=ra,ia=function(t){var e;return(e={}).args=t,e};function aa(t,e){var r;return(r={})[t]=e,r[u]=[ui()],r}var ua=function(t){return vt(t,"data")&&!vt(t,"error")?t.data:t},ca=function(t){this.opts=t,this.instanceKey=zt(this.opts.hostname)+"",this.localStore=na,this.sessionStore=oa},sa={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};ca.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?To({},o,e):e,r))},ca.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},ca.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},ca.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},sa.lset.set=function(t){return this.__setMethod("localStore",t)},sa.lget.get=function(){return this.__getMethod("localStore")},ca.prototype.ldel=function(t){return this.__delMethod("localStore",t)},ca.prototype.lclear=function(){return this.__clearMethod("localStore")},sa.sset.set=function(t){return this.__setMethod("sessionStore",t)},sa.sget.get=function(){return this.__getMethod("sessionStore")},ca.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},ca.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(ca.prototype,sa);var fa=c[0],la=c[1],pa=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];!0===this.opts.debugOn&&Reflect.apply(console.info,console,t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Gt)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(ni(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new kt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&ni(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!$t(t))throw new kt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=$t(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=To({},{_cb:ui()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=To({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=To({},{method:fa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return ua(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=ri(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ua(o)}),(function(t){throw e.cleanUp(),console.error(t),new Et("Server side error",t)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?To({},e,this.getAuthHeader(),this.extraHeader):To({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=To({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(qt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(t){throw console.error("getRemoteContract err",t),new Et("getRemoteContract",t)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Lt(t)&&b(e)){var n=ia(e);return!0===r?n:aa(t,n)}throw new kt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(qt)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Lt(t))return aa(t,o);throw new kt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:la}).then(qt)},Object.defineProperties(r.prototype,n),r}(ca)))),ha=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,dt(t))}),Reflect.apply(t,null,r))}};function da(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function va(t,e,r,n){void 0===n&&(n=!1);var o=da(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var ga=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return oi(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch(Ct)}},ya=function(t,e,r,n,o){var i={},a=function(t){i=va(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return oi(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch(Ct)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},ba=function(t,e,r,n,o){var i={},a=function(t){i=va(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return oi(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch(Ct)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},_a=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ga(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ga(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var ma=function(t,e,r,n){var o=function(t,e,r,n){return ha(ya,ba,_a)({},t,e,r,n)}(t,n,e,r);return e.enableAuth&&(o.userdata=function(){return t.jsonqlUserdata},o.getToken=function(e){return void 0===e&&(e=!1),t.rawAuthToken(e)},o.profileIndex=function(e){if(void 0===e&&(e=!1),!1===e)return t.profileIndex;t.profileIndex=e},o.getProfiles=function(e){return void 0===e&&(e=!1),t.getProfiles(e)}),e.exposeContract&&(o.getContract=function(){return t.getContract()}),e.exposeStore&&(o.tmpSave=function(t){},o.tmpGet=function(t){},o.tmpDel=function(t){},o.persistSave=function(t){},o.persistGet=function(t){},o.persistDel=function(t){}),o.eventEmitter=n,o.version="1.5.1",o.log=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return Reflect.apply(t.log,t,["[DEV DEBUG]"].concat(e))},o},wa={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},ja={hostname:ii(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:ii("jsonql",["string"]),loginHandlerName:ii("login",["string"]),logoutHandlerName:ii("logout",["string"]),enableJsonp:ii(!1,["boolean"]),enableAuth:ii(!1,["boolean"]),useJwt:ii(!0,["boolean"]),persistToken:ii(!1,["boolean","number"]),useLocalstorage:ii(!0,["boolean"]),storageKey:ii("jsonqlstore",["string"]),authKey:ii("jsonqlauthkey",["string"]),contractExpired:ii(0,["number"]),keepContract:ii(!0,["boolean"]),exposeContract:ii(!1,["boolean"]),exposeStore:ii(!1,["boolean"]),showContractDesc:ii(!1,["boolean"]),contractKey:ii(!1,["boolean"]),contractKeyName:ii("X-JSONQL-CV-KEY",["string"]),enableTimeout:ii(!1,["boolean"]),timeout:ii(5e3,["number"]),returnInstance:ii(!1,["boolean"]),allowReturnRawToken:ii(!1,["boolean"]),debugOn:ii(!1,["boolean"])};function Sa(t){return da(t,v)?Promise.resolve(t):function(t){var e=t.contract;return ai(t,ja,wa).then((function(t){return t.contract=e,t}))}(t)}var Oa=new WeakMap,ka=new WeakMap,Aa=function(){this.__suspend__=null,this.queueStore=new Set},Ea={$suspend:{configurable:!0},$queues:{configurable:!0}};Ea.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Aa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ea.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Aa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Aa.prototype,Ea);var Ta=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Oa.set(this,t)},r.normalStore.get=function(){return Oa.get(this)},r.lazyStore.set=function(t){ka.set(this,t)},r.lazyStore.get=function(){return ka.get(this)},e.prototype.hashFnToKey=function(t){return zt(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Aa));return function(t,e){var r;return function(t,e,r){return void 0===e&&(e={}),Sa(e).then((function(t){return{baseClient:new pa(r,t),opts:t}})).then((function(e){var r=e.baseClient,n=e.opts;return Nt(r,n.contract).then((function(e){return ma(r,n,e,t)}))}))}((r=e.debugOn,new Ta({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),e,t)}})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClient=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b=Array.isArray,_="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},m="object"==typeof _&&_&&_.Object===Object&&_,j="object"==typeof self&&self&&self.Object===Object&&self,w=m||j||Function("return this")(),S=w.Symbol,O=Object.prototype,k=O.hasOwnProperty,A=O.toString,E=S?S.toStringTag:void 0;var T=Object.prototype.toString;var x="[object Null]",P="[object Undefined]",q=S?S.toStringTag:void 0;function C(t){return null==t?void 0===t?P:x:q&&q in Object(t)?function(t){var e=k.call(t,E),r=t[E];try{t[E]=void 0;var n=!0}catch(t){}var o=A.call(t);return n&&(e?t[E]=r:delete t[E]),o}(t):function(t){return T.call(t)}(t)}function $(t,e){return function(r){return t(e(r))}}var z=$(Object.getPrototypeOf,Object);function N(t){return null!=t&&"object"==typeof t}var M="[object Object]",I=Function.prototype,R=Object.prototype,F=I.toString,J=R.hasOwnProperty,U=F.call(Object);function D(t){if(!N(t)||C(t)!=M)return!1;var e=z(t);if(null===e)return!0;var r=J.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&F.call(r)==U}function H(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&X(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var dt=function(t){return b(t)?t:[t]},vt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},gt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),yt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),bt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),_t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),mt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),xt=Object.freeze({__proto__:null,Jsonql406Error:gt,Jsonql500Error:yt,JsonqlForbiddenError:bt,JsonqlAuthorisationError:_t,JsonqlContractAuthError:mt,JsonqlResolverAppError:jt,JsonqlResolverNotFoundError:wt,JsonqlEnumError:St,JsonqlTypeError:Ot,JsonqlCheckerError:kt,JsonqlValidationError:At,JsonqlError:Et,JsonqlServerError:Tt}),Pt=Et,qt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function Ct(t){if(qt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&xt[o])throw new xt[r](i,a);throw new Pt(i,a)}return t}function $t(t){return!!function(t){return D(t)&&(vt(t,r)||vt(t,n)||vt(t,o))}(t)&&t}function zt(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var Nt=function(t,e){return void 0===e&&(e={}),$t(e)?Promise.resolve(e):t.getContract()},Mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function It(t){this.message=t}It.prototype=new Error,It.prototype.name="InvalidCharacterError";var Rt="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new It("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=Mt.indexOf(n);return a};var Ft=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Rt(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return Rt(e)}};function Jt(t){this.message=t}Jt.prototype=new Error,Jt.prototype.name="InvalidTokenError";var Ut=function(t,e){if("string"!=typeof t)throw new Jt("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(Ft(t.split(".")[r]))}catch(t){throw new Jt("Invalid token specified: "+t.message)}},Dt=Jt;Ut.InvalidTokenError=Dt;var Ht="[object String]";function Lt(t){return"string"==typeof t||!b(t)&&N(t)&&C(t)==Ht}var Bt=function(t){return""!==ht(t)&&Lt(t)},Kt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Gt(t){if(Bt(t))return function(t){var e=t.iat||Kt(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Et("Token has expired on "+r,t)}return t}(Ut(t));throw new Et("Token must be a string!")}var Vt=function(t){return!!b(t)||null!=t&&""!==ht(t)},Wt="[object Number]";function Yt(t){return function(t){return"number"==typeof t||N(t)&&C(t)==Wt}(t)&&t!=+t}var Qt=function(t){return!Lt(t)&&!Yt(parseFloat(t))},Xt=function(t){return null!=t&&"boolean"==typeof t},Zt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==ht(t)&&(!1===e||!0===e&&null!==t)},te=s,ee=f,re=l,ne=p,oe=h,ie=d,ae="continue",ue=function(t){switch(t){case"number":return Qt;case"string":return Bt;case"boolean":return Xt;default:return Zt}},ce=function(t,e){return void 0===e&&(e=""),!!b(t)&&(""===e||""===ht(e)||!(t.filter((function(t){return!ue(e)(t)})).length>0))},se=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},fe=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ue(e)(t)})).length)})).length:e.length>e.filter((function(t){return!ce(r,t)})).length};var le,pe=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[le?a:++n];if(!1===e(o[u],u,o))break}return t};var he="[object Arguments]";function de(t){return N(t)&&C(t)==he}var ve=Object.prototype,ge=ve.hasOwnProperty,ye=ve.propertyIsEnumerable,be=de(function(){return arguments}())?de:function(t){return N(t)&&ge.call(t,"callee")&&!ye.call(t,"callee")};var _e="object"==typeof exports&&exports&&!exports.nodeType&&exports,me=_e&&"object"==typeof module&&module&&!module.nodeType&&module,je=me&&me.exports===_e?w.Buffer:void 0,we=(je?je.isBuffer:void 0)||function(){return!1},Se=9007199254740991,Oe=/^(?:0|[1-9]\d*)$/;function ke(t,e){var r=typeof t;return!!(e=null==e?Se:e)&&("number"==r||"symbol"!=r&&Oe.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=Ae}var Te={};Te["[object Float32Array]"]=Te["[object Float64Array]"]=Te["[object Int8Array]"]=Te["[object Int16Array]"]=Te["[object Int32Array]"]=Te["[object Uint8Array]"]=Te["[object Uint8ClampedArray]"]=Te["[object Uint16Array]"]=Te["[object Uint32Array]"]=!0,Te["[object Arguments]"]=Te["[object Array]"]=Te["[object ArrayBuffer]"]=Te["[object Boolean]"]=Te["[object DataView]"]=Te["[object Date]"]=Te["[object Error]"]=Te["[object Function]"]=Te["[object Map]"]=Te["[object Number]"]=Te["[object Object]"]=Te["[object RegExp]"]=Te["[object Set]"]=Te["[object String]"]=Te["[object WeakMap]"]=!1;var xe,Pe="object"==typeof exports&&exports&&!exports.nodeType&&exports,qe=Pe&&"object"==typeof module&&module&&!module.nodeType&&module,Ce=qe&&qe.exports===Pe&&m.process,$e=function(){try{var t=qe&&qe.require&&qe.require("util").types;return t||Ce&&Ce.binding&&Ce.binding("util")}catch(t){}}(),ze=$e&&$e.isTypedArray,Ne=ze?(xe=ze,function(t){return xe(t)}):function(t){return N(t)&&Ee(t.length)&&!!Te[C(t)]},Me=Object.prototype.hasOwnProperty;function Ie(t,e){var r=b(t),n=!r&&be(t),o=!r&&!n&&we(t),i=!r&&!n&&!o&&Ne(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},tr.prototype.set=function(t,e){var r=this.__data__,n=Xe(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var er,rr=w["__core-js_shared__"],nr=(er=/[^.]+$/.exec(rr&&rr.keys&&rr.keys.IE_PROTO||""))?"Symbol(src)_1."+er:"";var or=Function.prototype.toString;function ir(t){if(null!=t){try{return or.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ar=/^\[object .+?Constructor\]$/,ur=Function.prototype,cr=Object.prototype,sr=ur.toString,fr=cr.hasOwnProperty,lr=RegExp("^"+sr.call(fr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function pr(t){return!(!De(t)||function(t){return!!nr&&nr in t}(t))&&(Ge(t)?lr:ar).test(ir(t))}function hr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return pr(r)?r:void 0}var dr=hr(w,"Map"),vr=hr(Object,"create");var gr="__lodash_hash_undefined__",yr=Object.prototype.hasOwnProperty;var br=Object.prototype.hasOwnProperty;var _r="__lodash_hash_undefined__";function mr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&xr?new Ar:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=se(t))?!fe({arg:r},e):!ue(t)(r))})).length)})).length}return!1},Yn=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Wn,null,a);case"array"===t:return!ce(e.arg);case!1!==(r=se(t)):return!fe(e,r);default:return!ue(t)(e.arg)}},Qn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Xn=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!ce(e))throw new Et("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!ce(t))throw new Et("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Qn(t,a):t,index:r,param:a,optional:i}}));default:throw new Et("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Vt(e)&&!(r.type.length>r.type.filter((function(e){return Yn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Yn(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Zn=function(){try{var t=hr(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function to(t,e,r){"__proto__"==e&&Zn?Zn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function eo(t,e,r){(void 0===r||Qe(t[e],r))&&(void 0!==r||e in t)||to(t,e,r)}var ro="object"==typeof exports&&exports&&!exports.nodeType&&exports,no=ro&&"object"==typeof module&&module&&!module.nodeType&&module,oo=no&&no.exports===ro?w.Buffer:void 0,io=oo?oo.allocUnsafe:void 0;function ao(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new qr(n).set(new qr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var uo=Object.create,co=function(){function t(){}return function(e){if(!De(e))return{};if(uo)return uo(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function so(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var fo=Object.prototype.hasOwnProperty;function lo(t,e,r){var n=t[e];fo.call(t,e)&&Qe(n,r)&&(void 0!==r||e in t)||to(t,e,r)}var po=Object.prototype.hasOwnProperty;function ho(t){if(!De(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Fe(t),r=[];for(var n in t)("constructor"!=n||!e&&po.call(t,n))&&r.push(n);return r}function vo(t){return Ve(t)?Ie(t,!0):ho(t)}function go(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=wo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(jo);function Ao(t,e){return ko(function(t,e,r){return e=mo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=mo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Eo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!De(r))return!1;var n=typeof e;return!!("number"==n?Ve(r)&&ke(e,r.length):"string"==n&&e in r)&&Qe(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=0;e--){var r=qi().key(e);t(Ci(r),r)}},remove:function(t){return qi().removeItem(t)},clearAll:function(){return qi().clear()}};function qi(){return xi.localStorage}function Ci(t){return qi().getItem(t)}var $i=hi.trim,zi={name:"cookieStorage",read:function(t){if(!t||!Ri(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Ni.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Ni.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Mi,remove:Ii,clearAll:function(){Mi((function(t,e){Ii(e)}))}},Ni=hi.Global.document;function Mi(t){for(var e=Ni.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if($i(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Ii(t){t&&Ri(t)&&(Ni.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Ri(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Ni.cookie)}var Fi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Ji=hi.bind,Ui=hi.each,Di=hi.create,Hi=hi.slice,Li=function(){var t=Di(Bi,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Ji(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Ji(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),Ui(r,(function(e,r){t.fire(r,void 0,e)}))}}};var Bi={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Ji(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Hi(arguments,1);Ui(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},Ki=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),Gi=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=Ki.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=Ki.compress(this._serialize(r));t(e,n)}}};var Vi=[Pi,zi],Wi=[Fi,Li,Gi],Yi=Ai.createStore(Vi,Wi),Qi=hi.Global;function Xi(){return Qi.sessionStorage}function Zi(t){return Xi().getItem(t)}var ta=[{name:"sessionStorage",read:Zi,write:function(t,e){return Xi().setItem(t,e)},each:function(t){for(var e=Xi().length-1;e>=0;e--){var r=Xi().key(e);t(Zi(r),r)}},remove:function(t){return Xi().removeItem(t)},clearAll:function(){return Xi().clear()}},zi],ea=[Fi,Gi],ra=Ai.createStore(ta,ea),na=Yi,oa=ra,ia=function(t){var e;return(e={}).args=t,e};function aa(t,e){var r;return(r={})[t]=e,r[u]=[ui()],r}var ua=function(t){return vt(t,"data")&&!vt(t,"error")?t.data:t},ca=function(t){this.opts=t,this.instanceKey=zt(this.opts.hostname)+"",this.localStore=na,this.sessionStore=oa},sa={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};ca.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?To({},o,e):e,r))},ca.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},ca.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},ca.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},sa.lset.set=function(t){return this.__setMethod("localStore",t)},sa.lget.get=function(){return this.__getMethod("localStore")},ca.prototype.ldel=function(t){return this.__delMethod("localStore",t)},ca.prototype.lclear=function(){return this.__clearMethod("localStore")},sa.sset.set=function(t){return this.__setMethod("sessionStore",t)},sa.sget.get=function(){return this.__getMethod("sessionStore")},ca.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},ca.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(ca.prototype,sa);var fa=c[0],la=c[1],pa=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Gt)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(ni(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new At("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&ni(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!$t(t))throw new At("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=$t(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=To({},{_cb:ui()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=To({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=To({},{method:fa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return ua(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=ri(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ua(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new Tt("Server side error",r)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?To({},e,this.getAuthHeader(),this.extraHeader):To({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=To({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(Ct).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new Tt("getRemoteContract",e)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Lt(t)&&b(e)){var n=ia(e);return!0===r?n:aa(t,n)}throw new At("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(Ct)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Lt(t))return aa(t,o);throw new At("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:la}).then(Ct)},Object.defineProperties(r.prototype,n),r}(ca)))),ha=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,dt(t))}),Reflect.apply(t,null,r))}};function da(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function va(t,e,r,n){void 0===n&&(n=!1);var o=da(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var ga=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return oi(r,i).then((function(){return t.query.apply(t,[e,a,u])}))}},ya=function(t,e,r,n,o){var i={},a=function(t){i=va(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return oi(a,i).then((function(){return e.query.apply(e,[t,a,u])}))}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},ba=function(t,e,r,n,o){var i={},a=function(t){i=va(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return oi(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])}))}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},_a=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ga(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ga(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var ma=function(t,e,r,n){var o=function(t,e,r,n){return ha(ya,ba,_a)({},t,e,r,n)}(t,n,e,r);return e.enableAuth&&(o.userdata=function(){return t.jsonqlUserdata},o.getToken=function(e){return void 0===e&&(e=!1),t.rawAuthToken(e)},o.profileIndex=function(e){if(void 0===e&&(e=!1),!1===e)return t.profileIndex;t.profileIndex=e},o.getProfiles=function(e){return void 0===e&&(e=!1),t.getProfiles(e)}),e.exposeContract&&(o.getContract=function(){return t.getContract()}),e.exposeStore&&(o.tmpSave=function(t){},o.tmpGet=function(t){},o.tmpDel=function(t){},o.persistSave=function(t){},o.persistGet=function(t){},o.persistDel=function(t){}),o.eventEmitter=n,o.version="1.5.1",o.log=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return Reflect.apply(t.log,t,["[DEV DEBUG]"].concat(e))},o},ja={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},wa={hostname:ii(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:ii("jsonql",["string"]),loginHandlerName:ii("login",["string"]),logoutHandlerName:ii("logout",["string"]),enableJsonp:ii(!1,["boolean"]),enableAuth:ii(!1,["boolean"]),useJwt:ii(!0,["boolean"]),persistToken:ii(!1,["boolean","number"]),useLocalstorage:ii(!0,["boolean"]),storageKey:ii("jsonqlstore",["string"]),authKey:ii("jsonqlauthkey",["string"]),contractExpired:ii(0,["number"]),keepContract:ii(!0,["boolean"]),exposeContract:ii(!1,["boolean"]),exposeStore:ii(!1,["boolean"]),showContractDesc:ii(!1,["boolean"]),contractKey:ii(!1,["boolean"]),contractKeyName:ii("X-JSONQL-CV-KEY",["string"]),enableTimeout:ii(!1,["boolean"]),timeout:ii(5e3,["number"]),returnInstance:ii(!1,["boolean"]),allowReturnRawToken:ii(!1,["boolean"]),debugOn:ii(!1,["boolean"])};function Sa(t){return da(t,v)?Promise.resolve(t):function(t){var e=t.contract;return ai(t,wa,ja).then((function(t){return t.contract=e,t}))}(t)}var Oa=new WeakMap,ka=new WeakMap,Aa=function(){this.__suspend__=null,this.queueStore=new Set},Ea={$suspend:{configurable:!0},$queues:{configurable:!0}};Ea.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Aa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ea.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Aa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Aa.prototype,Ea);var Ta=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Oa.set(this,t)},r.normalStore.get=function(){return Oa.get(this)},r.lazyStore.set=function(t){ka.set(this,t)},r.lazyStore.get=function(){return ka.get(this)},e.prototype.hashFnToKey=function(t){return zt(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Aa));return function(t,e){var r;return function(t,e,r){return void 0===e&&(e={}),Sa(e).then((function(t){return{baseClient:new pa(r,t),opts:t}})).then((function(e){var r=e.baseClient,n=e.opts;return Nt(r,n.contract).then((function(e){return ma(r,n,e,t)}))}))}((r=e.debugOn,new Ta({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),e,t)}})); //# sourceMappingURL=core.js.map diff --git a/packages/http-client/core.js.map b/packages/http-client/core.js.map index d85cb822..134a4298 100644 --- a/packages/http-client/core.js.map +++ b/packages/http-client/core.js.map @@ -1 +1 @@ -{"version":3,"file":"core.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"y2vCAAA"} \ No newline at end of file +{"version":3,"file":"core.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"i0vCAAA"} \ No newline at end of file diff --git a/packages/http-client/dist/jsonql-client.static.js b/packages/http-client/dist/jsonql-client.static.js index 3cb965c0..961f72db 100644 --- a/packages/http-client/dist/jsonql-client.static.js +++ b/packages/http-client/dist/jsonql-client.static.js @@ -1,9650 +1,2 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = global || self, global.jsonqlClientStatic = factory()); -}(this, (function () { 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var fly = createCommonjsModule(function (module, exports) { - (function webpackUniversalModuleDefinition(root, factory) { - { module.exports = factory(); } - })(commonjsGlobal, function() { - return /******/ (function(modules) { // webpackBootstrap - /******/ // The module cache - /******/ var installedModules = {}; - /******/ - /******/ // The require function - /******/ function __webpack_require__(moduleId) { - /******/ - /******/ // Check if module is in cache - /******/ if(installedModules[moduleId]) { - /******/ return installedModules[moduleId].exports; - /******/ } - /******/ // Create a new module (and put it into the cache) - /******/ var module = installedModules[moduleId] = { - /******/ i: moduleId, - /******/ l: false, - /******/ exports: {} - /******/ }; - /******/ - /******/ // Execute the module function - /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - /******/ - /******/ // Flag the module as loaded - /******/ module.l = true; - /******/ - /******/ // Return the exports of the module - /******/ return module.exports; - /******/ } - /******/ - /******/ - /******/ // expose the modules object (__webpack_modules__) - /******/ __webpack_require__.m = modules; - /******/ - /******/ // expose the module cache - /******/ __webpack_require__.c = installedModules; - /******/ - /******/ // identity function for calling harmony imports with the correct context - /******/ __webpack_require__.i = function(value) { return value; }; - /******/ - /******/ // define getter function for harmony exports - /******/ __webpack_require__.d = function(exports, name, getter) { - /******/ if(!__webpack_require__.o(exports, name)) { - /******/ Object.defineProperty(exports, name, { - /******/ configurable: false, - /******/ enumerable: true, - /******/ get: getter - /******/ }); - /******/ } - /******/ }; - /******/ - /******/ // getDefaultExport function for compatibility with non-harmony modules - /******/ __webpack_require__.n = function(module) { - /******/ var getter = module && module.__esModule ? - /******/ function getDefault() { return module['default']; } : - /******/ function getModuleExports() { return module; }; - /******/ __webpack_require__.d(getter, 'a', getter); - /******/ return getter; - /******/ }; - /******/ - /******/ // Object.prototype.hasOwnProperty.call - /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; - /******/ - /******/ // __webpack_public_path__ - /******/ __webpack_require__.p = ""; - /******/ - /******/ // Load entry module and return exports - /******/ return __webpack_require__(__webpack_require__.s = 2); - /******/ }) - /************************************************************************/ - /******/ ([ - /* 0 */ - /***/ (function(module, exports, __webpack_require__) { - - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - module.exports = { - type: function type(ob) { - return Object.prototype.toString.call(ob).slice(8, -1).toLowerCase(); - }, - isObject: function isObject(ob, real) { - if (real) { - return this.type(ob) === "object"; - } else { - return ob && (typeof ob === 'undefined' ? 'undefined' : _typeof(ob)) === 'object'; - } - }, - isFormData: function isFormData(val) { - return typeof FormData !== 'undefined' && val instanceof FormData; - }, - trim: function trim(str) { - return str.replace(/(^\s*)|(\s*$)/g, ''); - }, - encode: function encode(val) { - return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); - }, - formatParams: function formatParams(data) { - var str = ""; - var first = true; - var that = this; - if (!this.isObject(data)) { - return data; - } - - function _encode(sub, path) { - var encode = that.encode; - var type = that.type(sub); - if (type == "array") { - sub.forEach(function (e, i) { - if (!that.isObject(e)) { i = ""; } - _encode(e, path + ('%5B' + i + '%5D')); - }); - } else if (type == "object") { - for (var key in sub) { - if (path) { - _encode(sub[key], path + "%5B" + encode(key) + "%5D"); - } else { - _encode(sub[key], encode(key)); - } - } - } else { - if (!first) { - str += "&"; - } - first = false; - str += path + "=" + encode(sub); - } - } - - _encode(data, ""); - return str; - }, - - // Do not overwrite existing attributes - merge: function merge(a, b) { - for (var key in b) { - if (!a.hasOwnProperty(key)) { - a[key] = b[key]; - } else if (this.isObject(b[key], 1) && this.isObject(a[key], 1)) { - this.merge(a[key], b[key]); - } - } - return a; - } - }; - - /***/ }), - /* 1 */, - /* 2 */ - /***/ (function(module, exports, __webpack_require__) { - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - var utils = __webpack_require__(0); - var isBrowser = typeof document !== "undefined"; - - var Fly = function () { - function Fly(engine) { - _classCallCheck(this, Fly); - - this.engine = engine || XMLHttpRequest; - - this.default = this; //For typeScript - - /** - * Add lock/unlock API for interceptor. - * - * Once an request/response interceptor is locked, the incoming request/response - * will be added to a queue before they enter the interceptor, they will not be - * continued until the interceptor is unlocked. - * - * @param [interceptor] either is interceptors.request or interceptors.response - */ - function wrap(interceptor) { - var resolve = void 0; - var reject = void 0; - - function _clear() { - interceptor.p = resolve = reject = null; - } - - utils.merge(interceptor, { - lock: function lock() { - if (!resolve) { - interceptor.p = new Promise(function (_resolve, _reject) { - resolve = _resolve; - reject = _reject; - }); - } - }, - unlock: function unlock() { - if (resolve) { - resolve(); - _clear(); - } - }, - clear: function clear() { - if (reject) { - reject("cancel"); - _clear(); - } - } - }); - } - - var interceptors = this.interceptors = { - response: { - use: function use(handler, onerror) { - this.handler = handler; - this.onerror = onerror; - } - }, - request: { - use: function use(handler) { - this.handler = handler; - } - } - }; - - var irq = interceptors.request; - var irp = interceptors.response; - wrap(irp); - wrap(irq); - - this.config = { - method: "GET", - baseURL: "", - headers: {}, - timeout: 0, - params: {}, // Default Url params - parseJson: true, // Convert response data to JSON object automatically. - withCredentials: false - }; - } - - _createClass(Fly, [{ - key: "request", - value: function request(url, data, options) { - var _this = this; - - var engine = new this.engine(); - var contentType = "Content-Type"; - var contentTypeLowerCase = contentType.toLowerCase(); - var interceptors = this.interceptors; - var requestInterceptor = interceptors.request; - var responseInterceptor = interceptors.response; - var requestInterceptorHandler = requestInterceptor.handler; - var promise = new Promise(function (resolve, reject) { - if (utils.isObject(url)) { - options = url; - url = options.url; - } - options = options || {}; - options.headers = options.headers || {}; - - function isPromise(p) { - // some polyfill implementation of Promise may be not standard, - // so, we test by duck-typing - return p && p.then && p.catch; - } - - /** - * If the request/response interceptor has been locked, - * the new request/response will enter a queue. otherwise, it will be performed directly. - * @param [promise] if the promise exist, means the interceptor is locked. - * @param [callback] - */ - function enqueueIfLocked(promise, callback) { - if (promise) { - promise.then(function () { - callback(); - }); - } else { - callback(); - } - } - - // make the http request - function makeRequest(options) { - data = options.body; - // Normalize the request url - url = utils.trim(options.url); - var baseUrl = utils.trim(options.baseURL || ""); - if (!url && isBrowser && !baseUrl) { url = location.href; } - if (url.indexOf("http") !== 0) { - var isAbsolute = url[0] === "/"; - if (!baseUrl && isBrowser) { - var arr = location.pathname.split("/"); - arr.pop(); - baseUrl = location.protocol + "//" + location.host + (isAbsolute ? "" : arr.join("/")); - } - if (baseUrl[baseUrl.length - 1] !== "/") { - baseUrl += "/"; - } - url = baseUrl + (isAbsolute ? url.substr(1) : url); - if (isBrowser) { - - // Normalize the url which contains the ".." or ".", such as - // "http://xx.com/aa/bb/../../xx" to "http://xx.com/xx" . - var t = document.createElement("a"); - t.href = url; - url = t.href; - } - } - - var responseType = utils.trim(options.responseType || ""); - var needQuery = ["GET", "HEAD", "DELETE", "OPTION"].indexOf(options.method) !== -1; - var dataType = utils.type(data); - var params = options.params || {}; - - // merge url params when the method is "GET" (data is object) - if (needQuery && dataType === "object") { - params = utils.merge(data, params); - } - // encode params to String - params = utils.formatParams(params); - - // save url params - var _params = []; - if (params) { - _params.push(params); - } - // Add data to url params when the method is "GET" (data is String) - if (needQuery && data && dataType === "string") { - _params.push(data); - } - - // make the final url - if (_params.length > 0) { - url += (url.indexOf("?") === -1 ? "?" : "&") + _params.join("&"); - } - - engine.open(options.method, url); - - // try catch for ie >=9 - try { - engine.withCredentials = !!options.withCredentials; - engine.timeout = options.timeout || 0; - if (responseType !== "stream") { - engine.responseType = responseType; - } - } catch (e) {} - - var customContentType = options.headers[contentType] || options.headers[contentTypeLowerCase]; - - // default content type - var _contentType = "application/x-www-form-urlencoded"; - // If the request data is json object, transforming it to json string, - // and set request content-type to "json". In browser, the data will - // be sent as RequestBody instead of FormData - if (utils.trim((customContentType || "").toLowerCase()) === _contentType) { - data = utils.formatParams(data); - } else if (!utils.isFormData(data) && ["object", "array"].indexOf(utils.type(data)) !== -1) { - _contentType = 'application/json;charset=utf-8'; - data = JSON.stringify(data); - } - //If user doesn't set content-type, set default. - if (!(customContentType || needQuery)) { - options.headers[contentType] = _contentType; - } - - for (var k in options.headers) { - if (k === contentType && utils.isFormData(data)) { - // Delete the content-type, Let the browser set it - delete options.headers[k]; - } else { - try { - // In browser environment, some header fields are readonly, - // write will cause the exception . - engine.setRequestHeader(k, options.headers[k]); - } catch (e) {} - } - } - - function onresult(handler, data, type) { - enqueueIfLocked(responseInterceptor.p, function () { - if (handler) { - //如果失败,添加请求信息 - if (type) { - data.request = options; - } - var ret = handler.call(responseInterceptor, data, Promise); - data = ret === undefined ? data : ret; - } - if (!isPromise(data)) { - data = Promise[type === 0 ? "resolve" : "reject"](data); - } - data.then(function (d) { - resolve(d); - }).catch(function (e) { - reject(e); - }); - }); - } - - function onerror(e) { - e.engine = engine; - onresult(responseInterceptor.onerror, e, -1); - } - - function Err(msg, status) { - this.message = msg; - this.status = status; - } - - engine.onload = function () { - try { - // The xhr of IE9 has not response field - var response = engine.response || engine.responseText; - if (response && options.parseJson && (engine.getResponseHeader(contentType) || "").indexOf("json") !== -1 - // Some third engine implementation may transform the response text to json object automatically, - // so we should test the type of response before transforming it - && !utils.isObject(response)) { - response = JSON.parse(response); - } - - var headers = engine.responseHeaders; - // In browser - if (!headers) { - headers = {}; - var items = (engine.getAllResponseHeaders() || "").split("\r\n"); - items.pop(); - items.forEach(function (e) { - if (!e) { return; } - var key = e.split(":")[0]; - headers[key] = engine.getResponseHeader(key); - }); - } - var status = engine.status; - var statusText = engine.statusText; - var _data = { data: response, headers: headers, status: status, statusText: statusText }; - // The _response filed of engine is set in adapter which be called in engine-wrapper.js - utils.merge(_data, engine._response); - if (status >= 200 && status < 300 || status === 304) { - _data.engine = engine; - _data.request = options; - onresult(responseInterceptor.handler, _data, 0); - } else { - var e = new Err(statusText, status); - e.response = _data; - onerror(e); - } - } catch (e) { - onerror(new Err(e.msg, engine.status)); - } - }; - - engine.onerror = function (e) { - onerror(new Err(e.msg || "Network Error", 0)); - }; - - engine.ontimeout = function () { - onerror(new Err("timeout [ " + engine.timeout + "ms ]", 1)); - }; - engine._options = options; - setTimeout(function () { - engine.send(needQuery ? null : data); - }, 0); - } - - enqueueIfLocked(requestInterceptor.p, function () { - utils.merge(options, JSON.parse(JSON.stringify(_this.config))); - var headers = options.headers; - headers[contentType] = headers[contentType] || headers[contentTypeLowerCase] || ""; - delete headers[contentTypeLowerCase]; - options.body = data || options.body; - url = utils.trim(url || ""); - options.method = options.method.toUpperCase(); - options.url = url; - var ret = options; - if (requestInterceptorHandler) { - ret = requestInterceptorHandler.call(requestInterceptor, options, Promise) || options; - } - if (!isPromise(ret)) { - ret = Promise.resolve(ret); - } - ret.then(function (d) { - //if options continue - if (d === options) { - makeRequest(d); - } else { - resolve(d); - } - }, function (err) { - reject(err); - }); - }); - }); - promise.engine = engine; - return promise; - } - }, { - key: "all", - value: function all(promises) { - return Promise.all(promises); - } - }, { - key: "spread", - value: function spread(callback) { - return function (arr) { - return callback.apply(null, arr); - }; - } - }]); - - return Fly; - }(); - - //For typeScript - - - Fly.default = Fly; - - ["get", "post", "put", "patch", "head", "delete"].forEach(function (e) { - Fly.prototype[e] = function (url, data, option) { - return this.request(url, data, utils.merge({ method: e }, option)); - }; - }); - ["lock", "unlock", "clear"].forEach(function (e) { - Fly.prototype[e] = function () { - this.interceptors.request[e](); - }; - }); - module.exports = Fly; - - /***/ }) - /******/ ]); - }); - }); - - var Fly = unwrapExports(fly); - - // the core stuff to id if it's calling with jsonql - var DATA_KEY = 'data'; - var ERROR_KEY = 'error'; - - var JSONQL_PATH = 'jsonql'; - // according to the json query spec - var CONTENT_TYPE = 'application/vnd.api+json'; - var CHARSET = 'charset=utf-8'; - var DEFAULT_HEADER = { - 'Accept': CONTENT_TYPE, - 'Content-Type': [ CONTENT_TYPE, CHARSET ].join(';') - }; - - // export const INDEX = 'index'; use INDEX_KEY instead - var DEFAULT_TYPE = 'any'; - - // @TODO remove this is not in use - // export const CLIENT_CONFIG_FILE = '.clients.json'; - // export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js'; - // type of resolvers - var QUERY_NAME = 'query'; - var MUTATION_NAME = 'mutation'; - var SOCKET_NAME = 'socket'; - // for calling the mutation - var PAYLOAD_PARAM_NAME = 'payload'; // @TODO shortern them - var CONDITION_PARAM_NAME = 'condition'; - var QUERY_ARG_NAME = 'args'; - var TIMESTAMP_PARAM_NAME = 'TS'; - // new jsonp - var JSONP_CALLBACK_NAME = 'jsonqlJsonpCallback'; - - // methods allow - var API_REQUEST_METHODS = ['POST', 'PUT']; - // for contract-cli - var KEY_WORD = 'continue'; - - var TYPE_KEY = 'type'; - var OPTIONAL_KEY = 'optional'; - var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word - var ARGS_KEY = 'args'; - var CHECKER_KEY = 'checker'; - var ALIAS_KEY = 'alias'; - var CHECKED_KEY = '__checked__'; - var LOGIN_NAME = 'login'; - var ISSUER_NAME = LOGIN_NAME; // legacy issue need to replace them later - var LOGOUT_NAME = 'logout'; - - var AUTH_HEADER = 'Authorization'; - var BEARER = 'Bearer'; - - // for client use @TODO need to clean this up some of them are not in use - var CREDENTIAL_STORAGE_KEY = 'jsonqlcredential'; - var CLIENT_STORAGE_KEY = 'jsonqlstore'; - var CLIENT_AUTH_KEY = 'jsonqlauthkey'; - // contract key - var CONTRACT_KEY_NAME = 'X-JSONQL-CV-KEY'; - var SHOW_CONTRACT_DESC_PARAM = {desc: 'y'}; - - var OR_SEPERATOR = '|'; - - var STRING_TYPE = 'string'; - var BOOLEAN_TYPE = 'boolean'; - var ARRAY_TYPE = 'array'; - var OBJECT_TYPE = 'object'; - - var NUMBER_TYPE = 'number'; - var ARRAY_TYPE_LFT = 'array.<'; - var ARRAY_TYPE_RGT = '>'; - - var NO_ERROR_MSG$1 = 'No message'; - var NO_STATUS_CODE = -1; - var ON_RESULT_PROP_NAME = 'onResult'; - var ON_ERROR_PROP_NAME = 'onError'; - var HSA_ALGO = 'HS256'; - - /** - * 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; - - 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$1 = root.Symbol; - - /** 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$1 ? Symbol$1.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$1 ? Symbol$1.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); - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** Built-in value references. */ - var getPrototype = overArg(Object.getPrototypeOf, Object); - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @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 objectTag = '[object Object]'; - - /** Used for built-in method references. */ - var funcProto = Function.prototype, - objectProto$2 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty$1.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; - } - - /** - * 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; - } - - /** `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$1 ? Symbol$1.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(''); - } - - // bunch of generic helpers - - /** - * DIY in Array - * @param {array} arr to check from - * @param {*} value to check against - * @return {boolean} true on found - */ - var inArray = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; - - // quick and dirty to turn non array to array - var toArray = function (arg) { return isArray(arg) ? arg : [arg]; }; - - /** - * @param {object} obj for search - * @param {string} key target - * @return {boolean} true on success - */ - var isObjectHasKey = function(obj, key) { - try { - var keys = Object.keys(obj); - return inArray(keys, key) - } catch(e) { - // @BUG when the obj is not an OBJECT we got some weird output - return false; - /* - console.info('obj', obj) - console.error(e) - throw new Error(e) - */ - } - }; - - /** - * create a event name - * @param {string[]} args - * @return {string} event name for use - */ - var createEvt = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return args.join('_'); - }; - - // just a simple util method to return the error based on the status code - /** - * @param {number} statusCode to check - * @param {boolean} contract if this is a contract call or not - * @return {string} the error name - */ - function getErrorByStatus(statusCode, contract) { - if ( contract === void 0 ) contract = false; - - switch (statusCode) { - case 401: - return contract ? 'JsonqlContractAuthError' : 'JsonqlAuthorisationError'; - case 403: - return 'JsonqlForbiddenError'; - case 404: - return 'JsonqlResolverNotFoundError'; - case 406: - return 'Jsonql406Error'; - case 500: - return 'Jsonql500Error'; - default: - return 'JsonqlError'; - } - } - - /** - * This is a custom error to throw when server throw a 406 - * 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 Jsonql406Error = /*@__PURE__*/(function (Error) { - function Jsonql406Error() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - // We can't access the static name from an instance - // but we can do it like this - this.className = Jsonql406Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql406Error); - } - } - - if ( Error ) Jsonql406Error.__proto__ = Error; - Jsonql406Error.prototype = Object.create( Error && Error.prototype ); - Jsonql406Error.prototype.constructor = Jsonql406Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 406; - }; - - staticAccessors.name.get = function () { - return 'Jsonql406Error'; - }; - - Object.defineProperties( Jsonql406Error, staticAccessors ); - - return Jsonql406Error; - }(Error)); - - /** - * This is a custom error to throw when server throw a 500 - * 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 Jsonql500Error = /*@__PURE__*/(function (Error) { - function Jsonql500Error() { - 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 = Jsonql500Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql500Error); - } - } - - if ( Error ) Jsonql500Error.__proto__ = Error; - Jsonql500Error.prototype = Object.create( Error && Error.prototype ); - Jsonql500Error.prototype.constructor = Jsonql500Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'Jsonql500Error'; - }; - - Object.defineProperties( Jsonql500Error, staticAccessors ); - - return Jsonql500Error; - }(Error)); - - /** - * This is a custom error to throw when pass credential but fail - * 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 JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { - function JsonqlAuthorisationError() { - 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 = JsonqlAuthorisationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlAuthorisationError); - } - } - - if ( Error ) JsonqlAuthorisationError.__proto__ = Error; - JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); - JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlAuthorisationError'; - }; - - Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); - - return JsonqlAuthorisationError; - }(Error)); - - /** - * This is a custom error when not supply the credential and try to get contract - * 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 JsonqlContractAuthError = /*@__PURE__*/(function (Error) { - function JsonqlContractAuthError() { - 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 = JsonqlContractAuthError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlContractAuthError); - } - } - - if ( Error ) JsonqlContractAuthError.__proto__ = Error; - JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); - JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlContractAuthError'; - }; - - Object.defineProperties( JsonqlContractAuthError, staticAccessors ); - - return JsonqlContractAuthError; - }(Error)); - - /** - * This is a custom error to throw when the resolver throw error and capture inside the middleware - * 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 JsonqlResolverAppError = /*@__PURE__*/(function (Error) { - function JsonqlResolverAppError() { - 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 = JsonqlResolverAppError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverAppError); - } - } - - if ( Error ) JsonqlResolverAppError.__proto__ = Error; - JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverAppError'; - }; - - Object.defineProperties( JsonqlResolverAppError, staticAccessors ); - - return JsonqlResolverAppError; - }(Error)); - - /** - * This is a custom error to throw when could not find the resolver - * 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 JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { - function JsonqlResolverNotFoundError() { - 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 = JsonqlResolverNotFoundError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverNotFoundError); - } - } - - if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; - JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 404; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverNotFoundError'; - }; - - Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); - - return JsonqlResolverNotFoundError; - }(Error)); - - // this get throw from within the checkOptions when run through the enum failed - var JsonqlEnumError = /*@__PURE__*/(function (Error) { - function JsonqlEnumError() { - 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 = JsonqlEnumError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlEnumError); - } - } - - if ( Error ) JsonqlEnumError.__proto__ = Error; - JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); - JsonqlEnumError.prototype.constructor = JsonqlEnumError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlEnumError'; - }; - - Object.defineProperties( JsonqlEnumError, staticAccessors ); - - return JsonqlEnumError; - }(Error)); - - // this will throw from inside the checkOptions - var JsonqlTypeError = /*@__PURE__*/(function (Error) { - function JsonqlTypeError() { - 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 = JsonqlTypeError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlTypeError); - } - } - - if ( Error ) JsonqlTypeError.__proto__ = Error; - JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); - JsonqlTypeError.prototype.constructor = JsonqlTypeError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlTypeError'; - }; - - Object.defineProperties( JsonqlTypeError, staticAccessors ); - - return JsonqlTypeError; - }(Error)); - - // allow supply a custom checker function - // if that failed then we throw this error - var JsonqlCheckerError = /*@__PURE__*/(function (Error) { - function JsonqlCheckerError() { - 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 = JsonqlCheckerError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlCheckerError); - } - } - - if ( Error ) JsonqlCheckerError.__proto__ = Error; - JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); - JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlCheckerError'; - }; - - Object.defineProperties( JsonqlCheckerError, staticAccessors ); - - return JsonqlCheckerError; - }(Error)); - - // custom validation error class - // when validaton failed - var JsonqlValidationError = /*@__PURE__*/(function (Error) { - function JsonqlValidationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlValidationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlValidationError); - } - } - - if ( Error ) JsonqlValidationError.__proto__ = Error; - JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); - JsonqlValidationError.prototype.constructor = JsonqlValidationError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlValidationError'; - }; - - Object.defineProperties( JsonqlValidationError, staticAccessors ); - - return JsonqlValidationError; - }(Error)); - - /** - * This is a custom error to throw whenever a error happen inside the jsonql - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlError = /*@__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)); - - // this is from an example from Koa team to use for internal middleware ctx.throw - // but after the test the res.body part is unable to extract the required data - // I keep this one here for future reference - - var JsonqlServerError = /*@__PURE__*/(function (Error) { - function JsonqlServerError(statusCode, message) { - Error.call(this, message); - this.statusCode = statusCode; - this.className = JsonqlServerError.name; - } - - if ( Error ) JsonqlServerError.__proto__ = Error; - JsonqlServerError.prototype = Object.create( Error && Error.prototype ); - JsonqlServerError.prototype.constructor = JsonqlServerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlServerError'; - }; - - Object.defineProperties( JsonqlServerError, staticAccessors ); - - return JsonqlServerError; - }(Error)); - - // server side - - var errors = /*#__PURE__*/Object.freeze({ - __proto__: null, - Jsonql406Error: Jsonql406Error, - Jsonql500Error: Jsonql500Error, - JsonqlAuthorisationError: JsonqlAuthorisationError, - JsonqlContractAuthError: JsonqlContractAuthError, - JsonqlResolverAppError: JsonqlResolverAppError, - JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, - JsonqlEnumError: JsonqlEnumError, - JsonqlTypeError: JsonqlTypeError, - JsonqlCheckerError: JsonqlCheckerError, - JsonqlValidationError: JsonqlValidationError, - JsonqlError: JsonqlError, - JsonqlServerError: JsonqlServerError - }); - - // this will add directly to the then call in each http call - var JsonqlError$1 = JsonqlError; - - /** - * We can not just check something like result.data what if the result if false? - * @param {object} obj the result object - * @param {string} key we want to check if its exist or not - * @return {boolean} true on found - */ - var isObjectHasKey$1 = function (obj, key) { - var keys = Object.keys(obj); - return !!keys.filter(function (k) { return key === k; }).length; - }; - - /** - * It will ONLY have our own jsonql specific implement check - * @param {object} result the server return result - * @return {object} this will just throw error - */ - function clientErrorsHandler(result) { - if (isObjectHasKey$1(result, 'error')) { - var error = result.error; - var className = error.className; - var name = error.name; - var errorName = className || name; - // just throw the whole thing back - var msg = error.message || NO_ERROR_MSG$1; - var detail = error.detail || error; - if (errorName && errors[errorName]) { - throw new errors[className](msg, detail) - } - throw new JsonqlError$1(msg, detail) - } - // pass through to the next - return result; - } - - // get error name by instance - var UNKNOWN_ERROR = 'unknown'; - - /** - * @param {array} errs list of errors to compare from - * @param {object} e the error captured - * @return {array} filtered with name as value - */ - function mapErrToName(errs, e) { - return errs.filter(function (err) { return e instanceof err; }) - .map(function (err) { return err.name; }) - } - - /** - * @param {array} errs list of errors to compare from - * @param {object} e the error captured - * @return {string} name of the error object - */ - function getErrorNameByInstance(errs, e) { - var error = mapErrToName(errs, e); - return error.length ? error[0] : UNKNOWN_ERROR - } - - /** - * the same as above with a default JsonqlError as default - * @param {array} errs same - * @param {object} e error itself - * @return {string} the name of the error - */ - function getErrorNameByInstanceWithDefault(errs, e) { - var name = getErrorNameByInstance(errs, e); - return name === UNKNOWN_ERROR ? 'JsonqlError' : name; - } - - /** - * this will put into generator call at the very end and catch - * the error throw from inside then throw again - * this is necessary because we split calls inside and the throw - * will not reach the actual client unless we do it this way - * @param {object} e Error - * @return {void} just throw - */ - function finalCatch(e) { - // this is a hack to get around the validateAsync not actually throw error - // instead it just rejected it with the array of failed parameters - if (Array.isArray(e)) { - // if we want the message then I will have to create yet another function - // to wrap this function to provide the name prop - throw new JsonqlValidationError('', e) - } - var msg = e.message || NO_ERROR_MSG$1; - var detail = e.detail || e; - switch (true) { - case e instanceof Jsonql406Error: - throw new Jsonql406Error(msg, detail) - case e instanceof Jsonql500Error: - throw new Jsonql500Error(msg, detail) - case e instanceof JsonqlAuthorisationError: - throw new JsonqlAuthorisationError(msg, detail) - case e instanceof JsonqlContractAuthError: - throw new JsonqlContractAuthError(msg, detail) - case e instanceof JsonqlResolverAppError: - throw new JsonqlResolverAppError(msg, detail) - case e instanceof JsonqlResolverNotFoundError: - throw new JsonqlResolverNotFoundError(msg, detail) - case e instanceof JsonqlEnumError: - throw new JsonqlEnumError(msg, detail) - case e instanceof JsonqlTypeError: - throw new JsonqlTypeError(msg, detail) - case e instanceof JsonqlCheckerError: - throw new JsonqlCheckerError(msg, detail) - case e instanceof JsonqlValidationError: - throw new JsonqlValidationError(msg, detail) - case e instanceof JsonqlServerError: - throw new JsonqlServerError(msg, detail) - default: - throw new JsonqlError(msg, detail) - } - } - - // jsonql-errors main interface - var JSONQL_ERRORS_INFO = '__PLACEHOLDER__'; - - var errors$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - JSONQL_ERRORS_INFO: JSONQL_ERRORS_INFO, - UNKNOWN_ERROR: UNKNOWN_ERROR, - getErrorByStatus: getErrorByStatus, - clientErrorsHandler: clientErrorsHandler, - finalCatch: finalCatch, - getErrorNameByInstance: getErrorNameByInstance, - getErrorNameByInstanceWithDefault: getErrorNameByInstanceWithDefault, - Jsonql406Error: Jsonql406Error, - Jsonql500Error: Jsonql500Error, - JsonqlAuthorisationError: JsonqlAuthorisationError, - JsonqlContractAuthError: JsonqlContractAuthError, - JsonqlResolverAppError: JsonqlResolverAppError, - JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, - JsonqlEnumError: JsonqlEnumError, - JsonqlTypeError: JsonqlTypeError, - JsonqlCheckerError: JsonqlCheckerError, - JsonqlValidationError: JsonqlValidationError, - JsonqlError: JsonqlError, - JsonqlServerError: JsonqlServerError - }); - - /** - * Check several parameter that there is something in the param - * @param {*} param input - * @return {boolean} - */ - var isNotEmpty = function (a) { - if (isArray(a)) { - return true; - } - return a !== undefined && a !== null && trim(a) !== ''; - }; - - /** `Object#toString` result references. */ - var numberTag = '[object Number]'; - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - /** `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); - } - - // validator numbers - /** - * @2015-05-04 found a problem if the value is a number like string - * it will pass, so add a chck if it's string before we pass to next - * @param {number} value expected value - * @return {boolean} true if OK - */ - var checkIsNumber = function(value) { - return isString(value) ? false : !isNaN( parseFloat(value) ) - }; - - // validate string type - /** - * @param {string} value expected value - * @return {boolean} true if OK - */ - var checkIsString = function(value) { - return (trim(value) !== '') ? isString(value) : false; - }; - - // check for boolean - - /** - * @param {boolean} value expected - * @return {boolean} true if OK - */ - var checkIsBoolean = function(value) { - return value !== null && value !== undefined && typeof value === 'boolean' - }; - - // validate any thing only check if there is something - - /** - * @param {*} value the value - * @param {boolean} [checkNull=true] strict check if there is null value - * @return {boolean} true is OK - */ - var checkIsAny = function(value, checkNull) { - if ( checkNull === void 0 ) checkNull = true; - - if (value !== undefined && value !== '' && trim(value) !== '') { - if (checkNull === false || (checkNull === true && value !== null)) { - return true; - } - } - return false; - }; - - // Good practice rule - No magic number - - var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; - var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; - var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; - // @TODO the jsdoc return array. and we should also allow array syntax - var DEFAULT_TYPE$1 = DEFAULT_TYPE; - var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; - var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; - - var TYPE_KEY$1 = TYPE_KEY; - var OPTIONAL_KEY$1 = OPTIONAL_KEY; - var ENUM_KEY$1 = ENUM_KEY; - var ARGS_KEY$1 = ARGS_KEY; - var CHECKER_KEY$1 = CHECKER_KEY; - var ALIAS_KEY$1 = ALIAS_KEY; - - var ARRAY_TYPE$1 = ARRAY_TYPE; - var OBJECT_TYPE$1 = OBJECT_TYPE; - var STRING_TYPE$1 = STRING_TYPE; - var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; - var NUMBER_TYPE$1 = NUMBER_TYPE; - var KEY_WORD$1 = KEY_WORD; - var OR_SEPERATOR$1 = OR_SEPERATOR; - - // not actually in use - // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; - - // primitive types - - /** - * this is a wrapper method to call different one based on their type - * @param {string} type to check - * @return {function} a function to handle the type - */ - var combineFn = function(type) { - switch (type) { - case NUMBER_TYPE$1: - return checkIsNumber; - case STRING_TYPE$1: - return checkIsString; - case BOOLEAN_TYPE$1: - return checkIsBoolean; - default: - return checkIsAny; - } - }; - - // validate array type - - /** - * @param {array} value expected - * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well - * @return {boolean} true if OK - */ - var checkIsArray = function(value, type) { - if ( type === void 0 ) type=''; - - if (isArray(value)) { - if (type === '' || trim(type)==='') { - return true; - } - // we test it in reverse - // @TODO if the type is an array (OR) then what? - // we need to take into account this could be an array - var c = value.filter(function (v) { return !combineFn(type)(v); }); - return !(c.length > 0) - } - return false; - }; - - /** - * check if it matches the array. pattern - * @param {string} type - * @return {boolean|array} false means NO, always return array - */ - var isArrayLike = function(type) { - // @TODO could that have something like array<> instead of array.<>? missing the dot? - // because type script is Array without the dot - if (type.indexOf(ARRAY_TYPE_LFT$1) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { - var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); - if (_type.indexOf(OR_SEPERATOR$1)) { - return _type.split(OR_SEPERATOR$1) - } - return [_type] - } - return false; - }; - - /** - * we might encounter something like array. then we need to take it apart - * @param {object} p the prepared object for processing - * @param {string|array} type the type came from - * @return {boolean} for the filter to operate on - */ - var arrayTypeHandler = function(p, type) { - var arg = p.arg; - // need a special case to handle the OR type - // we need to test the args instead of the type(s) - if (type.length > 1) { - return !arg.filter(function (v) { return ( - !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) - ); }).length; - } - // type is array so this will be or! - return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length; - }; - - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]'; - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** Used for built-in method references. */ - var objectProto$3 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - - /** Built-in value references. */ - var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER$1 = 9007199254740991; - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; - } - - /** `Object#toString` result references. */ - var argsTag$1 = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - mapTag = '[object Map]', - numberTag$1 = '[object Number]', - objectTag$1 = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag$1 = '[object String]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag$1] = - typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag$1] = - typedArrayTags[weakMapTag] = false; - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - - /** Detect free variable `exports`. */ - var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports$1 && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - - /** Used for built-in method references. */ - var objectProto$4 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$3 = objectProto$4.hasOwnProperty; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$3.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$5 = Object.prototype; - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; - - return value === proto; - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeKeys = overArg(Object.keys, Object); - - /** Used for built-in method references. */ - var objectProto$6 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$4 = objectProto$6.hasOwnProperty; - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$4.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** `Object#toString` result references. */ - var asyncTag = '[object AsyncFunction]', - funcTag$1 = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike$1(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype; - - /** Built-in value references. */ - var splice = arrayProto.splice; - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** Used for built-in method references. */ - var funcProto$1 = Function.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$1 = funcProto$1.toString; - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString$1.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used for built-in method references. */ - var funcProto$2 = Function.prototype, - objectProto$7 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$2 = funcProto$2.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$5 = objectProto$7.hasOwnProperty; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString$2.call(hasOwnProperty$5).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /* Built-in method references that are verified to be native. */ - var Map$1 = getNative(root, 'Map'); - - /* Built-in method references that are verified to be native. */ - var nativeCreate = getNative(Object, 'create'); - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used for built-in method references. */ - var objectProto$8 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$6 = objectProto$8.hasOwnProperty; - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty$6.call(data, key) ? data[key] : undefined; - } - - /** Used for built-in method references. */ - var objectProto$9 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$7 = objectProto$9.hasOwnProperty; - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key); - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; - return this; - } - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map$1 || ListCache), - 'string': new Hash - }; - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; - - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED$2); - return this; - } - - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } - - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } - - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } - - /** Built-in value references. */ - var Uint8Array$1 = root.Uint8Array; - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$1 = 1, - COMPARE_UNORDERED_FLAG$1 = 2; - - /** `Object#toString` result references. */ - var boolTag$1 = '[object Boolean]', - dateTag$1 = '[object Date]', - errorTag$1 = '[object Error]', - mapTag$1 = '[object Map]', - numberTag$2 = '[object Number]', - regexpTag$1 = '[object RegExp]', - setTag$1 = '[object Set]', - stringTag$2 = '[object String]', - symbolTag$1 = '[object Symbol]'; - - var arrayBufferTag$1 = '[object ArrayBuffer]', - dataViewTag$1 = '[object DataView]'; - - /** Used to convert symbols to primitives and strings. */ - var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined, - symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag$1: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag$1: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array$1(object), new Uint8Array$1(other))) { - return false; - } - return true; - - case boolTag$1: - case dateTag$1: - case numberTag$2: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag$1: - return object.name == other.name && object.message == other.message; - - case regexpTag$1: - case stringTag$2: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag$1: - var convert = mapToArray; - - case setTag$1: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG$1; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag$1: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** Used for built-in method references. */ - var objectProto$a = Object.prototype; - - /** Built-in value references. */ - var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable$1.call(object, symbol); - }); - }; - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$2 = 1; - - /** Used for built-in method references. */ - var objectProto$b = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$8 = objectProto$b.hasOwnProperty; - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) { - return false; - } - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'); - - /* Built-in method references that are verified to be native. */ - var Promise$1 = getNative(root, 'Promise'); - - /* Built-in method references that are verified to be native. */ - var Set$1 = getNative(root, 'Set'); - - /* Built-in method references that are verified to be native. */ - var WeakMap$1 = getNative(root, 'WeakMap'); - - /** `Object#toString` result references. */ - var mapTag$2 = '[object Map]', - objectTag$2 = '[object Object]', - promiseTag = '[object Promise]', - setTag$2 = '[object Set]', - weakMapTag$1 = '[object WeakMap]'; - - var dataViewTag$2 = '[object DataView]'; - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map$1), - promiseCtorString = toSource(Promise$1), - setCtorString = toSource(Set$1), - weakMapCtorString = toSource(WeakMap$1); - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$2) || - (Map$1 && getTag(new Map$1) != mapTag$2) || - (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || - (Set$1 && getTag(new Set$1) != setTag$2) || - (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag$2 ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag$2; - case mapCtorString: return mapTag$2; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag$2; - case weakMapCtorString: return weakMapTag$1; - } - } - return result; - }; - } - - var getTag$1 = getTag; - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$3 = 1; - - /** `Object#toString` result references. */ - var argsTag$2 = '[object Arguments]', - arrayTag$1 = '[object Array]', - objectTag$3 = '[object Object]'; - - /** Used for built-in method references. */ - var objectProto$c = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$9 = objectProto$c.hasOwnProperty; - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag$1 : getTag$1(object), - othTag = othIsArr ? arrayTag$1 : getTag$1(other); - - objTag = objTag == argsTag$2 ? objectTag$3 : objTag; - othTag = othTag == argsTag$2 ? objectTag$3 : othTag; - - var objIsObj = objTag == objectTag$3, - othIsObj = othTag == objectTag$3, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { - var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$4 = 1, - COMPARE_UNORDERED_FLAG$2 = 2; - - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } - - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - - /** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } - - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } - - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /** Error message constants. */ - var FUNC_ERROR_TEXT = 'Expected a function'; - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** Used to match property names within property paths. */ - var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** Used as references for various `Number` constants. */ - var INFINITY$1 = 1 / 0; - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; - } - - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$5 = 1, - COMPARE_UNORDERED_FLAG$3 = 2; - - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); - }; - } - - /** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ - function identity(value) { - return value; - } - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - - /** - * Creates a function that returns the value at `path` of a given object. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - * @example - * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; - * - * _.map(objects, _.property('a.b')); - * // => [2, 1] - * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] - */ - function property(path) { - return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); - } - - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } - - // validate object type - /** - * @TODO if provide with the keys then we need to check if the key:value type as well - * @param {object} value expected - * @param {array} [keys=null] if it has the keys array to compare as well - * @return {boolean} true if OK - */ - var checkIsObject = function(value, keys) { - if ( keys === void 0 ) keys=null; - - if (isPlainObject(value)) { - if (!keys) { - return true; - } - if (checkIsArray(keys)) { - // please note we DON'T care if some is optional - // plese refer to the contract.json for the keys - return !keys.filter(function (key) { - var _value = value[key.name]; - return !(key.type.length > key.type.filter(function (type) { - var tmp; - if (_value !== undefined) { - if ((tmp = isArrayLike(type)) !== false) { - return !arrayTypeHandler({arg: _value}, tmp) - // return tmp.filter(t => !checkIsArray(_value, t)).length; - // @TODO there might be an object within an object with keys as well :S - } - return !combineFn(type)(_value) - } - return true; - }).length) - }).length; - } - } - return false; - }; - - /** - * fold this into it's own function to handler different object type - * @param {object} p the prepared object for process - * @return {boolean} - */ - var objectTypeHandler = function(p) { - var arg = p.arg; - var param = p.param; - var _args = [arg]; - if (Array.isArray(param.keys) && param.keys.length) { - _args.push(param.keys); - } - // just simple check - return Reflect.apply(checkIsObject, null, _args) - }; - - // move the index.js code here that make more sense to find where things are - // import debug from 'debug' - // const debugFn = debug('jsonql-params-validator:validator') - // also export this for use in other places - - /** - * We need to handle those optional parameter without a default value - * @param {object} params from contract.json - * @return {boolean} for filter operation false is actually OK - */ - var optionalHandler = function( params ) { - var arg = params.arg; - var param = params.param; - if (isNotEmpty(arg)) { - // debug('call optional handler', arg, params); - // loop through the type in param - return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } - ).length) - } - return false; - }; - - /** - * actually picking the validator - * @param {*} type for checking - * @param {*} value for checking - * @return {boolean} true on OK - */ - var validateHandler = function(type, value) { - var tmp; - switch (true) { - case type === OBJECT_TYPE$1: - // debugFn('call OBJECT_TYPE') - return !objectTypeHandler(value) - case type === ARRAY_TYPE$1: - // debugFn('call ARRAY_TYPE') - return !checkIsArray(value.arg) - // @TODO when the type is not present, it always fall through here - // so we need to find a way to actually pre-check the type first - // AKA check the contract.json map before running here - case (tmp = isArrayLike(type)) !== false: - // debugFn('call ARRAY_LIKE: %O', value) - return !arrayTypeHandler(value, tmp) - default: - return !combineFn(type)(value.arg) - } - }; - - /** - * it get too longer to fit in one line so break it out from the fn below - * @param {*} arg value - * @param {object} param config - * @return {*} value or apply default value - */ - var getOptionalValue = function(arg, param) { - if (arg !== undefined) { - return arg; - } - return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null) - }; - - /** - * padding the arguments with defaultValue if the arguments did not provide the value - * this will be the name export - * @param {array} args normalized arguments - * @param {array} params from contract.json - * @return {array} merge the two together - */ - var normalizeArgs = function(args, params) { - // first we should check if this call require a validation at all - // there will be situation where the function doesn't need args and params - if (!checkIsArray(params)) { - // debugFn('params value', params) - throw new JsonqlError(PARAMS_NOT_ARRAY_ERR) - } - if (params.length === 0) { - return []; - } - if (!checkIsArray(args)) { - throw new JsonqlError(ARGS_NOT_ARRAY_ERR) - } - // debugFn(args, params); - // fall through switch - switch(true) { - case args.length == params.length: // standard - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, - param: params[i] - } - ); }) - case params[0].variable === true: // using spread syntax - var type = params[0].type; - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, // keep the index for reference - param: params[i] || { type: type, name: '_' } - } - ); }) - // with optional defaultValue parameters - case args.length < params.length: - return params.map(function (param, i) { return ( - { - param: param, - index: i, - arg: getOptionalValue(args[i], param), - optional: param.optional || false - } - ); }) - // this one pass more than it should have anything after the args.length will be cast as any type - case args.length > params.length: - var ctn = params.length; - // this happens when we have those array. type - var _type = [ DEFAULT_TYPE$1 ]; - // we only looking at the first one, this might be a @BUG - /* - if ((tmp = isArrayLike(params[0].type[0])) !== false) { - _type = tmp; - } */ - // if we use the params as guide then the rest will get throw out - // which is not what we want, instead, anything without the param - // will get a any type and optional flag - return args.map(function (arg, i) { - var optional = i >= ctn ? true : !!params[i].optional; - var param = params[i] || { type: _type, name: ("_" + i) }; - return { - arg: optional ? getOptionalValue(arg, param) : arg, - index: i, - param: param, - optional: optional - } - }) - // @TODO find out if there is more cases not cover - default: // this should never happen - // debugFn('args', args) - // debugFn('params', params) - // this is unknown therefore we just throw it! - throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) - } - }; - - // what we want is after the validaton we also get the normalized result - // which is with the optional property if the argument didn't provide it - /** - * process the array of params back to their arguments - * @param {array} result the params result - * @return {array} arguments - */ - var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; - - /** - * validator main interface - * @param {array} args the arguments pass to the method call - * @param {array} params from the contract for that method - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {array} empty array on success, or failed parameter and reasons - */ - var validateSync = function(args, params, withResult) { - var obj; - - if ( withResult === void 0 ) withResult = false; - var cleanArgs = normalizeArgs(args, params); - var checkResult = cleanArgs.filter(function (p) { - // v1.4.4 this fixed the problem, the root level optional is from the last fn - if (p.optional === true || p.param.optional === true) { - return optionalHandler(p) - } - // because array of types means OR so if one pass means pass - return !(p.param.type.length > p.param.type.filter( - function (type) { return validateHandler(type, p); } - ).length) - }); - // using the same convention we been using all this time - return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) - }; - - /** - * A wrapper method that return promise - * @param {array} args arguments - * @param {array} params from contract.json - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {object} promise.then or catch - */ - var validateAsync = function(args, params, withResult) { - if ( withResult === void 0 ) withResult = false; - - return new Promise(function (resolver, rejecter) { - var result = validateSync(args, params, withResult); - if (withResult) { - return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) - : resolver(result[DATA_KEY]) - } - // the different is just in the then or catch phrase - return result.length ? rejecter(result) : resolver([]) - }) - }; - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** Detect free variable `exports`. */ - var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; - - /** Built-in value references. */ - var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, - allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** Built-in value references. */ - var objectCreate = Object.create; - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike$1(value); - } - - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; - } - - /** Used for built-in method references. */ - var objectProto$d = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$a = objectProto$d.hasOwnProperty; - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$a.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$e = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$b = objectProto$e.hasOwnProperty; - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty$b.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn(object) { - return isArrayLike$1(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } - - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeMax = Math.max; - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ - function constant(value) { - return function() { - return value; - }; - } - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeNow = Date.now; - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike$1(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - - /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; - } - - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; - } - - /** Error message constants. */ - var FUNC_ERROR_TEXT$1 = 'Expected a function'; - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT$1); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols$1 = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = baseIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } - - /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ - function omitBy(object, predicate) { - return pickBy(object, negate(baseIteratee(predicate))); - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } - - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ - function findKey(object, predicate) { - return baseFindKey(object, baseIteratee(predicate), baseForOwn); - } - - /** - * @param {array} arr Array for check - * @param {*} value target - * @return {boolean} true on successs - */ - var isInArray = function(arr, value) { - return !!arr.filter(function (a) { return a === value; }).length; - }; - - var isObjectHasKey$2 = function(obj, key) { - var keys = Object.keys(obj); - return isInArray(keys, key) - }; - - // just not to make my head hurt - var isEmpty = function (value) { return !isNotEmpty(value); }; - - /** - * Map the alias to their key then grab their value over - * @param {object} config the user supplied config - * @param {object} appProps the default option map - * @return {object} the config keys replaced with the appProps key by the ALIAS - */ - function mapAliasConfigKeys(config, appProps) { - // need to do two steps - // 1. take key with alias key - var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$1]; } ); - if (isEqual(aliasMap, {})) { - return config; - } - return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) - } - - /** - * We only want to run the valdiation against the config (user supplied) value - * but keep the defaultOptions untouch - * @param {object} config configuraton supplied by user - * @param {object} appProps the default options map - * @return {object} the pristine values that will add back to the final output - */ - function preservePristineValues(config, appProps) { - // @BUG this will filter out those that is alias key - // we need to first map the alias keys back to their full key - var _config = mapAliasConfigKeys(config, appProps); - // take the default value out - var pristineValues = mapValues( - omitBy(appProps, function (value, key) { return isObjectHasKey$2(_config, key); }), - function (value) { return value.args; } - ); - // for testing the value - var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !isObjectHasKey$2(_config, key); }); - // output - return { - pristineValues: pristineValues, - checkAgainstAppProps: checkAgainstAppProps, - config: _config // passing this correct values back - } - } - - /** - * This will take the value that is ONLY need to check - * @param {object} config that one - * @param {object} props map for creating checking - * @return {object} put that arg into the args - */ - function processConfigAction(config, props) { - // debugFn('processConfigAction', props) - // v.1.2.0 add checking if its mark optional and the value is empty then pass - return mapValues(props, function (value, key) { - var obj, obj$1; - - return ( - config[key] === undefined || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) - ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) - : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) - ); - } - ) - } - - /** - * Quick transform - * @TODO we should only validate those that is pass from the config - * and pass through those values that is from the defaultOptions - * @param {object} opts that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ - function prepareArgsForValidation(opts, appProps) { - var ref = preservePristineValues(opts, appProps); - var config = ref.config; - var pristineValues = ref.pristineValues; - var checkAgainstAppProps = ref.checkAgainstAppProps; - // output - return [ - processConfigAction(config, checkAgainstAppProps), - pristineValues - ] - } - - // breaking the whole thing up to see what cause the multiple calls issue - - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:options:validation') - - /** - * just make sure it returns an array to use - * @param {*} arg input - * @return {array} output - */ - var toArray$1 = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; - - /** - * DIY in array - * @param {array} arr to check against - * @param {*} value to check - * @return {boolean} true on OK - */ - var inArray$1 = function (arr, value) { return ( - !!arr.filter(function (v) { return v === value; }).length - ); }; - - /** - * break out to make the code easier to read - * @param {object} value to process - * @param {function} cb the validateSync - * @return {array} empty on success - */ - function validateHandler$1(value, cb) { - var obj; - - // cb is the validateSync methods - var args = [ - [ value[ARGS_KEY$1] ], - [( obj = {}, obj[TYPE_KEY$1] = toArray$1(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] - ]; - // debugFn('validateHandler', args) - return Reflect.apply(cb, null, args) - } - - /** - * Check against the enum value if it's provided - * @param {*} value to check - * @param {*} enumv to check against if it's not false - * @return {boolean} true on OK - */ - var enumHandler = function (value, enumv) { - if (checkIsArray(enumv)) { - return inArray$1(enumv, value) - } - return true; - }; - - /** - * Allow passing a function to check the value - * There might be a problem here if the function is incorrect - * and that will makes it hard to debug what is going on inside - * @TODO there could be a few feature add to this one under different circumstance - * @param {*} value to check - * @param {function} checker for checking - */ - var checkerHandler = function (value, checker) { - try { - return isFunction(checker) ? checker.apply(null, [value]) : false; - } catch (e) { - return false; - } - }; - - /** - * Taken out from the runValidaton this only validate the required values - * @param {array} args from the config2argsAction - * @param {function} cb validateSync - * @return {array} of configuration values - */ - function runValidationAction(cb) { - return function (value, key) { - // debugFn('runValidationAction', key, value) - if (value[KEY_WORD$1]) { - return value[ARGS_KEY$1] - } - var check = validateHandler$1(value, cb); - if (check.length) { - // log('runValidationAction', key, value) - throw new JsonqlTypeError(key, check) - } - if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { - // log(ENUM_KEY, value[ENUM_KEY]) - throw new JsonqlEnumError(key) - } - if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { - // log(CHECKER_KEY, value[CHECKER_KEY]) - throw new JsonqlCheckerError(key) - } - return value[ARGS_KEY$1] - } - } - - /** - * @param {object} args from the config2argsAction - * @param {function} cb validateSync - * @return {object} of configuration values - */ - function runValidation(args, cb) { - var argsForValidate = args[0]; - var pristineValues = args[1]; - // turn the thing into an array and see what happen here - // debugFn('_args', argsForValidate) - var result = mapValues(argsForValidate, runValidationAction(cb)); - return merge(result, pristineValues) - } - - // this is port back from the client to share across all projects - - /** - * @param {object} config user provide configuration option - * @param {object} appProps mutation configuration options - * @param {object} constProps the immutable configuration options - * @param {function} cb the validateSync method - * @return {object} Promise resolve merge config object - */ - function checkOptionsSync(config, appProps, constProps, cb) { - if ( config === void 0 ) config = {}; - - return merge( - runValidation( - prepareArgsForValidation(config, appProps), - cb - ), - constProps - ) - } - - // create function to construct the config entry so we don't need to keep building object - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:construct-config'); - /** - * @param {*} args value - * @param {string} type for value - * @param {boolean} [optional=false] - * @param {boolean|array} [enumv=false] - * @param {boolean|function} [checker=false] - * @return {object} config entry - */ - function constructConfig(args, type, optional, enumv, checker, alias) { - if ( optional === void 0 ) optional=false; - if ( enumv === void 0 ) enumv=false; - if ( checker === void 0 ) checker=false; - if ( alias === void 0 ) alias=false; - - var base = {}; - base[ARGS_KEY] = args; - base[TYPE_KEY] = type; - if (optional === true) { - base[OPTIONAL_KEY] = true; - } - if (checkIsArray(enumv)) { - base[ENUM_KEY] = enumv; - } - if (isFunction(checker)) { - base[CHECKER_KEY] = checker; - } - if (isString(alias)) { - base[ALIAS_KEY] = alias; - } - return base; - } - - // export also create wrapper methods - - /** - * This has a different interface - * @param {*} value to supply - * @param {string|array} type for checking - * @param {object} params to map against the config check - * @param {array} params.enumv NOT enum - * @param {boolean} params.optional false then nothing - * @param {function} params.checker need more work on this one later - * @param {string} params.alias mostly for cmd - */ - var createConfig = function (value, type, params) { - if ( params === void 0 ) params = {}; - - // Note the enumv not ENUM - // const { enumv, optional, checker, alias } = params; - // let args = [value, type, optional, enumv, checker, alias]; - var o = params[OPTIONAL_KEY]; - var e = params[ENUM_KEY]; - var c = params[CHECKER_KEY]; - var a = params[ALIAS_KEY]; - return constructConfig.apply(null, [value, type, o, e, c, a]) - }; - - // copy of above but it's sync - var checkConfig = function(validateSync) { - return function(config, appProps, constantProps) { - if ( constantProps === void 0 ) constantProps = {}; - - return checkOptionsSync(config, appProps, constantProps, validateSync) - } - }; - - // export - var isString$1 = checkIsString; - var isNumber$1 = checkIsNumber; - var validateAsync$1 = validateAsync; - - var createConfig$1 = createConfig; - var checkConfig$1 = checkConfig(validateSync); - - /** - * using just the map reduce to chain multiple functions together - * @param {function} mainFn the init function - * @param {array} moreFns as many as you want to take the last value and return a new one - * @return {function} accept value for the mainFn - */ - var chainFns = function (mainFn) { - var moreFns = [], len = arguments.length - 1; - while ( len-- > 0 ) moreFns[ len ] = arguments[ len + 1 ]; - - return ( - function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return ( - moreFns.reduce(function (value, nextFn) { return ( - // change here to check if the return value is array then we spread it - Reflect.apply(nextFn, null, toArray(value)) - ); }, Reflect.apply(mainFn, null, args)) - ); - } - ); - }; - - /** - * check if the object has name property - * @param {object} obj the object to check - * @param {string} name the prop name - * @return {*} the value or undefined - */ - function objHasProp(obj, name) { - var prop = Object.getOwnPropertyDescriptor(obj, name); - return prop !== undefined && prop.value ? prop.value : prop; - } - - /** - * 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 {string} name the name of the object to get inject also for checking - * @param {object} data to inject into the function static interface - * @param {boolean} [overwrite=false] if we want to overwrite the existing data - * @return {function} added property resolver - */ - function injectToFn(resolver, name, data, overwrite) { - if ( overwrite === void 0 ) overwrite = false; - - var check = objHasProp(resolver, name); - if (overwrite === false && check !== undefined) { - // console.info(`NOT INJECTED`) - return resolver; - } - /* this will throw error! - if (overwrite === true && check !== undefined) { - delete resolver[name] // delete this property - } - */ - // console.info(`INJECTED`) - Object.defineProperty(resolver, name, { - value: data, - writable: overwrite // if its set to true then we should able to overwrite it - }); - - return resolver; - } - - // breaking out the inner methods generator in here - - /** - * generate authorisation specific methods - * @param {object} jsonqlInstance instance of this - * @param {string} name of method - * @param {object} opts configuration - * @param {object} contract to match - * @return {function} for use - */ - var authMethodGenerator = function (jsonqlInstance, name, opts, contract) { - return function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var params = contract.auth[name].params; - var values = params.map(function (p, i) { return args[i]; }); - var header = args[params.length] || {}; - return validateAsync$1(args, params) - .then(function () { return jsonqlInstance - .query - .apply(jsonqlInstance, [name, values, header]); } - ) - .catch(finalCatch) - } - }; - - /** - * Break up the different type each - create query methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createQueryMethods = function (obj, jsonqlInstance, ee, config, contract) { - var query = {}; - var loop = function ( queryFn ) { - // to keep it clean we use a param to id the auth method - // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; - // generate the query method - query = injectToFn(query, queryFn, function queryFnHandler() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var params = contract.query[queryFn].params; - var _args = params.map(function (param, i) { return args[i]; }); - // debug('query', queryFn, _params); - // @TODO this need to change to a different way to add an extra header - var header = {}; - // @TODO validate against the type - return validateAsync$1(_args, params) - .then(function () { return jsonqlInstance - .query - .apply(jsonqlInstance, [queryFn, _args, header]); } - ) - .catch(finalCatch) - }); - }; - - for (var queryFn in contract.query) loop( queryFn ); - obj.query = query; - // create an alias to the helloWorld method - obj.helloWorld = query.helloWorld; - return [ obj, jsonqlInstance, ee, config, contract ] - }; - - /** - * create mutation methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createMutationMethods = function (obj, jsonqlInstance, ee, config, contract) { - var mutation = {}; - // process the mutation, the reason the mutation has a fixed number of parameters - // there is only the payload, and conditions parameters - // plus a header at the end - var loop = function ( mutationFn ) { - mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header) { - if ( header === void 0 ) header = {}; - - var args = [payload, conditions]; - var params = contract.mutation[mutationFn].params; - return validateAsync$1(args, params) - .then(function () { return jsonqlInstance - .mutation - .apply(jsonqlInstance, [mutationFn, payload, conditions, header]); } - ) - .catch(function (e) { - console.error('--- mutation fn catch ---', e); - return finalCatch(e) - }) - }); - }; - - for (var mutationFn in contract.mutation) loop( mutationFn ); - obj.mutation = mutation; - return [ obj, jsonqlInstance, ee, config, contract ] - }; - - /** - * create auth methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createAuthMethods = function (obj, jsonqlInstance, ee, config, contract) { - if (config.enableAuth && contract.auth) { - var auth = {}; // v1.3.1 add back the auth prop name in contract - var loginHandlerName = config.loginHandlerName; - var logoutHandlerName = config.logoutHandlerName; - if (contract.auth[loginHandlerName]) { - // changing to the name the config specify - auth[loginHandlerName] = function loginHandlerFn() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract); - return fn.apply(null, args) - .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance)) - .then(function (token) { - ee.$trigger(LOGIN_NAME, token); - return token; - }) - }; - } - // @TODO allow to logout one particular profile or all of them - if (contract.auth[logoutHandlerName]) { - auth[logoutHandlerName] = function logoutHandlerFn() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract); - return fn.apply(null, args) - .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance)) - .then(function (r) { - ee.$trigger(LOGOUT_NAME, r); - return r; - }) - }; - } else { - auth[logoutHandlerName] = function logoutHandlerFn() { - jsonqlInstance.postLogoutAction(KEY_WORD); - ee.$trigger(LOGOUT_NAME, KEY_WORD); - }; - } - obj.auth = auth; - } - - return obj; - }; - - /** - * Here just generate the methods calls - * @param {object} jsonqlInstance what it said - * @param {object} ee event emitter - * @param {object} config configuration - * @param {object} contract the map - * @return {object} with mapped methods - */ - function methodsGenerator(jsonqlInstance, ee, config, contract) { - var obj = {}; - var executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods); - return executor(obj, jsonqlInstance, ee, config, contract) - } - - // This generator will use the old style - - /** - * Group all the same methods together - * @param {object} ee event emitters - * @param {string} type query, mutation or auth - * @param {string} resolverName use as the guide - * @param {array} args from the call - * @return {function} the handler itself - */ - var handler = function (ee, type) { - // we don't run validate here because we want until the contract is ready - return function (resolverName) { - var args = [], len = arguments.length - 1; - while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; - - return ( - new Promise(function (resolver, rejecter) { - // this are the callbacks - ee.$only(createEvt(type, resolverName, ON_RESULT_PROP_NAME), resolver); - ee.$only(createEvt(type, resolverName, ON_ERROR_PROP_NAME), rejecter); - // this is the main call - ee.$trigger(type, { resolverName: resolverName, args: args }); - }) - ); - } - }; - - /** - * @param {object} ee eventEmitter - * @param {object} contract the map - * @param {object} config configuration - */ - var validateRegisteredEvents = function (ee, contract, config) { - var storedEvt = ee.$queues; - var debug = config.debugOn; - if (debug) { - console.info('(validateRegisteredEvents)', 'storedEvt', storedEvt); - } - storedEvt.forEach(function (args) { - var type = args[0]; - var payload = args[1]; - var resolverName = payload.resolverName; - if (debug) { - console.info('(validateRegisteredEvents)', type, resolverName); - } - if (!contract[type][resolverName]) { - throw new Error((type + "." + resolverName + " not existed in contract!")) - } - }); - }; - - /** - * set up all the event handlers once the contract is ready - * @param {object} jsonqlInstance what the name said - * @param {object} ee event emitter - * @param {object} config the configuration - * @param {object} contract the map - * @return {void} nothing - */ - function setupEventHandlers(jsonqlInstance, ee, config, contract) { - var methods = methodsGenerator(jsonqlInstance, ee, config, contract); - validateRegisteredEvents(ee, contract, config); - // create handler - var loop = function ( type ) { - // setup event listeners - only one listener per type - ee.$only(type, function(ref) { - var resolverName = ref.resolverName; - var args = ref.args; - - if (methods[type][resolverName]) { - Reflect.apply(methods[type][resolverName], null, args) - .then(function (result) { - ee.$trigger(createEvt(type, resolverName, ON_RESULT_PROP_NAME), result); - }) - .catch(function (err) { - ee.$trigger(createEvt(type, resolverName, ON_ERROR_PROP_NAME), err); - }); - } else { - console.error((resolverName + " is not defined in the contract!")); - } - }); - }; - - for (var type in methods) loop( type ); - // all done now release the queue if any - setTimeout(function () { - ee.$suspend = false; - }, 1); - } - - /** - * @param {object} jsonqlInstance jsonql class instance - * @param {object} config options - * @param {object} contractPromise an unresolve promise - * @param {object} ee eventEmitter - * @return {object} constructed functions call - */ - var generator = function (jsonqlInstance, config, contractPromise, ee) { - ee.$suspend = true; // hold all the calls - // wait for the promise to resolve - contractPromise.then(function (contract) { - setupEventHandlers(jsonqlInstance, ee, config, contract); - }); - // construct the api - var obj = { - query: handler(ee, 'query'), - mutation: handler(ee, 'mutation'), - auth: handler(ee, 'auth') - }; - // allow getting the token for valdiate agains the socket - obj.getToken = function () { return jsonqlInstance.rawAuthToken; }; - // this will pass to the ws-client if needed - // obj.eventEmitter = ee; - // this will require a param - if (config.exposeContract) { - obj.getContract = function () { return jsonqlInstance.get(); }; - } - if (config.enableAuth) { - obj.userdata = function () { return jsonqlInstance.userdata; }; - } - obj.version = '1.5.1'; - // output - return obj; - }; - - // split the contract into the node side and the generic side - /** - * Check if the json is a contract file or not - * @param {object} contract json object - * @return {boolean} true - */ - function checkIsContract(contract) { - return isPlainObject(contract) - && ( - isObjectHasKey(contract, QUERY_NAME) - || isObjectHasKey(contract, MUTATION_NAME) - || isObjectHasKey(contract, SOCKET_NAME) - ) - } - - /** - * Wrapper method that check if it's contract then return the contract or false - * @param {object} contract the object to check - * @return {boolean | object} false when it's not - */ - function isContract(contract) { - return checkIsContract(contract) ? contract : false; - } - - /** - * generate a 32bit hash based on the function.toString() - * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery - * @param {string} s the converted to string function - * @return {string} the hashed function string - */ - function hashCode(s) { - return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) - } - - // take only the module part which is what we use here - /** - * @param {object} jsonqlInstance the init instance of jsonql client - * @param {object} contract the static contract - * @return {object} contract may be from server - */ - var getContractFromConfig = function(jsonqlInstance, contract) { - if ( contract === void 0 ) contract = {}; - - if (isContract(contract)) { - return Promise.resolve(contract) - } - return jsonqlInstance.getContract() - }; - // wrapper method to make sure it's a string - var hashCode$1 = function (str) { return hashCode(str) + ''; }; - var USERDATA_TABLE = 'userdata'; - var CLS_LOCAL_STORE_NAME = 'localStore'; - var CLS_SESS_STORE_NAME = 'sessionStore'; - var CLS_CONTRACT_NAME = 'contract'; - var CLS_PROFILE_IDX = 'prof_idx'; - var ZERO_IDX = 0; - - /** - * The code was extracted from: - * https://github.com/davidchambers/Base64.js - */ - - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - - function InvalidCharacterError(message) { - this.message = message; - } - - InvalidCharacterError.prototype = new Error(); - InvalidCharacterError.prototype.name = 'InvalidCharacterError'; - - function polyfill (input) { - var str = String(input).replace(/=+$/, ''); - if (str.length % 4 == 1) { - throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); - } - for ( - // initialize result and counters - var bc = 0, bs, buffer, idx = 0, output = ''; - // get next character - buffer = str.charAt(idx++); - // character found in table? initialize bit storage and add its ascii value; - ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, - // and if not first of each 4 characters, - // convert the first 8 bits to one ascii character - bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 - ) { - // try to find character in table (0-63, not found => -1) - buffer = chars.indexOf(buffer); - } - return output; - } - - - var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; - - function b64DecodeUnicode(str) { - return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { - var code = p.charCodeAt(0).toString(16).toUpperCase(); - if (code.length < 2) { - code = '0' + code; - } - return '%' + code; - })); - } - - var base64_url_decode = function(str) { - var output = str.replace(/-/g, "+").replace(/_/g, "/"); - switch (output.length % 4) { - case 0: - break; - case 2: - output += "=="; - break; - case 3: - output += "="; - break; - default: - throw "Illegal base64url string!"; - } - - try{ - return b64DecodeUnicode(output); - } catch (err) { - return atob(output); - } - }; - - function InvalidTokenError(message) { - this.message = message; - } - - InvalidTokenError.prototype = new Error(); - InvalidTokenError.prototype.name = 'InvalidTokenError'; - - var lib = function (token,options) { - if (typeof token !== 'string') { - throw new InvalidTokenError('Invalid token specified'); - } - - options = options || {}; - var pos = options.header === true ? 0 : 1; - try { - return JSON.parse(base64_url_decode(token.split('.')[pos])); - } catch (e) { - throw new InvalidTokenError('Invalid token specified: ' + e.message); - } - }; - - var InvalidTokenError_1 = InvalidTokenError; - lib.InvalidTokenError = InvalidTokenError_1; - - // when the user is login with the jwt - - 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 = lib(token); - return validate(t) - } - throw new JsonqlError('Token must be a string!') - } - - var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; - - var appProps = { - algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), - expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), - notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), - audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), - subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), - issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), - noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), - header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), - keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), - mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) - }; - - /** - * @param {boolean} sec return in second or not - * @return {number} timestamp - */ - var timestamp$1 = function (sec) { - if ( sec === void 0 ) sec = false; - - var time = Date.now(); - return sec ? Math.floor( time / 1000 ) : time; - }; - - var assign = make_assign(); - var create = make_create(); - var trim$1 = make_trim(); - var Global = (typeof window !== 'undefined' ? window : commonjsGlobal); - - var util = { - assign: assign, - create: create, - trim: trim$1, - bind: bind, - slice: slice, - each: each, - map: map, - pluck: pluck, - isList: isList, - isFunction: isFunction$1, - isObject: isObject$1, - Global: Global - }; - - function make_assign() { - if (Object.assign) { - return Object.assign - } else { - return function shimAssign(obj, props1, props2, etc) { - var arguments$1 = arguments; - - for (var i = 1; i < arguments.length; i++) { - each(Object(arguments$1[i]), function(val, key) { - obj[key] = val; - }); - } - return obj - } - } - } - - function make_create() { - if (Object.create) { - return function create(obj, assignProps1, assignProps2, etc) { - var assignArgsList = slice(arguments, 1); - return assign.apply(this, [Object.create(obj)].concat(assignArgsList)) - } - } else { - function F() {} // eslint-disable-line no-inner-declarations - return function create(obj, assignProps1, assignProps2, etc) { - var assignArgsList = slice(arguments, 1); - F.prototype = obj; - return assign.apply(this, [new F()].concat(assignArgsList)) - } - } - } - - function make_trim() { - if (String.prototype.trim) { - return function trim(str) { - return String.prototype.trim.call(str) - } - } else { - return function trim(str) { - return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '') - } - } - } - - function bind(obj, fn) { - return function() { - return fn.apply(obj, Array.prototype.slice.call(arguments, 0)) - } - } - - function slice(arr, index) { - return Array.prototype.slice.call(arr, index || 0) - } - - function each(obj, fn) { - pluck(obj, function(val, key) { - fn(val, key); - return false - }); - } - - function map(obj, fn) { - var res = (isList(obj) ? [] : {}); - pluck(obj, function(v, k) { - res[k] = fn(v, k); - return false - }); - return res - } - - function pluck(obj, fn) { - if (isList(obj)) { - for (var i=0; i= 0; i--) { - var key = localStorage().key(i); - fn(read(key), key); - } - } - - function remove(key) { - return localStorage().removeItem(key) - } - - function clearAll() { - return localStorage().clear() - } - - // cookieStorage is useful Safari private browser mode, where localStorage - // doesn't work but cookies do. This implementation is adopted from - // https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage - - - var Global$2 = util.Global; - var trim$2 = util.trim; - - var cookieStorage = { - name: 'cookieStorage', - read: read$1, - write: write$1, - each: each$3, - remove: remove$1, - clearAll: clearAll$1, - }; - - var doc = Global$2.document; - - function read$1(key) { - if (!key || !_has(key)) { return null } - var regexpStr = "(?:^|.*;\\s*)" + - escape(key).replace(/[\-\.\+\*]/g, "\\$&") + - "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"; - return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")) - } - - function each$3(callback) { - var cookies = doc.cookie.split(/; ?/g); - for (var i = cookies.length - 1; i >= 0; i--) { - if (!trim$2(cookies[i])) { - continue - } - var kvp = cookies[i].split('='); - var key = unescape(kvp[0]); - var val = unescape(kvp[1]); - callback(val, key); - } - } - - function write$1(key, data) { - if(!key) { return } - doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; - } - - function remove$1(key) { - if (!key || !_has(key)) { - return - } - doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; - } - - function clearAll$1() { - each$3(function(_, key) { - remove$1(key); - }); - } - - function _has(key) { - return (new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie) - } - - var defaults = defaultsPlugin; - - function defaultsPlugin() { - var defaultValues = {}; - - return { - defaults: defaults, - get: get - } - - function defaults(_, values) { - defaultValues = values; - } - - function get(super_fn, key) { - var val = super_fn(); - return (val !== undefined ? val : defaultValues[key]) - } - } - - var bind$2 = util.bind; - var each$4 = util.each; - var create$2 = util.create; - var slice$2 = util.slice; - - var events = eventsPlugin; - - function eventsPlugin() { - var pubsub = _newPubSub(); - - return { - watch: watch, - unwatch: unwatch, - once: once, - - set: set, - remove: remove, - clearAll: clearAll - } - - // new pubsub functions - function watch(_, key, listener) { - return pubsub.on(key, bind$2(this, listener)) - } - function unwatch(_, subId) { - pubsub.off(subId); - } - function once(_, key, listener) { - pubsub.once(key, bind$2(this, listener)); - } - - // overwrite function to fire when appropriate - function set(super_fn, key, val) { - var oldVal = this.get(key); - super_fn(); - pubsub.fire(key, val, oldVal); - } - function remove(super_fn, key) { - var oldVal = this.get(key); - super_fn(); - pubsub.fire(key, undefined, oldVal); - } - function clearAll(super_fn) { - var oldVals = {}; - this.each(function(val, key) { - oldVals[key] = val; - }); - super_fn(); - each$4(oldVals, function(oldVal, key) { - pubsub.fire(key, undefined, oldVal); - }); - } - } - - - function _newPubSub() { - return create$2(_pubSubBase, { - _id: 0, - _subSignals: {}, - _subCallbacks: {} - }) - } - - var _pubSubBase = { - _id: null, - _subCallbacks: null, - _subSignals: null, - on: function(signal, callback) { - if (!this._subCallbacks[signal]) { - this._subCallbacks[signal] = {}; - } - this._id += 1; - this._subCallbacks[signal][this._id] = callback; - this._subSignals[this._id] = signal; - return this._id - }, - off: function(subId) { - var signal = this._subSignals[subId]; - delete this._subCallbacks[signal][subId]; - delete this._subSignals[subId]; - }, - once: function(signal, callback) { - var subId = this.on(signal, bind$2(this, function() { - callback.apply(this, arguments); - this.off(subId); - })); - }, - fire: function(signal) { - var args = slice$2(arguments, 1); - each$4(this._subCallbacks[signal], function(callback) { - callback.apply(this, args); - }); - } - }; - - var lzString = createCommonjsModule(function (module) { - /* eslint-disable */ - // Copyright (c) 2013 Pieroxy - // This work is free. You can redistribute it and/or modify it - // under the terms of the WTFPL, Version 2 - // For more information see LICENSE.txt or http://www.wtfpl.net/ - // - // For more information, the home page: - // http://pieroxy.net/blog/pages/lz-string/testing.html - // - // LZ-based compression algorithm, version 1.4.4 - var LZString = (function() { - - // private property - var f = String.fromCharCode; - var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; - var baseReverseDic = {}; - - function getBaseValue(alphabet, character) { - if (!baseReverseDic[alphabet]) { - baseReverseDic[alphabet] = {}; - for (var i=0 ; i>> 8; - buf[i*2+1] = current_value % 256; - } - return buf; - }, - - //decompress from uint8array (UCS-2 big endian format) - decompressFromUint8Array:function (compressed) { - if (compressed===null || compressed===undefined){ - return LZString.decompress(compressed); - } else { - var buf=new Array(compressed.length/2); // 2 bytes per character - for (var i=0, TotalLen=buf.length; i> 1; - } - } else { - value = 1; - for (i=0 ; i> 1; - } - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - delete context_dictionaryToCreate[context_w]; - } else { - value = context_dictionary[context_w]; - for (i=0 ; i> 1; - } - - - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - // Add wc to the dictionary. - context_dictionary[context_wc] = context_dictSize++; - context_w = String(context_c); - } - } - - // Output the code for w. - if (context_w !== "") { - if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) { - if (context_w.charCodeAt(0)<256) { - for (i=0 ; i> 1; - } - } else { - value = 1; - for (i=0 ; i> 1; - } - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - delete context_dictionaryToCreate[context_w]; - } else { - value = context_dictionary[context_w]; - for (i=0 ; i> 1; - } - - - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - } - - // Mark the end of the stream - value = 2; - for (i=0 ; i> 1; - } - - // Flush the last char - while (true) { - context_data_val = (context_data_val << 1); - if (context_data_position == bitsPerChar-1) { - context_data.push(getCharFromInt(context_data_val)); - break; - } - else { context_data_position++; } - } - return context_data.join(''); - }, - - decompress: function (compressed) { - if (compressed == null) { return ""; } - if (compressed == "") { return null; } - return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); }); - }, - - _decompress: function (length, resetValue, getNextValue) { - var dictionary = [], - next, - enlargeIn = 4, - dictSize = 4, - numBits = 3, - entry = "", - result = [], - i, - w, - bits, resb, maxpower, power, - c, - data = {val:getNextValue(0), position:resetValue, index:1}; - - for (i = 0; i < 3; i += 1) { - dictionary[i] = i; - } - - bits = 0; - maxpower = Math.pow(2,2); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - switch (next = bits) { - case 0: - bits = 0; - maxpower = Math.pow(2,8); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - c = f(bits); - break; - case 1: - bits = 0; - maxpower = Math.pow(2,16); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - c = f(bits); - break; - case 2: - return ""; - } - dictionary[3] = c; - w = c; - result.push(c); - while (true) { - if (data.index > length) { - return ""; - } - - bits = 0; - maxpower = Math.pow(2,numBits); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - switch (c = bits) { - case 0: - bits = 0; - maxpower = Math.pow(2,8); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - dictionary[dictSize++] = f(bits); - c = dictSize-1; - enlargeIn--; - break; - case 1: - bits = 0; - maxpower = Math.pow(2,16); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - dictionary[dictSize++] = f(bits); - c = dictSize-1; - enlargeIn--; - break; - case 2: - return result.join(''); - } - - if (enlargeIn == 0) { - enlargeIn = Math.pow(2, numBits); - numBits++; - } - - if (dictionary[c]) { - entry = dictionary[c]; - } else { - if (c === dictSize) { - entry = w + w.charAt(0); - } else { - return null; - } - } - result.push(entry); - - // Add w+entry[0] to the dictionary. - dictionary[dictSize++] = w + entry.charAt(0); - enlargeIn--; - - w = entry; - - if (enlargeIn == 0) { - enlargeIn = Math.pow(2, numBits); - numBits++; - } - - } - } - }; - return LZString; - })(); - - if( module != null ) { - module.exports = LZString; - } - }); - - var compression = compressionPlugin; - - function compressionPlugin() { - return { - get: get, - set: set, - } - - function get(super_fn, key) { - var val = super_fn(key); - if (!val) { return val } - var decompressed = lzString.decompress(val); - // fallback to existing values that are not compressed - return (decompressed == null) ? val : this._deserialize(decompressed) - } - - function set(super_fn, key, val) { - var compressed = lzString.compress(this._serialize(val)); - super_fn(key, compressed); - } - } - - // sort of persist on the user side - - var storages = [localStorage_1, cookieStorage]; - var plugins = [defaults, events, compression]; - - var localStore = storeEngine.createStore(storages, plugins); - - var Global$3 = util.Global; - - var sessionStorage_1 = { - name: 'sessionStorage', - read: read$2, - write: write$2, - each: each$5, - remove: remove$2, - clearAll: clearAll$2 - }; - - function sessionStorage() { - return Global$3.sessionStorage - } - - function read$2(key) { - return sessionStorage().getItem(key) - } - - function write$2(key, data) { - return sessionStorage().setItem(key, data) - } - - function each$5(fn) { - for (var i = sessionStorage().length - 1; i >= 0; i--) { - var key = sessionStorage().key(i); - fn(read$2(key), key); - } - } - - function remove$2(key) { - return sessionStorage().removeItem(key) - } - - function clearAll$2() { - return sessionStorage().clear() - } - - // session store with watch - // @1.5.0 stop using the expired plugin and deal it ourself - // import expiredPlugin from 'store/plugins/expire' - - var storages$1 = [sessionStorage_1, cookieStorage]; - var plugins$1 = [defaults, compression]; - - var sessionStore = storeEngine.createStore(storages$1, plugins$1); - - // export store interface - - // export back the raw version for development purposes - var localStore$1 = localStore; - var sessionStore$1 = sessionStore; - - // ported from jsonql-params-validator - - /** - * @param {*} args arguments to send - *@return {object} formatted payload - */ - var formatPayload = function (args) { - var obj; - - return ( - ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) - ); - }; - - /** - * Get name from the payload (ported back from jsonql-koa) - * @param {*} payload to extract from - * @return {string} name - */ - function getNameFromPayload(payload) { - return Object.keys(payload)[0] - } - - /** - * wrapper method to add the timestamp as well - * @param {string} resolverName - * @param {*} payload - * @return {object} delierable - */ - function createDeliverable(resolverName, payload) { - var obj; - - return ( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME] = [ timestamp$1() ], obj ) - } - - /** - * @param {string} resolverName name of function - * @param {array} [args=[]] from the ...args - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createQuery(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - - if (isString(resolverName) && isArray(args)) { - var payload = formatPayload(args); - if (jsonp === true) { - return payload; - } - return createDeliverable(resolverName, payload) - } - throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) - } - - /** - * @param {string} resolverName name of function - * @param {*} payload to send - * @param {object} [condition={}] for what - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createMutation(resolverName, payload, condition, jsonp) { - if ( condition === void 0 ) condition = {}; - if ( jsonp === void 0 ) jsonp = false; - - var _payload = {}; - _payload[PAYLOAD_PARAM_NAME] = payload; - _payload[CONDITION_PARAM_NAME] = condition; - if (jsonp === true) { - return _payload; - } - if (isString(resolverName)) { - return createDeliverable(resolverName, _payload) - } - throw new JsonqlValidationError("[createMutation] expect resolverName to be string!", { resolverName: resolverName, payload: payload, condition: condition }) - } - - /** - * @return {object} _cb as key with timestamp - */ - var cacheBurst = function () { return ({ _cb: timestamp$1() }); }; - - // break up from node-middleware - - // ported from http-client - - /** - * handle the return data - * @TODO how to handle the return timestamp and calculate the diff? - * @param {object} result return from server - * @return {object} strip the data part out, or if the error is presented - */ - var resultHandler = function (result) { return ( - (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result - ); }; - - // new 1.5.0 - - // this becomes the base class instead of the HttpCls - var StoreClass = function StoreClass(opts) { - this.opts = opts; - // make it a string - this.instanceKey = hashCode$1(this.opts.hostname); - // pass this store for use later - this.localStore = localStore$1; - this.sessionStore = sessionStore$1; - /* - if (this.opts.debugOn) { // reuse this to clear out the data - this.log('clear all stores') - localStore.clearAll() - sessionStore.clearAll() - - localStore.set('TEST', Date.now()) - sessionStore.set('TEST', Date.now()) - } - */ - }; - - var prototypeAccessors = { lset: { configurable: true },lget: { configurable: true },sset: { configurable: true },sget: { configurable: true } }; - // store in local storage id by the instanceKey - // values should be an object so with key so we just merge - // into the existing store without going through the keys - StoreClass.prototype.__setMethod = function __setMethod (storeType, values) { - var obj; - - var store = this[storeType]; - var data = this.__getMethod(storeType); - var skey = this.opts.storageKey; - var ikey = this.instanceKey; - store.set(skey, ( obj = {}, obj[ikey] = data ? merge({}, data, values) : values, obj )); - }; - // return the data id by the instaceKey - StoreClass.prototype.__getMethod = function __getMethod (storeType) { - var store = this[storeType]; - var data = store.get(this.opts.storageKey); - return data ? data[this.instanceKey] : false - }; - // remove from local store id by instanceKey - StoreClass.prototype.__delMethod = function __delMethod (storeType, key) { - var data = this.__getMethod(storeType); - if (data) { - var store = {}; - for (var k in data) { - if (k !== key) { - store[k] = data[k]; - } - } - this.__setMethod(storeType, store); - } - }; - // clear everything by this instanceKey - StoreClass.prototype.__clearMethod = function __clearMethod (storeKey) { - var skey = this.opts.storageKey; - var store = this[storeKey]; - var data = store.get(skey); - if (data) { - var _store = {}; - for (var k in data) { - if (k !== this.instanceKey) { - _store[k] = data[k]; - } - } - store.set(skey, _store); - } - }; - // Alias for different store - prototypeAccessors.lset.set = function (values) { - return this.__setMethod(CLS_LOCAL_STORE_NAME, values) - }; - - prototypeAccessors.lget.get = function () { - return this.__getMethod(CLS_LOCAL_STORE_NAME) - }; - - StoreClass.prototype.ldel = function ldel (key) { - return this.__delMethod(CLS_LOCAL_STORE_NAME, key) - }; - - StoreClass.prototype.lclear = function lclear () { - return this.__clearMethod(CLS_LOCAL_STORE_NAME) - }; - - // store in session store id by the instanceKey - prototypeAccessors.sset.set = function (values) { - // this.log('--- sset ---', values) - return this.__setMethod(CLS_SESS_STORE_NAME, values) - }; - - prototypeAccessors.sget.get = function () { - return this.__getMethod(CLS_SESS_STORE_NAME) - }; - - StoreClass.prototype.sdel = function sdel (key) { - return this.__delMethod(CLS_SESS_STORE_NAME, key) - }; - - StoreClass.prototype.sclear = function sclear () { - return this.__clearMethod(CLS_SESS_STORE_NAME) - }; - - Object.defineProperties( StoreClass.prototype, prototypeAccessors ); - - // base HttpClass - /** - * It will ONLY have our own jsonql specific implement check - * @param {object} result the server return result - * @return {object} this will just throw error - */ - function clientErrorsHandler$1(result) { - if (isObjectHasKey(result, 'error')) { - var error = result.error; - var className = error.className; - var name = error.name; - var errorName = className || name; - // just throw the whole thing back - var msg = error.message || NO_ERROR_MSG; - var detail = error.detail || error; - console.info('--- errorName ---', errorName, errors$1); - - if (errorName && errors$1[errorName]) { - throw new errors$1[className](msg, detail) - } - throw new JsonqlError(msg, detail) - } - // pass through to the next - return result; - } - - - - // extract the one we need - var POST = API_REQUEST_METHODS[0]; - var PUT = API_REQUEST_METHODS[1]; - - var HttpClass = /*@__PURE__*/(function (StoreClass) { - function HttpClass(opts) { - StoreClass.call(this, opts); - // change the way how we init Fly - // flyio now become external depedencies and it makes it easier to switch - // @BUG should we run test to check if we have the windows object? - // this.log(opts) - // this.fly = opts.Fly ? new opts.Fly() : new Fly() - // to a different environment like WeChat mini app - - this.extraHeader = {}; - // @1.2.1 for adding query to the call on the fly - this.extraParams = {}; - // this.log('start up opts', opts); - this.reqInterceptor(); - this.resInterceptor(); - } - - if ( StoreClass ) HttpClass.__proto__ = StoreClass; - HttpClass.prototype = Object.create( StoreClass && StoreClass.prototype ); - HttpClass.prototype.constructor = HttpClass; - - var prototypeAccessors = { headers: { configurable: true } }; - - // set headers for that one call - prototypeAccessors.headers.set = function (header) { - this.extraHeader = header; - }; - - /** - * Create the reusage request method - * @param {object} payload jsonql payload - * @param {object} options extra options add the request - * @param {object} headers extra headers add to the call - * @return {object} the fly request instance - */ - HttpClass.prototype.request = function request (payload, options, headers) { - var obj; - - if ( options === void 0 ) options = {}; - if ( headers === void 0 ) headers = {}; - this.headers = headers; - var params = merge({}, cacheBurst(), this.extraParams); - // @TODO need to add a jsonp url and payload - if (this.opts.enableJsonp) { - var resolverName = getNameFromPayload(payload); - params = merge({}, params, ( obj = {}, obj[JSONP_CALLBACK_NAME] = resolverName, obj )); - payload = payload[resolverName]; - } - // double up the url param and see what happen @TODO remove later - var reqParams = merge({}, { method: POST, params: params }, options); - this.log('request params', reqParams, this.jsonqlEndpoint); - - return this.fly.request(this.jsonqlEndpoint, payload, reqParams) - }; - - /** - * This will replace the create baseRequest method - * - */ - HttpClass.prototype.reqInterceptor = function reqInterceptor () { - var this$1 = this; - - this.fly.interceptors.request.use( - function (req) { - var headers = this$1.getHeaders(); - this$1.log('request interceptor call', headers); - - for (var key in headers) { - req.headers[key] = headers[key]; - } - return req; - } - ); - }; - - // @TODO - HttpClass.prototype.processJsonp = function processJsonp (result) { - return resultHandler(result) - }; - - /** - * This will be replacement of the first then call - * - */ - HttpClass.prototype.resInterceptor = function resInterceptor () { - var this$1 = this; - - var self = this; - var jsonp = self.opts.enableJsonp; - this.fly.interceptors.response.use( - function (res) { - this$1.log('response interceptor call', res); - self.cleanUp(); - // now more processing here - // there is a problem if we throw the result.error here - // the original data is lost, so we need to do what we did before - // deal with that error in the first then instead - var result = isString$1(res.data) ? JSON.parse(res.data) : res.data; - if (jsonp) { - return self.processJsonp(result) - } - return resultHandler(result) - }, - // this get call when it's not 200 - function (err) { - self.cleanUp(); - console.error(err); - throw new JsonqlServerError('Server side error', err) - } - ); - }; - - /** - * Get the headers inject into the call - * @return {object} headers - */ - HttpClass.prototype.getHeaders = function getHeaders () { - if (this.opts.enableAuth) { - return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader) - } - return merge({}, DEFAULT_HEADER, this.extraHeader) - }; - - /** - * Post http call operation to clean up things we need - */ - HttpClass.prototype.cleanUp = function cleanUp () { - this.extraHeader = {}; - this.extraParams = {}; - }; - - /** - * GET for contract only - * @return {promise} resolve the contract - */ - HttpClass.prototype.getRemoteContract = function getRemoteContract () { - var this$1 = this; - - if (this.opts.showContractDesc) { - this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM); - } - return this.request({}, {method: 'GET'}, this.contractHeader) - .then(clientErrorsHandler$1) - .then(function (result) { - this$1.log('get contract result', result); - // when refresh the window the result is different! - // @TODO need to check the Koa side about why is that - // also it should set a flag if we want the description or not - if (result.cache && result.contract) { - return result.contract; - } - // just the normal result - return result - }) - .catch(function (err) { - console.error('getRemoteContract err', err); - throw new JsonqlServerError('getRemoteContract', err) - }) - }; - - /** - * POST to server - query - * @param {object} name of the resolver - * @param {array} args arguments - * @return {object} promise resolve to the resolver return - */ - HttpClass.prototype.query = function query (name, args) { - if ( args === void 0 ) args = []; - - return this.request(createQuery(name, args)) - .then(clientErrorsHandler$1) - }; - - /** - * PUT to server - mutation - * @param {string} name of resolver - * @param {object} payload what it said - * @param {object} conditions what it said - * @return {object} promise resolve to the resolver return - */ - HttpClass.prototype.mutation = function mutation (name, payload, conditions) { - if ( payload === void 0 ) payload = {}; - if ( conditions === void 0 ) conditions = {}; - - return this.request(createMutation(name, payload, conditions), {method: PUT}) - .then(clientErrorsHandler$1) - }; - - Object.defineProperties( HttpClass.prototype, prototypeAccessors ); - - return HttpClass; - }(StoreClass)); - - // all the contract related methods will be here - - // export - var ContractClass = /*@__PURE__*/(function (HttpClass) { - function ContractClass(opts) { - HttpClass.call(this, opts); - } - - if ( HttpClass ) ContractClass.__proto__ = HttpClass; - ContractClass.prototype = Object.create( HttpClass && HttpClass.prototype ); - ContractClass.prototype.constructor = ContractClass; - - var prototypeAccessors = { contractHeader: { configurable: true } }; - - /** - * return the contract public api - * @return {object} contract - */ - ContractClass.prototype.getContract = function getContract () { - var contract = this.readContract(); - this.log('getContract first call', contract); - return contract ? Promise.resolve(contract) - : this.getRemoteContract().then(this.storeContract.bind(this)) - }; - - /** - * We are changing the way how to auth to get the contract.json - * Instead of in the url, we will be putting that key value in the header - * @return {object} header - */ - prototypeAccessors.contractHeader.get = function () { - var base = {}; - if (this.opts.contractKey !== false) { - base[this.opts.contractKeyName] = this.opts.contractKey; - } - return base; - }; - - /** - * Save the contract to local store - * @param {object} contract to save - * @return {object|boolean} false when its not a contract or contract on OK - */ - ContractClass.prototype.storeContract = function storeContract (contract) { - var obj; - - // first need to check if the contract is a contract - if (!isContract(contract)) { - throw new JsonqlValidationError("Contract is malformed!") - //return false; - } - /* @TODO need to rethink how to expired the contract - let args = [contract] - if (this.opts.contractExpired) { - let expired = parseFloat(this.opts.contractExpired) - if (!isNaN(expired) && expired > 0) { - args.push(expired) - } - } - // calling the setter - this.jsonqlContract = args; - */ - this.lset = ( obj = {}, obj[CLS_CONTRACT_NAME] = contract, obj ); - // return it - this.log('storeContract return result', contract); - return contract; - }; - - /** - * return the contract from options or localStore - * @return {object|boolean} false on not found - */ - ContractClass.prototype.readContract = function readContract () { - var contract = isContract(this.opts.contract); - if (contract !== false) { - return contract; - } - var data = this.lget; - if (data) { - return data[CLS_CONTRACT_NAME] - } - return false; - }; - - Object.defineProperties( ContractClass.prototype, prototypeAccessors ); - - return ContractClass; - }(HttpClass)); - - // this is the new auth class that integrate with the jsonql-jwt - // export - var AuthClass = /*@__PURE__*/(function (ContractClass) { - function AuthClass(opts) { - ContractClass.call(this, opts); - if (opts.enableAuth) { - this.setDecoder = jwtDecode; - } - } - - if ( ContractClass ) AuthClass.__proto__ = ContractClass; - AuthClass.prototype = Object.create( ContractClass && ContractClass.prototype ); - AuthClass.prototype.constructor = AuthClass; - - var prototypeAccessors = { profileIndex: { configurable: true },setDecoder: { configurable: true },saveProfile: { configurable: true },readProfile: { configurable: true },jsonqlToken: { configurable: true },jsonqlUserdata: { configurable: true } }; - - /** - * for overwrite - * @param {string} token stored token - * @return {string} token - */ - AuthClass.prototype.decoder = function decoder (token) { - return token; - }; - - /** - * set the profile index - * @param {number} idx - */ - prototypeAccessors.profileIndex.set = function (idx) { - var obj; - - var key = CLS_PROFILE_IDX; - if (isNumber$1(idx)) { - this[key] = idx; - if (this.opts.persistToken) { - this.lset = ( obj = {}, obj[key] = idx, obj ); - } - return; - } - throw new JsonqlValidationError('profileIndex', ("Expect idx to be number but got " + (typeof idx))) - }; - - /** - * get the profile index - * @return {number} idx - */ - prototypeAccessors.profileIndex.get = function () { - var key = CLS_PROFILE_IDX; - if (this.opts.persistToken) { - var data = this.lget; - if (data[key]) { - return data[key] - } - } - return this[key] ? this[key] : ZERO_IDX - }; - - /** - * Return the token from session store - * @param {number} [idx=false] profile index - * @return {string} token - */ - AuthClass.prototype.rawAuthToken = function rawAuthToken (idx) { - if ( idx === void 0 ) idx = false; - - if (idx !== false) { - this.profileIndex = idx; - } - // this should return from the base - return this.jsonqlToken; // see base-cls - }; - - /** - * Setter to add a decoder when retrieve user token - * @param {function} d a decoder - */ - prototypeAccessors.setDecoder.set = function (d) { - if (typeof d === 'function') { - this.decoder = d; - } - }; - - /** - * getter to return the session or local store set method - * @param {*} data to save - * @return {object} set method - */ - prototypeAccessors.saveProfile.set = function (data) { - if (this.opts.persistToken) { - // this.log('--- saveProfile lset ---', data) - this.lset = data; - } else { - // this.log('--- saveProfile sset ---', data) - this.sset = data; - } - }; - - /** - * getter to return the session or local store get method - * @return {object} get method - */ - prototypeAccessors.readProfile.get = function () { - return this.opts.persistToken ? this.lget : this.sget - }; - - // these were in the base class before but it should be here - /** - * save token - * @param {string} token to store - * @return {string|boolean} false on failed - */ - prototypeAccessors.jsonqlToken.set = function (token) { - var obj; - - var data = this.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - // @TODO also have to make sure the token is not already existed! - var tokens = (data && data[key]) ? data[key] : []; - tokens.push(token); - this.saveProfile = ( obj = {}, obj[key] = tokens, obj ); - // store the userdata - this.jsonqlUserdata = this.decoder(token); - }; - - /** - * Jsonql token getter - * 1.5.1 each token associate with the same profileIndex - * @return {string|boolean} false when failed - */ - prototypeAccessors.jsonqlToken.get = function () { - var data = this.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - if (data && data[key]) { - this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex]); - return data[key][this.profileIndex] - } - return false - }; - - /** - * this one will use the sessionStore - * basically we hook this onto the token store and decode it to store here - * we only store one decoded user data at a time, but the token can be multiple - */ - prototypeAccessors.jsonqlUserdata.set = function (userdata) { - var obj; - - this.sset = ( obj = {}, obj[USERDATA_TABLE] = userdata, obj ); - }; - - /** - * this one store in the session store - * get login userdata decoded jwt - * 1.5.1 each userdata associate with the same profileIndex - * @return {object|null} - */ - prototypeAccessors.jsonqlUserdata.get = function () { - var data = this.sget; - return data ? data[USERDATA_TABLE] : false - }; - - /** - * Construct the auth header - * @return {object} header - */ - AuthClass.prototype.getAuthHeader = function getAuthHeader () { - var obj; - - var token = this.jsonqlToken; // only call the getter to get the default one - return token ? ( obj = {}, obj[this.opts.AUTH_HEADER] = (BEARER + " " + token), obj ) : {}; - }; - - /** - * return all the stored token and decode it - * @param {number} [idx=false] profile index - * @return {array|boolean|string} false not found or array - */ - AuthClass.prototype.getProfiles = function getProfiles (idx) { - if ( idx === void 0 ) idx = false; - - var self = this; // just in case the scope problem - var data = self.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - if (data && data[key]) { - if (idx !== false && isNumber$1(idx)) { - return data[key][idx] || false - } - return data[key].map(self.decoder.bind(self)) - } - return false - }; - - /** - * call after the login - * @param {string} token return from server - * @return {object} decoded token to userdata object - */ - AuthClass.prototype.postLoginAction = function postLoginAction (token) { - this.jsonqlToken = token; - return token - }; - - /** - * call after the logout @TODO - */ - AuthClass.prototype.postLogoutAction = function postLogoutAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - console.info("postLogoutAction", args); - }; - - Object.defineProperties( AuthClass.prototype, prototypeAccessors ); - - return AuthClass; - }(ContractClass)); - - // this the core of the internal storage management - - // This class will only focus on the storage system - var JsonqlBaseClient = /*@__PURE__*/(function (AuthCls) { - function JsonqlBaseClient(fly, opts) { - // change at 1.4.10 pass it directly without init it - this.fly = fly; - AuthCls.call(this, opts); - } - - if ( AuthCls ) JsonqlBaseClient.__proto__ = AuthCls; - JsonqlBaseClient.prototype = Object.create( AuthCls && AuthCls.prototype ); - JsonqlBaseClient.prototype.constructor = JsonqlBaseClient; - - var prototypeAccessors = { jsonqlEndpoint: { configurable: true } }; - - /** - * construct the end point - * @return {string} the end point to call - */ - prototypeAccessors.jsonqlEndpoint.get = function () { - var baseUrl = this.opts.hostname || ''; - return [baseUrl, this.opts.jsonqlPath].join('/') - }; - - /** - * simple log - */ - JsonqlBaseClient.prototype.log = function log () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - if (this.opts.debugOn === true) { - Reflect.apply(console.info, console, args); - } - }; - - Object.defineProperties( JsonqlBaseClient.prototype, prototypeAccessors ); - - return JsonqlBaseClient; - }(AuthClass)); - - // export interface - - // all the client configuration options here - var constProps = { - contract: false, - MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong? - CONTENT_TYPE: CONTENT_TYPE, - BEARER: BEARER, - AUTH_HEADER: AUTH_HEADER - }; - - // grab the localhost name and put into the hostname as default - var getHostName = function () { - try { - return [window.location.protocol, window.location.host].join('//') - } catch(e) { - return null - } - }; - - var appProps$1 = { - - hostname: createConfig$1(getHostName(), [STRING_TYPE]), // required the hostname - jsonqlPath: createConfig$1(JSONQL_PATH, [STRING_TYPE]), // The path on the server - - loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), - logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), - // add to koa v1.3.0 - this might remove in the future - enableJsonp: createConfig$1(false, [BOOLEAN_TYPE]), - enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), - // enable useJwt by default @TODO replace with something else and remove them later - useJwt: createConfig$1(true, [BOOLEAN_TYPE]), - // when true then store infinity or pass a time in seconds then we check against - // the token date of creation - persistToken: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE]), - // the header - // v1.2.0 we are using this option during the dev - // so it won't save anything to the localstorage and fetch a new contract - // whenever the browser reload - useLocalstorage: createConfig$1(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage - storageKey: createConfig$1(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage - authKey: createConfig$1(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage - contractExpired: createConfig$1(0, [NUMBER_TYPE]),// -1 always fetch contract, - // 0 never expired, - // > 0 then compare the timestamp with the current one to see if we need to get contract again - // useful during development - keepContract: createConfig$1(true, [BOOLEAN_TYPE]), - exposeContract: createConfig$1(false, [BOOLEAN_TYPE]), - exposeStore: createConfig$1(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn - // @1.2.1 new option for the contract-console to fetch the contract with description - showContractDesc: createConfig$1(false, [BOOLEAN_TYPE]), - contractKey: createConfig$1(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this - contractKeyName: createConfig$1(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs - enableTimeout: createConfig$1(false, [BOOLEAN_TYPE]), // @TODO - timeout: createConfig$1(5000, [NUMBER_TYPE]), // 5 seconds - returnInstance: createConfig$1(false, [BOOLEAN_TYPE]), - allowReturnRawToken: createConfig$1(false, [BOOLEAN_TYPE]), - debugOn: createConfig$1(false, [BOOLEAN_TYPE]) - }; - - // This is for the sync version therefore we don't need to care about the contract options - - function checkOptions(config) { - return checkConfig$1(config, appProps$1, constProps) - } - - // export interface - - // sync version without needing the promise - function checkOptions$1(config) { - return objHasProp(config, CHECKED_KEY) ? config : checkOptions(config) - } - - var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); - var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); - - // making all the functionality on it's own - // import { WatchClass } from './watch' - - var SuspendClass = function SuspendClass() { - // suspend, release and queue - this.__suspend__ = null; - this.queueStore = new Set(); - /* - this.watch('suspend', function(value, prop, oldValue) { - this.logger(`${prop} set from ${oldValue} to ${value}`) - // it means it set the suspend = true then release it - if (oldValue === true && value === false) { - // we want this happen after the return happens - setTimeout(() => { - this.release() - }, 1) - } - return value; // we need to return the value to store it - }) - */ - }; - - var prototypeAccessors$1 = { $suspend: { configurable: true },$queues: { configurable: true } }; - - /** - * setter to set the suspend and check if it's boolean value - * @param {boolean} value to trigger - */ - prototypeAccessors$1.$suspend.set = function (value) { - var this$1 = this; - - if (typeof value === 'boolean') { - var lastValue = this.__suspend__; - this.__suspend__ = value; - this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); - if (lastValue === true && value === false) { - setTimeout(function () { - this$1.release(); - }, 1); - } - } else { - throw new Error("$suspend only accept Boolean value!") - } - }; - - /** - * queuing call up when it's in suspend mode - * @param {any} value - * @return {Boolean} true when added or false when it's not - */ - SuspendClass.prototype.$queue = function $queue () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - if (this.__suspend__ === true) { - this.logger('($queue)', 'added to $queue', args); - // there shouldn't be any duplicate ... - this.queueStore.add(args); - } - return this.__suspend__; - }; - - /** - * a getter to get all the store queue - * @return {array} Set turn into Array before return - */ - prototypeAccessors$1.$queues.get = function () { - var size = this.queueStore.size; - this.logger('($queues)', ("size: " + size)); - if (size > 0) { - return Array.from(this.queueStore) - } - return [] - }; - - /** - * Release the queue - * @return {int} size if any - */ - SuspendClass.prototype.release = function release () { - var this$1 = this; - - var size = this.queueStore.size; - this.logger('(release)', ("Release was called " + size)); - if (size > 0) { - var queue = Array.from(this.queueStore); - this.queueStore.clear(); - this.logger('queue', queue); - queue.forEach(function (args) { - this$1.logger(args); - Reflect.apply(this$1.$trigger, this$1, args); - }); - this.logger(("Release size " + (this.queueStore.size))); - } - }; - - Object.defineProperties( SuspendClass.prototype, prototypeAccessors$1 ); - - // break up the main file because its getting way too long - - var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { - function NbEventServiceBase(config) { - if ( config === void 0 ) config = {}; - - SuspendClass.call(this); - if (config.logger && typeof config.logger === 'function') { - this.logger = config.logger; - } - this.keep = config.keep; - // for the $done setter - this.result = config.keep ? [] : null; - // we need to init the store first otherwise it could be a lot of checking later - this.normalStore = new Map(); - this.lazyStore = new Map(); - } - - if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; - NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); - NbEventServiceBase.prototype.constructor = NbEventServiceBase; - - var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; - - /** - * validate the event name(s) - * @param {string[]} evt event name - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validateEvt = function validateEvt () { - var this$1 = this; - var evt = [], len = arguments.length; - while ( len-- ) evt[ len ] = arguments[ len ]; - - evt.forEach(function (e) { - if (typeof e !== 'string') { - this$1.logger('(validateEvt)', e); - throw new Error("event name must be string type!") - } - }); - return true; - }; - - /** - * Simple quick check on the two main parameters - * @param {string} evt event name - * @param {function} callback function to call - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validate = function validate (evt, callback) { - if (this.validateEvt(evt)) { - if (typeof callback === 'function') { - return true; - } - } - throw new Error("callback required to be function type!") - }; - - /** - * Check if this type is correct or not added in V1.5.0 - * @param {string} type for checking - * @return {boolean} true on OK - */ - NbEventServiceBase.prototype.validateType = function validateType (type) { - var types = ['on', 'only', 'once', 'onlyOnce']; - return !!types.filter(function (t) { return type === t; }).length; - }; - - /** - * Run the callback - * @param {function} callback function to execute - * @param {array} payload for callback - * @param {object} ctx context or null - * @return {void} the result store in $done - */ - NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { - this.logger('(run)', callback, payload, ctx); - this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); - }; - - /** - * Take the content out and remove it from store id by the name - * @param {string} evt event name - * @param {string} [storeName = lazyStore] name of store - * @return {object|boolean} content or false on not found - */ - NbEventServiceBase.prototype.takeFromStore = function takeFromStore (evt, storeName) { - if ( storeName === void 0 ) storeName = 'lazyStore'; - - var store = this[storeName]; // it could be empty at this point - if (store) { - this.logger('(takeFromStore)', storeName, store); - if (store.has(evt)) { - var content = store.get(evt); - this.logger('(takeFromStore)', ("has " + evt), content); - store.delete(evt); - return content; - } - return false; - } - throw new Error((storeName + " is not supported!")) - }; - - /** - * The add to store step is similar so make it generic for resuse - * @param {object} store which store to use - * @param {string} evt event name - * @param {spread} args because the lazy store and normal store store different things - * @return {array} store and the size of the store - */ - NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { - var args = [], len = arguments.length - 2; - while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; - - var fnSet; - if (store.has(evt)) { - this.logger('(addToStore)', (evt + " existed")); - fnSet = store.get(evt); - } else { - this.logger('(addToStore)', ("create new Set for " + evt)); - // this is new - fnSet = new Set(); - } - // lazy only store 2 items - this is not the case in V1.6.0 anymore - // we need to check the first parameter is string or not - if (args.length > 2) { - if (Array.isArray(args[0])) { // lazy store - // check if this type of this event already register in the lazy store - var t = args[2]; - if (!this.checkTypeInLazyStore(evt, t)) { - fnSet.add(args); - } - } else { - if (!this.checkContentExist(args, fnSet)) { - this.logger('(addToStore)', "insert new", args); - fnSet.add(args); - } - } - } else { // add straight to lazy store - fnSet.add(args); - } - store.set(evt, fnSet); - return [store, fnSet.size] - }; - - /** - * @param {array} args for compare - * @param {object} fnSet A Set to search from - * @return {boolean} true on exist - */ - NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { - var list = Array.from(fnSet); - return !!list.filter(function (l) { - var hash = l[0]; - if (hash === args[0]) { - return true; - } - return false; - }).length; - }; - - /** - * get the existing type to make sure no mix type add to the same store - * @param {string} evtName event name - * @param {string} type the type to check - * @return {boolean} true you can add, false then you can't add this type - */ - NbEventServiceBase.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { - this.validateEvt(evtName, type); - var all = this.$get(evtName, true); - if (all === false) { - // pristine it means you can add - return true; - } - // it should only have ONE type in ONE event store - return !all.filter(function (list) { - var t = list[3]; - return type !== t; - }).length; - }; - - /** - * This is checking just the lazy store because the structure is different - * therefore we need to use a new method to check it - */ - NbEventServiceBase.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { - this.validateEvt(evtName, type); - var store = this.lazyStore.get(evtName); - this.logger('(checkTypeInLazyStore)', store); - if (store) { - return !!Array - .from(store) - .filter(function (l) { - var t = l[2]; - return t !== type; - }).length - } - return false; - }; - - /** - * wrapper to re-use the addToStore, - * V1.3.0 add extra check to see if this type can add to this evt - * @param {string} evt event name - * @param {string} type on or once - * @param {function} callback function - * @param {object} context the context the function execute in or null - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { - if ( context === void 0 ) context = null; - - this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); - // @TODO we need to check the existing store for the type first! - if (this.checkTypeInStore(evt, type)) { - this.logger('(addToNormalStore)', (type + " can add to " + evt + " normal store")); - var key = this.hashFnToKey(callback); - var args = [this.normalStore, evt, key, callback, context, type]; - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.normalStore = _store; - return size; - } - return false; - }; - - /** - * Add to lazy store this get calls when the callback is not register yet - * so we only get a payload object or even nothing - * @param {string} evt event name - * @param {array} payload of arguments or empty if there is none - * @param {object} [context=null] the context the callback execute in - * @param {string} [type=false] register a type so no other type can add to this evt - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - // this is add in V1.6.0 - // when there is type then we will need to check if this already added in lazy store - // and no other type can add to this lazy store - var args = [this.lazyStore, evt, this.toArray(payload), context]; - if (type) { - args.push(type); - } - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.lazyStore = _store; - return size; - }; - - /** - * make sure we store the argument correctly - * @param {*} arg could be array - * @return {array} make sured - */ - NbEventServiceBase.prototype.toArray = function toArray (arg) { - return Array.isArray(arg) ? arg : [arg]; - }; - - /** - * setter to store the Set in private - * @param {object} obj a Set - */ - prototypeAccessors.normalStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); - }; - - /** - * @return {object} Set object - */ - prototypeAccessors.normalStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) - }; - - /** - * setter to store the Set in lazy store - * @param {object} obj a Set - */ - prototypeAccessors.lazyStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); - }; - - /** - * @return {object} the lazy store Set - */ - prototypeAccessors.lazyStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) - }; - - /** - * generate a hashKey to identify the function call - * The build-in store some how could store the same values! - * @param {function} fn the converted to string function - * @return {string} hashKey - */ - NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { - return hashCode(fn.toString()) + ''; - }; - - Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); - - return NbEventServiceBase; - }(SuspendClass)); - - // The top level - // export - var EventService = /*@__PURE__*/(function (NbStoreService) { - function EventService(config) { - if ( config === void 0 ) config = {}; - - NbStoreService.call(this, config); - } - - if ( NbStoreService ) EventService.__proto__ = NbStoreService; - EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); - EventService.prototype.constructor = EventService; - - var prototypeAccessors = { $done: { configurable: true } }; - - /** - * logger function for overwrite - */ - EventService.prototype.logger = function logger () {}; - - ////////////////////////// - // PUBLIC METHODS // - ////////////////////////// - - /** - * Register your evt handler, note we don't check the type here, - * we expect you to be sensible and know what you are doing. - * @param {string} evt name of event - * @param {function} callback bind method --> if it's array or not - * @param {object} [context=null] to execute this call in - * @return {number} the size of the store - */ - EventService.prototype.$on = function $on (evt , callback , context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - var type = 'on'; - this.validate(evt, callback); - // first need to check if this evt is in lazy store - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register first then call later - if (lazyStoreContent === false) { - this.logger('($on)', (evt + " callback is not in lazy store")); - // @TODO we need to check if there was other listener to this - // event and are they the same type then we could solve that - // register the different type to the same event name - - return this.addToNormalStore(evt, type, callback, context) - } - this.logger('($on)', (evt + " found in lazy store")); - // this is when they call $trigger before register this callback - var size = 0; - lazyStoreContent.forEach(function (content) { - var payload = content[0]; - var ctx = content[1]; - var t = content[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.logger("($on)", ("call run on " + evt)); - this$1.run(callback, payload, context || ctx); - size += this$1.addToNormalStore(evt, type, callback, context || ctx); - }); - return size; - }; - - /** - * once only registered it once, there is no overwrite option here - * @NOTE change in v1.3.0 $once can add multiple listeners - * but once the event fired, it will remove this event (see $only) - * @param {string} evt name - * @param {function} callback to execute - * @param {object} [context=null] the handler execute in - * @return {boolean} result - */ - EventService.prototype.$once = function $once (evt , callback , context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'once'; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (lazyStoreContent === false) { - this.logger('($once)', (evt + " not in the lazy store")); - // v1.3.0 $once now allow to add multiple listeners - return this.addToNormalStore(evt, type, callback, context) - } else { - // now this is the tricky bit - // there is a potential bug here that cause by the developer - // if they call $trigger first, the lazy won't know it's a once call - // so if in the middle they register any call with the same evt name - // then this $once call will be fucked - add this to the documentation - this.logger('($once)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.logger('($once)', ("call run for " + evt)); - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - }; - - /** - * This one event can only bind one callbackback - * @param {string} evt event name - * @param {function} callback event handler - * @param {object} [context=null] the context the event handler execute in - * @return {boolean} true bind for first time, false already existed - */ - EventService.prototype.$only = function $only (evt, callback, context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'only'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($only)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($only)', (evt + " found data in lazy store to execute")); - var list = Array.from(lazyStoreContent); - // $only allow to trigger this multiple time on the single handler - list.forEach( function (l) { - var payload = l[0]; - var ctx = l[1]; - var t = l[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.logger("($only)", ("call run for " + evt)); - this$1.run(callback, payload, context || ctx); - }); - } - return added; - }; - - /** - * $only + $once this is because I found a very subtile bug when we pass a - * resolver, rejecter - and it never fire because that's OLD added in v1.4.0 - * @param {string} evt event name - * @param {function} callback to call later - * @param {object} [context=null] exeucte context - * @return {void} - */ - EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'onlyOnce'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($onlyOnce)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($onlyOnce)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== 'onlyOnce') { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.logger("($onlyOnce)", ("call run for " + evt)); - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - return added; - }; - - /** - * This is a shorthand of $off + $on added in V1.5.0 - * @param {string} evt event name - * @param {function} callback to exeucte - * @param {object} [context = null] or pass a string as type - * @param {string} [type=on] what type of method to replace - * @return {} - */ - EventService.prototype.$replace = function $replace (evt, callback, context, type) { - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = 'on'; - - if (this.validateType(type)) { - this.$off(evt); - var method = this['$' + type]; - this.logger("($replace)", evt, callback); - return Reflect.apply(method, this, [evt, callback, context]) - } - throw new Error((type + " is not supported!")) - }; - - /** - * trigger the event - * @param {string} evt name NOT allow array anymore! - * @param {mixed} [payload = []] pass to fn - * @param {object|string} [context = null] overwrite what stored - * @param {string} [type=false] if pass this then we need to add type to store too - * @return {number} if it has been execute how many times - */ - EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - this.validateEvt(evt); - var found = 0; - // first check the normal store - var nStore = this.normalStore; - this.logger('($trigger)', 'normalStore', nStore); - if (nStore.has(evt)) { - // @1.8.0 to add the suspend queue - var added = this.$queue(evt, payload, context, type); - this.logger('($trigger)', evt, 'found; add to queue: ', added); - if (added === true) { - this.logger('($trigger)', evt, 'not executed. Exit now.'); - return false; // not executed - } - var nSet = Array.from(nStore.get(evt)); - var ctn = nSet.length; - var hasOnce = false; - for (var i=0; i < ctn; ++i) { - ++found; - // this.logger('found', found) - var ref = nSet[i]; - var _ = ref[0]; - var callback = ref[1]; - var ctx = ref[2]; - var type$1 = ref[3]; - this.logger("($trigger)", ("call run for " + evt)); - this.run(callback, payload, context || ctx); - if (type$1 === 'once' || type$1 === 'onlyOnce') { - hasOnce = true; - } - } - if (hasOnce) { - nStore.delete(evt); - } - return found; - } - // now this is not register yet - this.addToLazyStore(evt, payload, context, type); - return found; - }; - - /** - * this is an alias to the $trigger - * @NOTE breaking change in V1.6.0 we swap the parameter around - * @param {string} evt event name - * @param {*} params pass to the callback - * @param {string} type of call - * @param {object} context what context callback execute in - * @return {*} from $trigger - */ - EventService.prototype.$call = function $call (evt, params, type, context) { - if ( type === void 0 ) type = false; - if ( context === void 0 ) context = null; - - var args = [evt, params, context, type]; - return Reflect.apply(this.$trigger, this, args) - }; - - /** - * remove the evt from all the stores - * @param {string} evt name - * @return {boolean} true actually delete something - */ - EventService.prototype.$off = function $off (evt) { - var this$1 = this; - - this.validateEvt(evt); - var stores = [ this.lazyStore, this.normalStore ]; - var found = false; - stores.forEach(function (store) { - if (store.has(evt)) { - found = true; - this$1.logger('($off)', evt); - store.delete(evt); - } - }); - return found; - }; - - /** - * return all the listener from the event - * @param {string} evtName event name - * @param {boolean} [full=false] if true then return the entire content - * @return {array|boolean} listerner(s) or false when not found - */ - EventService.prototype.$get = function $get (evt, full) { - if ( full === void 0 ) full = false; - - this.validateEvt(evt); - var store = this.normalStore; - if (store.has(evt)) { - return Array - .from(store.get(evt)) - .map( function (l) { - if (full) { - return l; - } - var key = l[0]; - var callback = l[1]; - return callback; - }) - } - return false; - }; - - /** - * store the return result from the run - * @param {*} value whatever return from callback - */ - prototypeAccessors.$done.set = function (value) { - this.logger('($done)', 'value: ', value); - if (this.keep) { - this.result.push(value); - } else { - this.result = value; - } - }; - - /** - * @TODO is there any real use with the keep prop? - * getter for $done - * @return {*} whatever last store result - */ - prototypeAccessors.$done.get = function () { - if (this.keep) { - this.logger('(get $done)', this.result); - return this.result[this.result.length - 1] - } - return this.result; - }; - - Object.defineProperties( EventService.prototype, prototypeAccessors ); - - return EventService; - }(NbEventServiceBase)); - - // default - - // this will generate a event emitter and will be use everywhere - // output - function getEventEmitter(debugOn) { - var logger = debugOn ? function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - args.unshift('[NBS]'); - console.log.apply(null, args); - }: undefined; - return new EventService({ logger: logger }) - } - - // this is the new Event base interface - /** - * this is the slim client without Fly, you pick the version of Fly to use - * This is a breaking change because it swap the input positions - * @param {object} fly fly.js - * @param {object} config configuration - * @return {object} the jsonql client instance - */ - function jsonqlStaticClient(fly, config) { - if ( config === void 0 ) config = {}; - - var contract = config.contract; - var opts = checkOptions$1(config); - var jsonqlBase = new JsonqlBaseClient(fly, opts); - var contractPromise = getContractFromConfig(jsonqlBase, contract); - var ee = getEventEmitter(opts.debugOn); - // finally - var methods = generator(jsonqlBase, opts, contractPromise, ee); - methods.eventEmitter = ee; - return methods; - } - - // This is the static version that build with the Fly for Browser - - // this is the slim client without Fly - function jsonqlStaticClientFull(config) { - if ( config === void 0 ) config = {}; - - return jsonqlStaticClient(new Fly(), config) - } - - return jsonqlStaticClientFull; - -}))); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClientStatic=e()}(this,(function(){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r,n=e((function(t,e){var r;r=function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=2)}([function(t,e,r){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};t.exports={type:function(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()},isObject:function(t,e){return e?"object"===this.type(t):t&&"object"===(void 0===t?"undefined":n(t))},isFormData:function(t){return"undefined"!=typeof FormData&&t instanceof FormData},trim:function(t){return t.replace(/(^\s*)|(\s*$)/g,"")},encode:function(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")},formatParams:function(t){var e="",r=!0,n=this;return this.isObject(t)?(function t(o,i){var a=n.encode,u=n.type(o);if("array"==u)o.forEach((function(e,r){n.isObject(e)||(r=""),t(e,i+"%5B"+r+"%5D")}));else if("object"==u)for(var c in o)t(o[c],i?i+"%5B"+a(c)+"%5D":a(c));else r||(e+="&"),r=!1,e+=i+"="+a(o)}(t,""),e):t},merge:function(t,e){for(var r in e)t.hasOwnProperty(r)?this.isObject(e[r],1)&&this.isObject(t[r],1)&&this.merge(t[r],e[r]):t[r]=e[r];return t}}},,function(t,e,r){var n=function(){function t(t,e){for(var r=0;r0&&(t+=(-1===t.indexOf("?")?"?":"&")+w.join("&")),a.open(r.method,t);try{a.withCredentials=!!r.withCredentials,a.timeout=r.timeout||0,"stream"!==y&&(a.responseType=y)}catch(t){}var j=r.headers[u]||r.headers[c],O="application/x-www-form-urlencoded";for(var S in o.trim((j||"").toLowerCase())===O?e=o.formatParams(e):o.isFormData(e)||-1===["object","array"].indexOf(o.type(e))||(O="application/json;charset=utf-8",e=JSON.stringify(e)),j||b||(r.headers[u]=O),r.headers)if(S===u&&o.isFormData(e))delete r.headers[S];else try{a.setRequestHeader(S,r.headers[S])}catch(t){}function k(t,e,n){v(l.p,(function(){if(t){n&&(e.request=r);var o=t.call(l,e,Promise);e=void 0===o?e:o}d(e)||(e=Promise[0===n?"resolve":"reject"](e)),e.then((function(t){s(t)})).catch((function(t){h(t)}))}))}function E(t){t.engine=a,k(l.onerror,t,-1)}function A(t,e){this.message=t,this.status=e}a.onload=function(){try{var t=a.response||a.responseText;t&&r.parseJson&&-1!==(a.getResponseHeader(u)||"").indexOf("json")&&!o.isObject(t)&&(t=JSON.parse(t));var e=a.responseHeaders;if(!e){e={};var n=(a.getAllResponseHeaders()||"").split("\r\n");n.pop(),n.forEach((function(t){if(t){var r=t.split(":")[0];e[r]=a.getResponseHeader(r)}}))}var i=a.status,c=a.statusText,s={data:t,headers:e,status:i,statusText:c};if(o.merge(s,a._response),i>=200&&i<300||304===i)s.engine=a,s.request=r,k(l.handler,s,0);else{var f=new A(c,i);f.response=s,E(f)}}catch(f){E(new A(f.msg,a.status))}},a.onerror=function(t){E(new A(t.msg||"Network Error",0))},a.ontimeout=function(){E(new A("timeout [ "+a.timeout+"ms ]",1))},a._options=r,setTimeout((function(){a.send(b?null:e)}),0)}(n):s(n)}),(function(t){h(t)}))}))}));return h.engine=a,h}},{key:"all",value:function(t){return Promise.all(t)}},{key:"spread",value:function(t){return function(e){return t.apply(null,e)}}}]),t}();a.default=a,["get","post","put","patch","head","delete"].forEach((function(t){a.prototype[t]=function(e,r,n){return this.request(e,r,o.merge({method:t},n))}})),["lock","unlock","clear"].forEach((function(t){a.prototype[t]=function(){this.interceptors.request[t]()}})),t.exports=a}])},t.exports=r()})),o=(r=n)&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r,i="application/vnd.api+json",a={Accept:i,"Content-Type":[i,"charset=utf-8"].join(";")},u="query",c="mutation",s="socket",f="payload",l="condition",p="TS",h=["POST","PUT"],d="type",v="optional",g="enumv",y="args",b="checker",m="alias",_="__checked__",w={desc:"y"},j="No message",O="onResult",S="onError",k=Array.isArray,E="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},A="object"==typeof E&&E&&E.Object===Object&&E,T="object"==typeof self&&self&&self.Object===Object&&self,x=A||T||Function("return this")(),P=x.Symbol,q=Object.prototype,C=q.hasOwnProperty,$=q.toString,z=P?P.toStringTag:void 0;var N=Object.prototype.toString;var R="[object Null]",M="[object Undefined]",F=P?P.toStringTag:void 0;function J(t){return null==t?void 0===t?M:R:F&&F in Object(t)?function(t){var e=C.call(t,z),r=t[z];try{t[z]=void 0;var n=!0}catch(t){}var o=$.call(t);return n&&(e?t[z]=r:delete t[z]),o}(t):function(t){return N.call(t)}(t)}function I(t,e){return function(r){return t(e(r))}}var U=I(Object.getPrototypeOf,Object);function D(t){return null!=t&&"object"==typeof t}var H="[object Object]",L=Function.prototype,B=Object.prototype,K=L.toString,G=B.hasOwnProperty,V=K.call(Object);function W(t){if(!D(t)||J(t)!=H)return!1;var e=U(t);if(null===e)return!0;var r=G.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&K.call(r)==V}function Y(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&it(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var wt=function(t){return k(t)?t:[t]},jt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},Ot=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),xt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),Pt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),qt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),Ct=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),$t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),zt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Nt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),Rt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),Mt=Object.freeze({__proto__:null,Jsonql406Error:St,Jsonql500Error:kt,JsonqlForbiddenError:Et,JsonqlAuthorisationError:At,JsonqlContractAuthError:Tt,JsonqlResolverAppError:xt,JsonqlResolverNotFoundError:Pt,JsonqlEnumError:qt,JsonqlTypeError:Ct,JsonqlCheckerError:$t,JsonqlValidationError:zt,JsonqlError:Nt,JsonqlServerError:Rt}),Ft=Nt,Jt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function It(t){if(Jt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||j,a=e.detail||e;if(o&&Mt[o])throw new Mt[r](i,a);throw new Ft(i,a)}return t}var Ut=function(t){return!!k(t)||null!=t&&""!==_t(t)},Dt="[object Number]";function Ht(t){return function(t){return"number"==typeof t||D(t)&&J(t)==Dt}(t)&&t!=+t}var Lt="[object String]";function Bt(t){return"string"==typeof t||!k(t)&&D(t)&&J(t)==Lt}var Kt=function(t){return!Bt(t)&&!Ht(parseFloat(t))},Gt=function(t){return""!==_t(t)&&Bt(t)},Vt=function(t){return null!=t&&"boolean"==typeof t},Wt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==_t(t)&&(!1===e||!0===e&&null!==t)},Yt=d,Qt=v,Xt=g,Zt=y,te=b,ee=m,re="continue",ne=function(t){switch(t){case"number":return Kt;case"string":return Gt;case"boolean":return Vt;default:return Wt}},oe=function(t,e){return void 0===e&&(e=""),!!k(t)&&(""===e||""===_t(e)||!(t.filter((function(t){return!ne(e)(t)})).length>0))},ie=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ae=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ne(e)(t)})).length)})).length:e.length>e.filter((function(t){return!oe(r,t)})).length};var ue,ce=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[ue?a:++n];if(!1===e(o[u],u,o))break}return t};var se="[object Arguments]";function fe(t){return D(t)&&J(t)==se}var le=Object.prototype,pe=le.hasOwnProperty,he=le.propertyIsEnumerable,de=fe(function(){return arguments}())?fe:function(t){return D(t)&&pe.call(t,"callee")&&!he.call(t,"callee")};var ve="object"==typeof exports&&exports&&!exports.nodeType&&exports,ge=ve&&"object"==typeof module&&module&&!module.nodeType&&module,ye=ge&&ge.exports===ve?x.Buffer:void 0,be=(ye?ye.isBuffer:void 0)||function(){return!1},me=9007199254740991,_e=/^(?:0|[1-9]\d*)$/;function we(t,e){var r=typeof t;return!!(e=null==e?me:e)&&("number"==r||"symbol"!=r&&_e.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=je}var Se={};Se["[object Float32Array]"]=Se["[object Float64Array]"]=Se["[object Int8Array]"]=Se["[object Int16Array]"]=Se["[object Int32Array]"]=Se["[object Uint8Array]"]=Se["[object Uint8ClampedArray]"]=Se["[object Uint16Array]"]=Se["[object Uint32Array]"]=!0,Se["[object Arguments]"]=Se["[object Array]"]=Se["[object ArrayBuffer]"]=Se["[object Boolean]"]=Se["[object DataView]"]=Se["[object Date]"]=Se["[object Error]"]=Se["[object Function]"]=Se["[object Map]"]=Se["[object Number]"]=Se["[object Object]"]=Se["[object RegExp]"]=Se["[object Set]"]=Se["[object String]"]=Se["[object WeakMap]"]=!1;var ke,Ee="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ae=Ee&&"object"==typeof module&&module&&!module.nodeType&&module,Te=Ae&&Ae.exports===Ee&&A.process,xe=function(){try{var t=Ae&&Ae.require&&Ae.require("util").types;return t||Te&&Te.binding&&Te.binding("util")}catch(t){}}(),Pe=xe&&xe.isTypedArray,qe=Pe?(ke=Pe,function(t){return ke(t)}):function(t){return D(t)&&Oe(t.length)&&!!Se[J(t)]},Ce=Object.prototype.hasOwnProperty;function $e(t,e){var r=k(t),n=!r&&de(t),o=!r&&!n&&be(t),i=!r&&!n&&!o&&qe(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},Ye.prototype.set=function(t,e){var r=this.__data__,n=Ve(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var Qe,Xe=x["__core-js_shared__"],Ze=(Qe=/[^.]+$/.exec(Xe&&Xe.keys&&Xe.keys.IE_PROTO||""))?"Symbol(src)_1."+Qe:"";var tr=Function.prototype.toString;function er(t){if(null!=t){try{return tr.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var rr=/^\[object .+?Constructor\]$/,nr=Function.prototype,or=Object.prototype,ir=nr.toString,ar=or.hasOwnProperty,ur=RegExp("^"+ir.call(ar).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function cr(t){return!(!Fe(t)||function(t){return!!Ze&&Ze in t}(t))&&(He(t)?ur:rr).test(er(t))}function sr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return cr(r)?r:void 0}var fr=sr(x,"Map"),lr=sr(Object,"create");var pr="__lodash_hash_undefined__",hr=Object.prototype.hasOwnProperty;var dr=Object.prototype.hasOwnProperty;var vr="__lodash_hash_undefined__";function gr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&kr?new jr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=ie(t))?!ae({arg:r},e):!ne(t)(r))})).length)})).length}return!1},Kn=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Bn,null,a);case"array"===t:return!oe(e.arg);case!1!==(r=ie(t)):return!ae(e,r);default:return!ne(t)(e.arg)}},Gn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Vn=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!oe(e))throw new Nt("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!oe(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==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Gn(t,a):t,index:r,param:a,optional:i}}));default:throw new Nt("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Ut(e)&&!(r.type.length>r.type.filter((function(e){return Kn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Kn(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Wn=function(){try{var t=sr(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function Yn(t,e,r){"__proto__"==e&&Wn?Wn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function Qn(t,e,r){(void 0===r||Ge(t[e],r))&&(void 0!==r||e in t)||Yn(t,e,r)}var Xn="object"==typeof exports&&exports&&!exports.nodeType&&exports,Zn=Xn&&"object"==typeof module&&module&&!module.nodeType&&module,to=Zn&&Zn.exports===Xn?x.Buffer:void 0,eo=to?to.allocUnsafe:void 0;function ro(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new Ar(n).set(new Ar(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var no=Object.create,oo=function(){function t(){}return function(e){if(!Fe(e))return{};if(no)return no(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function io(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ao=Object.prototype.hasOwnProperty;function uo(t,e,r){var n=t[e];ao.call(t,e)&&Ge(n,r)&&(void 0!==r||e in t)||Yn(t,e,r)}var co=Object.prototype.hasOwnProperty;function so(t){if(!Fe(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Ne(t),r=[];for(var n in t)("constructor"!=n||!e&&co.call(t,n))&&r.push(n);return r}function fo(t){return Le(t)?$e(t,!0):so(t)}function lo(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=bo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(yo);function jo(t,e){return wo(function(t,e,r){return e=go(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=go(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Oo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!Fe(r))return!1;var n=typeof e;return!!("number"==n?Le(r)&&we(e,r.length):"string"==n&&e in r)&&Ge(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,wt(t))}),Reflect.apply(t,null,r))}};function Vo(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function Wo(t,e,r,n){void 0===n&&(n=!1);var o=Vo(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var Yo=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return Lo(r,i).then((function(){return t.query.apply(t,[e,a,u])}))}},Qo=function(t,e,r,n,o){var i={},a=function(t){i=Wo(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return Lo(a,i).then((function(){return e.query.apply(e,[t,a,u])}))}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},Xo=function(t,e,r,n,o){var i={},a=function(t){i=Wo(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return Lo(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])}))}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Zo=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Yo(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Yo(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var ti=function(t,e){return function(r){for(var n=[],o=arguments.length-1;o-- >0;)n[o]=arguments[o+1];return new Promise((function(o,i){t.$only(Ot(e,r,O),o),t.$only(Ot(e,r,S),i),t.$trigger(e,{resolverName:r,args:n})}))}},ei=function(t,e,r){var n=t.$queues,o=r.debugOn;o&&console.info("(validateRegisteredEvents)","storedEvt",n),n.forEach((function(t){var r=t[0],n=t[1].resolverName;if(o&&console.info("(validateRegisteredEvents)",r,n),!e[r][n])throw new Error(r+"."+n+" not existed in contract!")}))};function ri(t,e,r,n){var o=function(t,e,r,n){return Go(Qo,Xo,Zo)({},t,e,r,n)}(t,e,r,n);ei(e,n,r);var i=function(t){e.$only(t,(function(r){var n=r.resolverName,i=r.args;o[t][n]?Reflect.apply(o[t][n],null,i).then((function(r){e.$trigger(Ot(t,n,O),r)})).catch((function(r){e.$trigger(Ot(t,n,S),r)})):console.error(n+" is not defined in the contract!")}))};for(var a in o)i(a);setTimeout((function(){e.$suspend=!1}),1)}var ni=function(t,e,r,n){n.$suspend=!0,r.then((function(r){ri(t,n,e,r)}));var o={query:ti(n,"query"),mutation:ti(n,"mutation"),auth:ti(n,"auth"),getToken:function(){return t.rawAuthToken}};return e.exposeContract&&(o.getContract=function(){return t.get()}),e.enableAuth&&(o.userdata=function(){return t.userdata}),o.version="1.5.1",o};function oi(t){return!!function(t){return W(t)&&(jt(t,u)||jt(t,c)||jt(t,s))}(t)&&t}function ii(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var ai=function(t,e){return void 0===e&&(e={}),oi(e)?Promise.resolve(e):t.getContract()},ui="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function ci(t){this.message=t}ci.prototype=new Error,ci.prototype.name="InvalidCharacterError";var si="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new ci("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=ui.indexOf(n);return a};var fi=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(si(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return si(e)}};function li(t){this.message=t}li.prototype=new Error,li.prototype.name="InvalidTokenError";var pi=function(t,e){if("string"!=typeof t)throw new li("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(fi(t.split(".")[r]))}catch(t){throw new li("Invalid token specified: "+t.message)}},hi=li;pi.InvalidTokenError=hi;var di,vi,gi,yi,bi,mi,_i,wi,ji,Oi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Si(t){if(Gt(t))return function(t){var e=t.iat||Oi(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Nt("Token has expired on "+r,t)}return t}(pi(t));throw new Nt("Token must be a string!")}Bo("HS256",["string"]),Bo(!1,["boolean","number","string"],((di={})[m]="exp",di[v]=!0,di)),Bo(!1,["boolean","number","string"],((vi={})[m]="nbf",vi[v]=!0,vi)),Bo(!1,["boolean","string"],((gi={})[m]="iss",gi[v]=!0,gi)),Bo(!1,["boolean","string"],((yi={})[m]="sub",yi[v]=!0,yi)),Bo(!1,["boolean","string"],((bi={})[m]="iss",bi[v]=!0,bi)),Bo(!1,["boolean"],((mi={})[v]=!0,mi)),Bo(!1,["boolean","string"],((_i={})[v]=!0,_i)),Bo(!1,["boolean","string"],((wi={})[v]=!0,wi)),Bo(!1,["boolean"],((ji={})[v]=!0,ji));var ki=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},Ei=Object.assign?Object.assign:function(t,e,r,n){for(var o=arguments,i=1;i=0;e--){var r=Vi().key(e);t(Wi(r),r)}},remove:function(t){return Vi().removeItem(t)},clearAll:function(){return Vi().clear()}};function Vi(){return Ki.localStorage}function Wi(t){return Vi().getItem(t)}var Yi=Pi.trim,Qi={name:"cookieStorage",read:function(t){if(!t||!ea(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Xi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Xi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Zi,remove:ta,clearAll:function(){Zi((function(t,e){ta(e)}))}},Xi=Pi.Global.document;function Zi(t){for(var e=Xi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Yi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function ta(t){t&&ea(t)&&(Xi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function ea(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Xi.cookie)}var ra=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var na=Pi.bind,oa=Pi.each,ia=Pi.create,aa=Pi.slice,ua=function(){var t=ia(ca,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,na(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,na(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),oa(r,(function(e,r){t.fire(r,void 0,e)}))}}};var ca={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,na(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=aa(arguments,1);oa(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},sa=e((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),fa=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=sa.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=sa.compress(this._serialize(r));t(e,n)}}};var la=[Gi,Qi],pa=[ra,ua,fa],ha=Hi.createStore(la,pa),da=Pi.Global;function va(){return da.sessionStorage}function ga(t){return va().getItem(t)}var ya=[{name:"sessionStorage",read:ga,write:function(t,e){return va().setItem(t,e)},each:function(t){for(var e=va().length-1;e>=0;e--){var r=va().key(e);t(ga(r),r)}},remove:function(t){return va().removeItem(t)},clearAll:function(){return va().clear()}},Qi],ba=[ra,fa],ma=Hi.createStore(ya,ba),_a=ha,wa=ma,ja=function(t){var e;return(e={}).args=t,e};function Oa(t,e){var r;return(r={})[t]=e,r[p]=[ki()],r}var Sa=function(t){return jt(t,"data")&&!jt(t,"error")?t.data:t},ka=function(t){this.opts=t,this.instanceKey=ii(this.opts.hostname)+"",this.localStore=_a,this.sessionStore=wa},Ea={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};ka.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?So({},o,e):e,r))},ka.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},ka.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},ka.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},Ea.lset.set=function(t){return this.__setMethod("localStore",t)},Ea.lget.get=function(){return this.__getMethod("localStore")},ka.prototype.ldel=function(t){return this.__delMethod("localStore",t)},ka.prototype.lclear=function(){return this.__clearMethod("localStore")},Ea.sset.set=function(t){return this.__setMethod("sessionStore",t)},Ea.sget.get=function(){return this.__getMethod("sessionStore")},ka.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},ka.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(ka.prototype,Ea);var Aa=h[0],Ta=h[1],xa=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Si)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(Ho(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new zt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&Ho(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!oi(t))throw new zt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=oi(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={headers:{configurable:!0}};return r.headers.set=function(t){this.extraHeader=t},e.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=So({},{_cb:ki()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=So({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=So({},{method:Aa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},e.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},e.prototype.processJsonp=function(t){return Sa(t)},e.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=Do(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):Sa(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new Rt("Server side error",r)}))},e.prototype.getHeaders=function(){return this.opts.enableAuth?So({},a,this.getAuthHeader(),this.extraHeader):So({},a,this.extraHeader)},e.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},e.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=So({},this.extraParams,w)),this.request({},{method:"GET"},this.contractHeader).then(It).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new Rt("getRemoteContract",e)}))},e.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Bt(t)&&k(e)){var n=ja(e);return!0===r?n:Oa(t,n)}throw new zt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(It)},e.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[f]=e,o[l]=r,!0===n)return o;if(Bt(t))return Oa(t,o);throw new zt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:Ta}).then(It)},Object.defineProperties(e.prototype,r),e}(ka)))),Pa={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:i,BEARER:"Bearer",AUTH_HEADER:"Authorization"},qa={hostname:Bo(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:Bo("jsonql",["string"]),loginHandlerName:Bo("login",["string"]),logoutHandlerName:Bo("logout",["string"]),enableJsonp:Bo(!1,["boolean"]),enableAuth:Bo(!1,["boolean"]),useJwt:Bo(!0,["boolean"]),persistToken:Bo(!1,["boolean","number"]),useLocalstorage:Bo(!0,["boolean"]),storageKey:Bo("jsonqlstore",["string"]),authKey:Bo("jsonqlauthkey",["string"]),contractExpired:Bo(0,["number"]),keepContract:Bo(!0,["boolean"]),exposeContract:Bo(!1,["boolean"]),exposeStore:Bo(!1,["boolean"]),showContractDesc:Bo(!1,["boolean"]),contractKey:Bo(!1,["boolean"]),contractKeyName:Bo("X-JSONQL-CV-KEY",["string"]),enableTimeout:Bo(!1,["boolean"]),timeout:Bo(5e3,["number"]),returnInstance:Bo(!1,["boolean"]),allowReturnRawToken:Bo(!1,["boolean"]),debugOn:Bo(!1,["boolean"])};function Ca(t){return Vo(t,_)?t:function(t){return Ko(t,qa,Pa)}(t)}var $a=new WeakMap,za=new WeakMap,Na=function(){this.__suspend__=null,this.queueStore=new Set},Ra={$suspend:{configurable:!0},$queues:{configurable:!0}};Ra.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Na.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ra.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Na.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Na.prototype,Ra);var Ma=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){$a.set(this,t)},r.normalStore.get=function(){return $a.get(this)},r.lazyStore.set=function(t){za.set(this,t)},r.lazyStore.get=function(){return za.get(this)},e.prototype.hashFnToKey=function(t){return ii(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Na));function Fa(t,e){void 0===e&&(e={});var r,n=e.contract,o=Ca(e),i=new xa(t,o),a=ai(i,n),u=(r=o.debugOn,new Ma({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),c=ni(i,o,a,u);return c.eventEmitter=u,c}return function(t){return void 0===t&&(t={}),Fa(new o,t)}})); //# sourceMappingURL=jsonql-client.static.js.map diff --git a/packages/http-client/dist/jsonql-client.static.js.map b/packages/http-client/dist/jsonql-client.static.js.map index 0d1c3e77..9e063d38 100644 --- a/packages/http-client/dist/jsonql-client.static.js.map +++ b/packages/http-client/dist/jsonql-client.static.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client.static.js","sources":["../node_modules/lodash-es/isArray.js","../node_modules/rollup-plugin-node-globals/src/global.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/lodash-es/_arrayMap.js","../node_modules/lodash-es/_baseSlice.js","../node_modules/lodash-es/_baseFindIndex.js","../node_modules/lodash-es/_baseIsNaN.js","../node_modules/lodash-es/_strictIndexOf.js","../node_modules/lodash-es/_asciiToArray.js","../node_modules/lodash-es/_hasUnicode.js","../node_modules/lodash-es/_unicodeToArray.js","../node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-errors/src/get-error-by-status.js","../node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-errors/src/resolver-not-found-error.js","../node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-errors/src/index.js","../node_modules/jsonql-errors/src/client-errors-handler.js","../node_modules/jsonql-errors/src/get-error-name-by-instance.js","../node_modules/jsonql-errors/index.js","../node_modules/jsonql-params-validator/src/number.js","../node_modules/jsonql-params-validator/src/string.js","../node_modules/jsonql-params-validator/src/boolean.js","../node_modules/jsonql-params-validator/src/any.js","../node_modules/jsonql-params-validator/src/constants.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/_listCacheClear.js","../node_modules/lodash-es/eq.js","../node_modules/lodash-es/_stackDelete.js","../node_modules/lodash-es/_stackGet.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-params-validator/src/validator.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/negate.js","../node_modules/lodash-es/_baseFindKey.js","../node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-params-validator/src/options/check-options-sync.js","../node_modules/jsonql-params-validator/src/options/construct-config.js","../node_modules/jsonql-params-validator/src/options/index.js","../node_modules/jsonql-params-validator/index.js","../src/core/methods-generator.js","../src/core/jsonql-static-generator.js","../node_modules/jsonql-utils/src/contract.js","../node_modules/nb-event-service/src/hash-code.js","../src/utils.js","../node_modules/jwt-decode/lib/atob.js","../node_modules/jsonql-jwt/src/client/decode-token/decode-token.js","../node_modules/jsonql-utils/src/timestamp.js","../node_modules/store/plugins/defaults.js","../src/stores/local-store.js","../src/stores/session-store.js","../src/stores/index.js","../node_modules/jsonql-utils/src/params-api.js","../node_modules/jsonql-utils/src/results.js","../src/base/store-cls.js","../src/base/http-cls.js","../src/base/contract-cls.js","../src/base/auth-cls.js","../src/base/base-cls.js","../src/base/index.js","../src/options/base-options.js","../src/options/check-options.js","../src/options/index.js","../node_modules/nb-event-service/src/suspend.js","../node_modules/nb-event-service/src/store-service.js","../node_modules/nb-event-service/src/event-service.js","../node_modules/nb-event-service/index.js","../src/ee.js","../src/static.js","../src/static-full.js"],"sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length;\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg];\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @return {*} json object on success\n */\nconst parse = function(n) {\n try {\n return JSON.parse(n)\n } catch(e) {\n return n;\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false;\n /*\n console.info('obj', obj)\n console.error(e)\n throw new Error(e)\n */\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = (n) => {\n if (typeof n === 'string') {\n return parse(n)\n }\n return JSON.parse(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== '';\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n","// just a simple util method to return the error based on the status code\n/**\n * @param {number} statusCode to check\n * @param {boolean} contract if this is a contract call or not\n * @return {string} the error name\n */\nexport default function getErrorByStatus(statusCode, contract = false) {\n switch (statusCode) {\n case 401:\n return contract ? 'JsonqlContractAuthError' : 'JsonqlAuthorisationError';\n case 403:\n return 'JsonqlForbiddenError';\n case 404:\n return 'JsonqlResolverNotFoundError';\n case 406:\n return 'Jsonql406Error';\n case 500:\n return 'Jsonql500Error';\n default:\n return 'JsonqlError';\n }\n}\n","/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error)\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","/**\n * This is a custom error to throw when could not find the resolver\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class JsonqlResolverNotFoundError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlResolverNotFoundError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlResolverNotFoundError);\n }\n }\n\n static get statusCode() {\n return 404;\n }\n\n static get name() {\n return 'JsonqlResolverNotFoundError';\n }\n}\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError);\n }\n }\n\n static get name() {\n return 'JsonqlEnumError';\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlTypeError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError);\n }\n }\n\n static get name() {\n return 'JsonqlTypeError';\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args)\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError)\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError';\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError';\n }\n}\n","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message)\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// server side\nimport Jsonql406Error from './406-error';\nimport Jsonql500Error from './500-error';\nimport JsonqlAuthorisationError from './authorisation-error';\nimport JsonqlContractAuthError from './contract-auth-error';\nimport JsonqlResolverAppError from './resolver-app-error';\nimport JsonqlResolverNotFoundError from './resolver-not-found-error';\n\n// check options error\nimport JsonqlEnumError from './enum-error';\nimport JsonqlTypeError from './type-error';\nimport JsonqlCheckerError from './checker-error';\n// share\nimport JsonqlValidationError from './validation-error';\nimport JsonqlError from './error';\n\nimport JsonqlServerError from './server-error';\n\nexport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n};\n","// this will add directly to the then call in each http call\n\nimport * as errors from './index';\nimport getErrorByStatus from './get-error-by-status';\nimport { NO_ERROR_MSG } from 'jsonql-constants';\nconst { JsonqlError } = errors;\n\n/**\n * We can not just check something like result.data what if the result if false?\n * @param {object} obj the result object\n * @param {string} key we want to check if its exist or not\n * @return {boolean} true on found\n */\nconst isObjectHasKey = (obj, key) => {\n const keys = Object.keys(obj)\n return !!keys.filter(k => key === k).length;\n}\n\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nexport default function clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n","// get error name by instance\nconst UNKNOWN_ERROR = 'unknown'\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {array} filtered with name as value\n */\nfunction mapErrToName(errs, e) {\n return errs.filter(err => e instanceof err)\n .map(err => err.name)\n}\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {string} name of the error object\n */\nfunction getErrorNameByInstance(errs, e) {\n let error = mapErrToName(errs, e)\n return error.length ? error[0] : UNKNOWN_ERROR\n}\n\n/**\n * the same as above with a default JsonqlError as default\n * @param {array} errs same\n * @param {object} e error itself\n * @return {string} the name of the error\n */\nfunction getErrorNameByInstanceWithDefault(errs, e) {\n let name = getErrorNameByInstance(errs, e)\n return name === UNKNOWN_ERROR ? 'JsonqlError' : name;\n}\n\n\nexport {\n getErrorNameByInstanceWithDefault,\n getErrorNameByInstance,\n UNKNOWN_ERROR\n}\n","// jsonql-errors main interface\nimport getErrorByStatus from './src/get-error-by-status'\nimport clientErrorsHandler from './src/client-errors-handler'\nimport {\n getErrorNameByInstance,\n getErrorNameByInstanceWithDefault,\n UNKNOWN_ERROR\n} from './src/get-error-name-by-instance'\nimport finalCatch from './src/final-catch.js'\nconst JSONQL_ERRORS_INFO = '__PLACEHOLDER__'\nimport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n JsonqlValidationError,\n JsonqlError,\n JsonqlServerError\n} from './src'\n// export\nexport {\n JSONQL_ERRORS_INFO,\n UNKNOWN_ERROR,\n\n getErrorByStatus,\n clientErrorsHandler,\n finalCatch,\n getErrorNameByInstance,\n getErrorNameByInstanceWithDefault,\n\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n}\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false;\n}\n\nexport default checkIsString\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nexport const ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\n","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber;\n case STRING_TYPE:\n return checkIsString;\n case BOOLEAN_TYPE:\n return checkIsBoolean;\n default:\n return checkIsAny;\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false;\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false;\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p;\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length;\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length;\n}\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport filter from 'lodash-es/filter'\n\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true;\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (_value !== undefined) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true;\n }).length)\n }).length;\n }\n }\n return false;\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p;\n let _args = [arg];\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return Reflect.apply(checkIsObject, null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\n\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n checkIsObject,\n combineFn,\n notEmpty\n} from './index'\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params;\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false;\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (arg !== undefined) {\n return arg;\n }\n return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ))\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ))\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ))\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length:\n let ctn = params.length;\n // this happens when we have those array. type\n let _type = [ DEFAULT_TYPE ]\n // we only looking at the first one, this might be a @BUG\n /*\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n } */\n // if we use the params as guide then the rest will get throw out\n // which is not what we want, instead, anything without the param\n // will get a any type and optional flag\n return args.map((arg, i) => {\n let optional = i >= ctn ? true : !!params[i].optional\n let param = params[i] || { type: _type, name: `_${i}` }\n return {\n arg: optional ? getOptionalValue(arg, param) : arg,\n index: i,\n param,\n optional\n }\n })\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n // v1.4.4 this fixed the problem, the root level optional is from the last fn\n if (p.optional === true || p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length;\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport isFunction from 'lodash-es/isFunction'\nimport merge from 'lodash-es/merge'\nimport mapValues from 'lodash-es/mapValues'\n\nimport JsonqlEnumError from 'jsonql-errors/src/enum-error'\nimport JsonqlTypeError from 'jsonql-errors/src/type-error'\nimport JsonqlCheckerError from 'jsonql-errors/src/checker-error'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true;\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // log('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n // log(ENUM_KEY, value[ENUM_KEY])\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n // log(CHECKER_KEY, value[CHECKER_KEY])\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args;\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","// this is port back from the client to share across all projects\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return merge(\n runValidation(\n prepareArgsForValidation(config, appProps),\n cb\n ),\n constProps\n )\n}\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\nimport checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n };\n if (optional === true) {\n base[OPTIONAL_KEY] = true;\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv;\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker;\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias;\n }\n return base;\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__';\n\n/**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n checkConfigAsync,\n checkConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nexport const inArray = isInArray;\nexport const isObjectHasKey = isObjectHasKeyFn;\n","// breaking out the inner methods generator in here\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { LOGOUT_NAME, LOGIN_NAME, KEY_WORD } from 'jsonql-constants'\nimport { chainFns } from 'jsonql-utils/src/chain-fns'\nimport { injectToFn } from 'jsonql-utils/src/obj-define-props'\n\n/**\n * generate authorisation specific methods\n * @param {object} jsonqlInstance instance of this\n * @param {string} name of method\n * @param {object} opts configuration\n * @param {object} contract to match\n * @return {function} for use\n */\nconst authMethodGenerator = (jsonqlInstance, name, opts, contract) => {\n return (...args) => {\n const params = contract.auth[name].params;\n const values = params.map((p, i) => args[i])\n const header = args[params.length] || {};\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [name, values, header])\n )\n .catch(finalCatch)\n }\n}\n\n/**\n * Break up the different type each - create query methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let query = {}\n for (let queryFn in contract.query) {\n // to keep it clean we use a param to id the auth method\n // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn;\n // generate the query method\n query = injectToFn(query, queryFn, function queryFnHandler(...args) {\n const params = contract.query[queryFn].params;\n const _args = params.map((param, i) => args[i])\n // debug('query', queryFn, _params);\n // @TODO this need to change to a different way to add an extra header\n const header = {}\n // @TODO validate against the type\n return validateAsync(_args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [queryFn, _args, header])\n )\n .catch(finalCatch)\n })\n }\n obj.query = query;\n // create an alias to the helloWorld method\n obj.helloWorld = query.helloWorld;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create mutation methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let mutation = {}\n // process the mutation, the reason the mutation has a fixed number of parameters\n // there is only the payload, and conditions parameters\n // plus a header at the end\n for (let mutationFn in contract.mutation) {\n mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header = {}) {\n const args = [payload, conditions];\n const params = contract.mutation[mutationFn].params;\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .mutation\n .apply(jsonqlInstance, [mutationFn, payload, conditions, header])\n )\n .catch(e => {\n console.error('--- mutation fn catch ---', e)\n return finalCatch(e)\n })\n })\n }\n obj.mutation = mutation;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create auth methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createAuthMethods = (obj, jsonqlInstance, ee, config, contract) => {\n if (config.enableAuth && contract.auth) {\n let auth = {} // v1.3.1 add back the auth prop name in contract\n const { loginHandlerName, logoutHandlerName } = config;\n if (contract.auth[loginHandlerName]) {\n // changing to the name the config specify\n auth[loginHandlerName] = function loginHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance))\n .then(token => {\n ee.$trigger(LOGIN_NAME, token)\n return token;\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) {\n auth[logoutHandlerName] = function logoutHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance))\n .then(r => {\n ee.$trigger(LOGOUT_NAME, r)\n return r;\n })\n }\n } else {\n auth[logoutHandlerName] = function logoutHandlerFn() {\n jsonqlInstance.postLogoutAction(KEY_WORD)\n ee.$trigger(LOGOUT_NAME, KEY_WORD)\n }\n }\n obj.auth = auth;\n }\n\n return obj;\n}\n\n/**\n * Here just generate the methods calls\n * @param {object} jsonqlInstance what it said\n * @param {object} ee event emitter\n * @param {object} config configuration\n * @param {object} contract the map\n * @return {object} with mapped methods\n */\nexport function methodsGenerator(jsonqlInstance, ee, config, contract) {\n let obj = {}\n const executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods)\n return executor(obj, jsonqlInstance, ee, config, contract)\n}\n","// This generator will use the old style\n// with default methods\nimport { ON_RESULT_PROP_NAME, ON_ERROR_PROP_NAME } from 'jsonql-constants'\nimport { createEvt } from 'jsonql-utils/src/generic'\n\nimport { methodsGenerator } from './methods-generator'\n\n/**\n * Group all the same methods together\n * @param {object} ee event emitters\n * @param {string} type query, mutation or auth\n * @param {string} resolverName use as the guide\n * @param {array} args from the call\n * @return {function} the handler itself\n */\nconst handler = (ee, type) => {\n // we don't run validate here because we want until the contract is ready\n return (resolverName, ...args) => (\n new Promise((resolver, rejecter) => {\n // this are the callbacks\n ee.$only(createEvt(type, resolverName, ON_RESULT_PROP_NAME), resolver)\n ee.$only(createEvt(type, resolverName, ON_ERROR_PROP_NAME), rejecter)\n // this is the main call\n ee.$trigger(type, { resolverName, args })\n })\n )\n}\n\n/**\n * @param {object} ee eventEmitter\n * @param {object} contract the map\n * @param {object} config configuration\n */\nconst validateRegisteredEvents = (ee, contract, config) => {\n const storedEvt = ee.$queues;\n const debug = config.debugOn;\n if (debug) {\n console.info('(validateRegisteredEvents)', 'storedEvt', storedEvt)\n }\n storedEvt.forEach(args => {\n let [type, payload] = args;\n let { resolverName } = payload;\n if (debug) {\n console.info('(validateRegisteredEvents)', type, resolverName)\n }\n if (!contract[type][resolverName]) {\n throw new Error(`${type}.${resolverName} not existed in contract!`)\n }\n })\n}\n\n/**\n * set up all the event handlers once the contract is ready\n * @param {object} jsonqlInstance what the name said\n * @param {object} ee event emitter\n * @param {object} config the configuration\n * @param {object} contract the map\n * @return {void} nothing\n */\nfunction setupEventHandlers(jsonqlInstance, ee, config, contract) {\n let methods = methodsGenerator(jsonqlInstance, ee, config, contract)\n validateRegisteredEvents(ee, contract, config)\n // create handler\n for (let type in methods) {\n // setup event listeners - only one listener per type\n ee.$only(type, function({resolverName, args}) {\n if (methods[type][resolverName]) {\n Reflect.apply(methods[type][resolverName], null, args)\n .then(result => {\n ee.$trigger(createEvt(type, resolverName, ON_RESULT_PROP_NAME), result)\n })\n .catch(err => {\n ee.$trigger(createEvt(type, resolverName, ON_ERROR_PROP_NAME), err)\n })\n } else {\n console.error(`${resolverName} is not defined in the contract!`)\n }\n })\n }\n // all done now release the queue if any\n setTimeout(() => {\n ee.$suspend = false;\n }, 1)\n}\n\n/**\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} config options\n * @param {object} contractPromise an unresolve promise\n * @param {object} ee eventEmitter\n * @return {object} constructed functions call\n */\nconst generator = (jsonqlInstance, config, contractPromise, ee) => {\n ee.$suspend = true; // hold all the calls\n // wait for the promise to resolve\n contractPromise.then(contract => {\n setupEventHandlers(jsonqlInstance, ee, config, contract)\n })\n // construct the api\n let obj = {\n query: handler(ee, 'query'),\n mutation: handler(ee, 'mutation'),\n auth: handler(ee, 'auth')\n }\n // allow getting the token for valdiate agains the socket\n obj.getToken = () => jsonqlInstance.rawAuthToken;\n // this will pass to the ws-client if needed\n // obj.eventEmitter = ee;\n // this will require a param\n if (config.exposeContract) {\n obj.getContract = () => jsonqlInstance.get()\n }\n if (config.enableAuth) {\n obj.userdata = () => jsonqlInstance.userdata;\n }\n obj.version = '__VERSION__';\n // output\n return obj;\n}\n\nexport default generator;\n","// split the contract into the node side and the generic side\nimport { isObjectHasKey } from './generic'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n SOCKET_NAME,\n QUERY_ARG_NAME,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlResolverNotFoundError } from 'jsonql-errors'\n/**\n * Check if the json is a contract file or not\n * @param {object} contract json object\n * @return {boolean} true\n */\nexport function checkIsContract(contract) {\n return isPlainObject(contract)\n && (\n isObjectHasKey(contract, QUERY_NAME)\n || isObjectHasKey(contract, MUTATION_NAME)\n || isObjectHasKey(contract, SOCKET_NAME)\n )\n}\n\n/**\n * Wrapper method that check if it's contract then return the contract or false\n * @param {object} contract the object to check\n * @return {boolean | object} false when it's not\n */\nexport function isContract(contract) {\n return checkIsContract(contract) ? contract : false;\n}\n\n/**\n * Ported from jsonql-params-validator but different\n * if we don't find the socket part then return false\n * @param {object} contract the contract object\n * @return {object|boolean} false on failed\n */\nexport function extractSocketPart(contract) {\n if (isObjectHasKey(contract, 'socket')) {\n return contract.socket;\n }\n return false;\n}\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @param {boolean} [fallback=false] this is a fall back option for old code\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport function groupByNamespace(contract, fallback = false) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n if (fallback) {\n return contract; // just return the whole contract\n }\n throw new JsonqlError(`socket not found in contract!`)\n }\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\n}\n\n/**\n * @NOTE ported from jsonql-ws-client\n * Got to make sure the connection order otherwise\n * it will hang\n * @param {object} nspSet contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspSet, publicNamespace) {\n let names = []; // need to make sure the order!\n for (let namespace in nspSet) {\n if (namespace === publicNamespace) {\n names[1] = namespace;\n } else {\n names[0] = namespace;\n }\n }\n return names;\n}\n\n\n/**\n * Extract the args from the payload\n * @param {object} payload to work with\n * @param {string} type of call\n * @return {array} args\n */\nexport function extractArgsFromPayload(payload, type) {\n switch (type) {\n case QUERY_NAME:\n return payload[QUERY_ARG_NAME];\n case MUTATION_NAME:\n return [\n payload[PAYLOAD_PARAM_NAME],\n payload[CONDITION_PARAM_NAME]\n ];\n default:\n throw new JsonqlError(`Unknown ${type} to extract argument from!`)\n }\n}\n\n/**\n * Like what the name said\n * @param {object} contract the contract json\n * @param {string} type query|mutation\n * @param {string} name of the function\n * @return {object} the params part of the contract\n */\nexport function extractParamsFromContract(contract, type, name) {\n try {\n const result = contract[type][name];\n // debug('extractParamsFromContract', result)\n if (!result) {\n // debug(name, type, contract)\n throw new JsonqlResolverNotFoundError(name, type)\n }\n return result;\n } catch(e) {\n throw new JsonqlResolverNotFoundError(name, e)\n }\n}\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport default function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n","// take only the module part which is what we use here\n// and export it again to use through out the client\n// this way we avoid those that we don't want node.js module got build into the code\nimport { isContract } from 'jsonql-utils/src/contract'\nimport hashCodeFn from 'nb-event-service/src/hash-code'\n/**\n * @param {object} jsonqlInstance the init instance of jsonql client\n * @param {object} contract the static contract\n * @return {object} contract may be from server\n */\nconst getContractFromConfig = function(jsonqlInstance, contract = {}) {\n if (isContract(contract)) {\n return Promise.resolve(contract)\n }\n return jsonqlInstance.getContract()\n}\n// wrapper method to make sure it's a string\nconst hashCode = str => hashCodeFn(str) + ''\n\n// simple util to check if an object has any properties\n// const hasProp = obj => isObject(obj) && Object.keys(obj).length\n\n// export some constants as well\n// since it's only use here there is no point of adding it to the constants module\n// or may be we add it back later\nconst ENDPOINT_TABLE = 'endpoint' // not in use anymore delete later @TODO\nconst USERDATA_TABLE = 'userdata'\nconst CLS_LOCAL_STORE_NAME = 'localStore'\nconst CLS_SESS_STORE_NAME = 'sessionStore'\nconst CLS_CONTRACT_NAME = 'contract'\nconst CLS_PROFILE_IDX = 'prof_idx'\nconst ZERO_IDX = 0\n// export\nexport {\n hashCode,\n getContractFromConfig,\n ENDPOINT_TABLE,\n USERDATA_TABLE,\n CLS_LOCAL_STORE_NAME,\n CLS_SESS_STORE_NAME,\n CLS_CONTRACT_NAME,\n CLS_PROFILE_IDX,\n ZERO_IDX\n}\n","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\nfunction polyfill (input) {\n var str = String(input).replace(/=+$/, '');\n if (str.length % 4 == 1) {\n throw new InvalidCharacterError(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = '';\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n return output;\n}\n\n\nmodule.exports = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill;\n","// when the user is login with the jwt\n// we use call this to decode the token and then add the payload\n// to the resolver so the user can call ResolverName.userdata\n// and get back the payload\nimport jwt_decode from 'jwt-decode'\nimport isString from 'jsonql-params-validator/src/string'\nimport JsonqlError from 'jsonql-errors/src/error'\n\nconst timestamp = function (sec = false) {\n var time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n\n/**\n * We only check the nbf and exp\n * @param {object} token for checking\n * @return {object} token on success\n */\nfunction validate(token) {\n const start = token.iat || timestamp(true)\n // we only check the exp for the time being\n if (token.exp) {\n if (start >= token.exp) {\n const expired = new Date(token.exp).toISOString()\n throw new JsonqlError(`Token has expired on ${expired}`, token)\n }\n }\n return token;\n}\n\n/**\n * The browser client version it has far fewer options and it doesn't verify it\n * because it couldn't this is the job for the server\n * @TODO we need to add some extra proessing here to check for the exp field\n * @param {string} token to decrypted\n * @return {object} decrypted object\n */\nexport default function jwtDecode(token) {\n if (isString(token)) {\n const t = jwt_decode(token)\n return validate(t)\n }\n throw new JsonqlError('Token must be a string!')\n}\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n","module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n","// sort of persist on the user side\nimport engine from 'store/src/store-engine'\n\nimport localStorage from 'store/storages/localStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// @1.5.0 stop using the expired plugin, and deal with it ourself\n// import expiredPlugin from 'store/plugins/expire'\nimport eventsPlugin from 'store/plugins/events'\nimport compressionPlugin from 'store/plugins/compression'\n\nconst storages = [localStorage, cookieStorage]\nconst plugins = [defaultPlugin, eventsPlugin, compressionPlugin]\n\nconst localStore = engine.createStore(storages, plugins)\n\nexport default localStore\n","// session store with watch\nimport engine from 'store/src/store-engine'\n\nimport sessionStorage from 'store/storages/sessionStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// start using compression in 1.5.0 \nimport compressionPlugin from 'store/plugins/compression'\n// @1.5.0 stop using the expired plugin and deal it ourself\n// import expiredPlugin from 'store/plugins/expire'\n\nconst storages = [sessionStorage, cookieStorage]\nconst plugins = [defaultPlugin, compressionPlugin]\n\nconst sessionStore = engine.createStore(storages, plugins)\n\nexport default sessionStore\n","// export store interface\n// @TODO need to figure out how to make this as a outside dependencies instead of built into it\nimport localStoreEngine from './local-store'\nimport sessionStoreEngine from './session-store'\n\n// export back the raw version for development purposes\nexport const localStore = localStoreEngine\nexport const sessionStore = sessionStoreEngine\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport isString from 'lodash-es/isString'\n\nimport { timestamp } from './timestamp'\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? JSON.parse(payload) : payload;\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName\n * @param {*} payload\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload) {\n return {\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload;\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload;\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getNameFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// break up from node-middleware\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n API_REQUEST_METHODS,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME ,\n QUERY_ARG_NAME,\n DATA_KEY,\n ERROR_KEY,\n INDEX_KEY,\n EXT,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport { isObjectHasKey } from './generic'\nimport { timestamp } from './timestamp'\nimport isArray from 'lodash-es/isArray'\nimport merge from 'lodash-es/merge'\n/**\n * getting what is calling after the above check\n * @param {string} method of call\n * @return {mixed} false on failed\n */\nexport const getCallMethod = method => {\n const [ POST, PUT ] = API_REQUEST_METHODS;\n switch (true) {\n case method === POST:\n return QUERY_NAME;\n case method === PUT:\n return MUTATION_NAME;\n default:\n return false;\n }\n}\n\n/**\n * wrapper method\n * @param {mixed} result of fn return\n * @param {boolean|array} [ts=false] when pass this then we append a new value to the end\n * @return {string} stringify data\n */\nexport const packResult = function(result, ts = false) {\n let payload = { [DATA_KEY]: result }\n if (ts && isArray(ts)) {\n ts.push(timestamp())\n payload[TIMESTAMP_PARAM_NAME] = ts\n }\n return JSON.stringify(payload)\n}\n\n/**\n * Check if the error object contain out custom key\n * @param {*} e object\n * @return {boolean} true\n */\nexport const isJsonqlErrorObj = e => {\n const searchFields = ['detail', 'className']\n const test = !!searchFields.filter(field => isObjectHasKey(e, field)).length\n if (test) {\n return ['className', 'message', 'statusCode']\n .filter(field => isObjectHasKey(e, field))\n .map(field => (\n {\n [field]: typeof e[field] === 'object' ? e[field].toString() : e[field]\n }\n ))\n .reduce(merge, {detail: e.toString()}) // can only get as much as possible\n }\n return false;\n}\n\n/**\n * wrapper method - the output is trying to match up the structure of the Error sub class\n * @param {mixed} detail of fn error\n * @param {string} [className=JsonqlError] the errorName\n * @param {number} [statusCode=500] the original error code\n * @return {string} stringify error\n */\nexport const packError = function(detail, className = 'JsonqlError', statusCode = 0, message = '') {\n let errorObj = { detail, className, statusCode, message }\n // we need to check the detail object to see if it has detail, className and message\n // if it has then we should merge the object instead\n return JSON.stringify({\n [ERROR_KEY]: isJsonqlErrorObj(detail) || errorObj,\n [TIMESTAMP_PARAM_NAME]: timestamp()\n })\n}\n\n// ported from http-client\n\n/**\n * handle the return data\n * @TODO how to handle the return timestamp and calculate the diff?\n * @param {object} result return from server\n * @return {object} strip the data part out, or if the error is presented\n */\nexport const resultHandler = result => (\n (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result\n)\n","// new 1.5.0\n// create a class method to handle all the saving and retriving data\n// using the instanceKey to id the data hence allow to use multiple instance\nimport merge from 'lodash-es/merge'\nimport { localStore, sessionStore } from '../stores'\nimport { CLS_SESS_STORE_NAME, CLS_LOCAL_STORE_NAME, hashCode } from '../utils'\n\n// this becomes the base class instead of the HttpCls\nexport default class StoreClass {\n\n constructor(opts) {\n this.opts = opts\n // make it a string\n this.instanceKey = hashCode(this.opts.hostname)\n // pass this store for use later\n this.localStore = localStore\n this.sessionStore = sessionStore\n /*\n if (this.opts.debugOn) { // reuse this to clear out the data\n this.log('clear all stores')\n localStore.clearAll()\n sessionStore.clearAll()\n\n localStore.set('TEST', Date.now())\n sessionStore.set('TEST', Date.now())\n }\n */\n }\n // store in local storage id by the instanceKey\n // values should be an object so with key so we just merge\n // into the existing store without going through the keys\n __setMethod(storeType, values) {\n let store = this[storeType]\n let data = this.__getMethod(storeType)\n const skey = this.opts.storageKey\n const ikey = this.instanceKey\n store.set(skey, {\n [ikey]: data ? merge({}, data, values) : values\n })\n }\n // return the data id by the instaceKey\n __getMethod(storeType) {\n let store = this[storeType]\n let data = store.get(this.opts.storageKey)\n return data ? data[this.instanceKey] : false\n }\n // remove from local store id by instanceKey\n __delMethod(storeType, key) {\n let data = this.__getMethod(storeType)\n if (data) {\n let store = {}\n for (let k in data) {\n if (k !== key) {\n store[k] = data[k]\n }\n }\n this.__setMethod(storeType, store)\n }\n }\n // clear everything by this instanceKey\n __clearMethod(storeKey) {\n const skey = this.opts.storageKey\n const store = this[storeKey]\n let data = store.get(skey)\n if (data) {\n let _store = {}\n for (let k in data) {\n if (k !== this.instanceKey) {\n _store[k] = data[k]\n }\n }\n store.set(skey, _store)\n }\n }\n // Alias for different store\n set lset(values) {\n return this.__setMethod(CLS_LOCAL_STORE_NAME, values)\n }\n\n get lget() {\n return this.__getMethod(CLS_LOCAL_STORE_NAME)\n }\n\n ldel(key) {\n return this.__delMethod(CLS_LOCAL_STORE_NAME, key)\n }\n\n lclear() {\n return this.__clearMethod(CLS_LOCAL_STORE_NAME)\n }\n\n // store in session store id by the instanceKey\n set sset(values) {\n // this.log('--- sset ---', values)\n return this.__setMethod(CLS_SESS_STORE_NAME, values)\n }\n\n get sget() {\n return this.__getMethod(CLS_SESS_STORE_NAME)\n }\n\n sdel(key) {\n return this.__delMethod(CLS_SESS_STORE_NAME, key)\n }\n\n sclear() {\n return this.__clearMethod(CLS_SESS_STORE_NAME)\n }\n\n\n}\n","// base HttpClass\nimport merge from 'lodash-es/merge'\nimport {\n createQuery,\n createMutation,\n getNameFromPayload\n} from 'jsonql-utils/src/params-api'\nimport { cacheBurst, urlParams } from 'jsonql-utils/src/urls'\nimport { resultHandler } from 'jsonql-utils/src/results'\nimport { isObject, isString } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlServerError,\n JsonqlError,\n // clientErrorsHandler\n} from 'jsonql-errors'\nimport {\n API_REQUEST_METHODS,\n DEFAULT_HEADER,\n JSONP_CALLBACK_NAME,\n SHOW_CONTRACT_DESC_PARAM\n} from 'jsonql-constants'\n\n// @DEBUG\nimport * as errors from 'jsonql-errors'\nimport { isObjectHasKey } from 'jsonql-utils/src/generic'\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nfunction clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n console.info('--- errorName ---', errorName, errors)\n\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n\n\n\n// extract the one we need\nconst [ POST, PUT ] = API_REQUEST_METHODS\n\nimport StoreClass from './store-cls'\n\nexport default class HttpClass extends StoreClass {\n /**\n * The opts has been check at the init stage\n * @param {object} opts configuration options\n */\n constructor(opts) {\n super(opts)\n // change the way how we init Fly\n // flyio now become external depedencies and it makes it easier to switch\n // @BUG should we run test to check if we have the windows object?\n // this.log(opts)\n // this.fly = opts.Fly ? new opts.Fly() : new Fly()\n // to a different environment like WeChat mini app\n\n this.extraHeader = {};\n // @1.2.1 for adding query to the call on the fly\n this.extraParams = {};\n // this.log('start up opts', opts);\n this.reqInterceptor()\n this.resInterceptor()\n }\n\n // set headers for that one call\n set headers(header) {\n this.extraHeader = header;\n }\n\n /**\n * Create the reusage request method\n * @param {object} payload jsonql payload\n * @param {object} options extra options add the request\n * @param {object} headers extra headers add to the call\n * @return {object} the fly request instance\n */\n request(payload, options = {}, headers = {}) {\n this.headers = headers;\n let params = merge({}, cacheBurst(), this.extraParams)\n // @TODO need to add a jsonp url and payload\n if (this.opts.enableJsonp) {\n let resolverName = getNameFromPayload(payload)\n params = merge({}, params, {[JSONP_CALLBACK_NAME]: resolverName})\n payload = payload[resolverName]\n }\n // double up the url param and see what happen @TODO remove later\n const reqParams = merge({}, { method: POST, params }, options)\n this.log('request params', reqParams, this.jsonqlEndpoint)\n\n return this.fly.request(this.jsonqlEndpoint, payload, reqParams)\n }\n\n /**\n * This will replace the create baseRequest method\n *\n */\n reqInterceptor() {\n this.fly.interceptors.request.use(\n req => {\n const headers = this.getHeaders()\n this.log('request interceptor call', headers)\n\n for (let key in headers) {\n req.headers[key] = headers[key]\n }\n return req;\n }\n )\n }\n\n // @TODO\n processJsonp(result) {\n return resultHandler(result)\n }\n\n /**\n * This will be replacement of the first then call\n *\n */\n resInterceptor() {\n const self = this;\n const jsonp = self.opts.enableJsonp;\n this.fly.interceptors.response.use(\n res => {\n this.log('response interceptor call', res)\n self.cleanUp()\n // now more processing here\n // there is a problem if we throw the result.error here\n // the original data is lost, so we need to do what we did before\n // deal with that error in the first then instead\n const result = isString(res.data) ? JSON.parse(res.data) : res.data;\n if (jsonp) {\n return self.processJsonp(result)\n }\n return resultHandler(result)\n },\n // this get call when it's not 200\n err => {\n self.cleanUp()\n console.error(err)\n throw new JsonqlServerError('Server side error', err)\n }\n )\n }\n\n /**\n * Get the headers inject into the call\n * @return {object} headers\n */\n getHeaders() {\n if (this.opts.enableAuth) {\n return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader)\n }\n return merge({}, DEFAULT_HEADER, this.extraHeader)\n }\n\n /**\n * Post http call operation to clean up things we need\n */\n cleanUp() {\n this.extraHeader = {}\n this.extraParams = {}\n }\n\n /**\n * GET for contract only\n * @return {promise} resolve the contract\n */\n getRemoteContract() {\n if (this.opts.showContractDesc) {\n this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM)\n }\n return this.request({}, {method: 'GET'}, this.contractHeader)\n .then(clientErrorsHandler)\n .then(result => {\n this.log('get contract result', result)\n // when refresh the window the result is different!\n // @TODO need to check the Koa side about why is that\n // also it should set a flag if we want the description or not\n if (result.cache && result.contract) {\n return result.contract;\n }\n // just the normal result\n return result\n })\n .catch(err => {\n console.error('getRemoteContract err', err)\n throw new JsonqlServerError('getRemoteContract', err)\n })\n }\n\n /**\n * POST to server - query\n * @param {object} name of the resolver\n * @param {array} args arguments\n * @return {object} promise resolve to the resolver return\n */\n query(name, args = []) {\n return this.request(createQuery(name, args))\n .then(clientErrorsHandler)\n }\n\n /**\n * PUT to server - mutation\n * @param {string} name of resolver\n * @param {object} payload what it said\n * @param {object} conditions what it said\n * @return {object} promise resolve to the resolver return\n */\n mutation(name, payload = {}, conditions = {}) {\n return this.request(createMutation(name, payload, conditions), {method: PUT})\n .then(clientErrorsHandler)\n }\n\n}\n","// all the contract related methods will be here\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { timestamp } from 'jsonql-utils/src/timestamp'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { ENDPOINT_TABLE, CLS_CONTRACT_NAME } from '../utils'\nimport { localStore } from '../stores'\nimport HttpClass from './http-cls'\n\n// export\nexport default class ContractClass extends HttpClass {\n\n constructor(opts) {\n super(opts)\n }\n\n /**\n * return the contract public api\n * @return {object} contract\n */\n getContract() {\n const contract = this.readContract()\n this.log('getContract first call', contract)\n return contract ? Promise.resolve(contract)\n : this.getRemoteContract().then(this.storeContract.bind(this))\n }\n\n /**\n * We are changing the way how to auth to get the contract.json\n * Instead of in the url, we will be putting that key value in the header\n * @return {object} header\n */\n get contractHeader() {\n let base = {};\n if (this.opts.contractKey !== false) {\n base[this.opts.contractKeyName] = this.opts.contractKey;\n }\n return base;\n }\n\n /**\n * Save the contract to local store\n * @param {object} contract to save\n * @return {object|boolean} false when its not a contract or contract on OK\n */\n storeContract(contract) {\n // first need to check if the contract is a contract\n if (!isContract(contract)) {\n throw new JsonqlValidationError(`Contract is malformed!`)\n //return false;\n }\n /* @TODO need to rethink how to expired the contract\n let args = [contract]\n if (this.opts.contractExpired) {\n let expired = parseFloat(this.opts.contractExpired)\n if (!isNaN(expired) && expired > 0) {\n args.push(expired)\n }\n }\n // calling the setter\n this.jsonqlContract = args;\n */\n this.lset = {[CLS_CONTRACT_NAME]: contract}\n // return it\n this.log('storeContract return result', contract)\n return contract;\n }\n\n /**\n * return the contract from options or localStore\n * @return {object|boolean} false on not found\n */\n readContract() {\n let contract = isContract(this.opts.contract)\n if (contract !== false) {\n return contract;\n }\n let data = this.lget\n if (data) {\n return data[CLS_CONTRACT_NAME]\n }\n return false;\n }\n}\n","// this is the new auth class that integrate with the jsonql-jwt\n// all the auth related methods will be here\nimport { decodeToken } from 'jsonql-jwt/src/client'\nimport { isNumber } from 'jsonql-params-validator'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { CREDENTIAL_STORAGE_KEY, AUTH_HEADER, BEARER } from 'jsonql-constants'\nimport { CLS_PROFILE_IDX, ZERO_IDX, USERDATA_TABLE } from '../utils'\nimport ContractClass from './contract-cls'\n// export\nexport default class AuthClass extends ContractClass {\n\n constructor(opts) {\n super(opts)\n if (opts.enableAuth) {\n this.setDecoder = decodeToken;\n }\n }\n\n /**\n * for overwrite\n * @param {string} token stored token\n * @return {string} token\n */\n decoder(token) {\n return token;\n }\n\n /**\n * set the profile index\n * @param {number} idx\n */\n set profileIndex(idx) {\n const key = CLS_PROFILE_IDX\n if (isNumber(idx)) {\n this[key] = idx;\n if (this.opts.persistToken) {\n this.lset = {[key]: idx}\n }\n return;\n }\n throw new JsonqlValidationError('profileIndex', `Expect idx to be number but got ${typeof idx}`)\n }\n\n /**\n * get the profile index\n * @return {number} idx\n */\n get profileIndex() {\n const key = CLS_PROFILE_IDX\n if (this.opts.persistToken) {\n const data = this.lget;\n if (data[key]) {\n return data[key]\n }\n }\n return this[key] ? this[key] : ZERO_IDX\n }\n\n /**\n * Return the token from session store\n * @param {number} [idx=false] profile index\n * @return {string} token\n */\n rawAuthToken(idx = false) {\n if (idx !== false) {\n this.profileIndex = idx;\n }\n // this should return from the base\n return this.jsonqlToken; // see base-cls\n }\n\n /**\n * Setter to add a decoder when retrieve user token\n * @param {function} d a decoder\n */\n set setDecoder(d) {\n if (typeof d === 'function') {\n this.decoder = d;\n }\n }\n\n /**\n * getter to return the session or local store set method\n * @param {*} data to save\n * @return {object} set method\n */\n set saveProfile(data) {\n if (this.opts.persistToken) {\n // this.log('--- saveProfile lset ---', data)\n this.lset = data\n } else {\n // this.log('--- saveProfile sset ---', data)\n this.sset = data\n }\n }\n\n /**\n * getter to return the session or local store get method\n * @return {object} get method\n */\n get readProfile() {\n return this.opts.persistToken ? this.lget : this.sget\n }\n\n // these were in the base class before but it should be here\n /**\n * save token\n * @param {string} token to store\n * @return {string|boolean} false on failed\n */\n set jsonqlToken(token) {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n // @TODO also have to make sure the token is not already existed!\n let tokens = (data && data[key]) ? data[key] : []\n tokens.push(token)\n this.saveProfile = {[key]: tokens}\n // store the userdata\n this.jsonqlUserdata = this.decoder(token)\n }\n\n /**\n * Jsonql token getter\n * 1.5.1 each token associate with the same profileIndex\n * @return {string|boolean} false when failed\n */\n get jsonqlToken() {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex])\n return data[key][this.profileIndex]\n }\n return false\n }\n\n /**\n * this one will use the sessionStore\n * basically we hook this onto the token store and decode it to store here\n * we only store one decoded user data at a time, but the token can be multiple\n */\n set jsonqlUserdata(userdata) {\n this.sset = {[USERDATA_TABLE]: userdata}\n }\n\n /**\n * this one store in the session store\n * get login userdata decoded jwt\n * 1.5.1 each userdata associate with the same profileIndex\n * @return {object|null}\n */\n get jsonqlUserdata() {\n const data = this.sget\n return data ? data[USERDATA_TABLE] : false\n }\n\n /**\n * Construct the auth header\n * @return {object} header\n */\n getAuthHeader() {\n const token = this.jsonqlToken // only call the getter to get the default one\n return token ? {[this.opts.AUTH_HEADER]: `${BEARER} ${token}`} : {};\n }\n\n /**\n * return all the stored token and decode it\n * @param {number} [idx=false] profile index\n * @return {array|boolean|string} false not found or array\n */\n getProfiles(idx = false) {\n const self = this; // just in case the scope problem\n const data = self.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n if (idx !== false && isNumber(idx)) {\n return data[key][idx] || false\n }\n return data[key].map(self.decoder.bind(self))\n }\n return false\n }\n\n /**\n * call after the login\n * @param {string} token return from server\n * @return {object} decoded token to userdata object\n */\n postLoginAction(token) {\n this.jsonqlToken = token\n return token\n }\n\n /**\n * call after the logout @TODO\n */\n postLogoutAction(...args) {\n console.info(`postLogoutAction`, args)\n }\n}\n","// this the core of the internal storage management\nimport { CREDENTIAL_STORAGE_KEY } from 'jsonql-constants'\n// import { isObject, isArray } from 'jsonql-params-validator'\n// import { JsonqlValidationError } from 'jsonql-errors'\n// import { timestamp } from 'jsonql-utils/src/timestamp'\n// import { inArray } from 'jsonql-utils/src/generic'\nimport { USERDATA_TABLE } from '../utils'\nimport AuthCls from './auth-cls'\n\n// This class will only focus on the storage system\nexport default class JsonqlBaseClient extends AuthCls {\n // change the order of the interface in 1.4.10 to match up the top level\n constructor(fly, opts) {\n // change at 1.4.10 pass it directly without init it\n this.fly = fly;\n super(opts)\n }\n\n /**\n * construct the end point\n * @return {string} the end point to call\n */\n get jsonqlEndpoint() {\n const baseUrl = this.opts.hostname || ''\n return [baseUrl, this.opts.jsonqlPath].join('/')\n }\n\n /**\n * simple log\n */\n log(...args) {\n if (this.opts.debugOn === true) {\n Reflect.apply(console.info, console, args)\n }\n }\n\n}\n","// export interface\n// @public\nimport JsonqlBaseClient from './base-cls'\n\nexport default JsonqlBaseClient\n","// all the client configuration options here\nimport {\n JSONQL_PATH,\n CONTENT_TYPE,\n BEARER,\n CLIENT_STORAGE_KEY,\n CLIENT_AUTH_KEY,\n CONTRACT_KEY_NAME,\n AUTH_HEADER,\n ISSUER_NAME,\n LOGOUT_NAME,\n BOOLEAN_TYPE,\n STRING_TYPE,\n NUMBER_TYPE,\n DEFAULT_HEADER\n} from 'jsonql-constants'\nimport { createConfig } from 'jsonql-params-validator'\nexport const constProps = {\n contract: false,\n MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong?\n CONTENT_TYPE,\n BEARER,\n AUTH_HEADER\n}\n\n// grab the localhost name and put into the hostname as default\nconst getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n return null\n }\n}\n\nexport const appProps = {\n\n hostname: createConfig(getHostName(), [STRING_TYPE]), // required the hostname\n jsonqlPath: createConfig(JSONQL_PATH, [STRING_TYPE]), // The path on the server\n\n loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]),\n logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]),\n // add to koa v1.3.0 - this might remove in the future\n enableJsonp: createConfig(false, [BOOLEAN_TYPE]),\n enableAuth: createConfig(false, [BOOLEAN_TYPE]),\n // enable useJwt by default @TODO replace with something else and remove them later\n useJwt: createConfig(true, [BOOLEAN_TYPE]),\n // when true then store infinity or pass a time in seconds then we check against\n // the token date of creation\n persistToken: createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE]),\n // the header\n // v1.2.0 we are using this option during the dev\n // so it won't save anything to the localstorage and fetch a new contract\n // whenever the browser reload\n useLocalstorage: createConfig(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage\n storageKey: createConfig(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage\n authKey: createConfig(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage\n contractExpired: createConfig(0, [NUMBER_TYPE]),// -1 always fetch contract,\n // 0 never expired,\n // > 0 then compare the timestamp with the current one to see if we need to get contract again\n // useful during development\n keepContract: createConfig(true, [BOOLEAN_TYPE]),\n exposeContract: createConfig(false, [BOOLEAN_TYPE]),\n exposeStore: createConfig(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn \n // @1.2.1 new option for the contract-console to fetch the contract with description\n showContractDesc: createConfig(false, [BOOLEAN_TYPE]),\n contractKey: createConfig(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this\n contractKeyName: createConfig(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs\n enableTimeout: createConfig(false, [BOOLEAN_TYPE]), // @TODO\n timeout: createConfig(5000, [NUMBER_TYPE]), // 5 seconds\n returnInstance: createConfig(false, [BOOLEAN_TYPE]),\n allowReturnRawToken: createConfig(false, [BOOLEAN_TYPE]),\n debugOn: createConfig(false, [BOOLEAN_TYPE])\n}\n","// This is for the sync version therefore we don't need to care about the contract options\nimport { appProps, constProps } from './base-options'\nimport { checkConfig } from 'jsonql-params-validator'\n\nexport default function checkOptions(config) {\n return checkConfig(config, appProps, constProps)\n}\n","// export interface\nimport checkOptionsAsyncLocal from './check-options-async'\nimport checkOptionsLocal from './check-options'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport { objHasProp } from 'jsonql-utils/src/obj-define-props'\n/**\n * 1.5.0 overload the orginal functions to pass over the check\n */\nfunction checkOptionsAsync(config) {\n return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsyncLocal(config)\n}\n\n// sync version without needing the promise\nfunction checkOptions(config) {\n return objHasProp(config, CHECKED_KEY) ? config : checkOptionsLocal(config)\n}\n\nexport {\n checkOptionsAsync,\n checkOptions\n}\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n\nexport default class SuspendClass {\n\n constructor() {\n // suspend, release and queue\n this.__suspend__ = null;\n this.queueStore = new Set()\n /*\n this.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n })\n */\n }\n\n /**\n * setter to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n set $suspend(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend__;\n this.__suspend__ = value;\n this.logger('($suspend)', `Change from ${lastValue} --> ${value}`)\n if (lastValue === true && value === false) {\n setTimeout(() => {\n this.release()\n }, 1)\n }\n } else {\n throw new Error(`$suspend only accept Boolean value!`)\n }\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {any} value\n * @return {Boolean} true when added or false when it's not\n */\n $queue(...args) {\n if (this.__suspend__ === true) {\n this.logger('($queue)', 'added to $queue', args)\n // there shouldn't be any duplicate ...\n this.queueStore.add(args)\n }\n return this.__suspend__;\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size;\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n release() {\n let size = this.queueStore.size\n this.logger('(release)', `Release was called ${size}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('queue', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport genHaskKey from './hash-code'\nimport SuspendClass from './suspend'\n\nexport default class NbEventServiceBase extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger;\n }\n this.keep = config.keep;\n // for the $done setter\n this.result = config.keep ? [] : null;\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (typeof e !== 'string') {\n this.logger('(validateEvt)', e)\n throw new Error(`event name must be string type!`)\n }\n })\n return true;\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n return true;\n }\n }\n throw new Error(`callback required to be function type!`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n const types = ['on', 'only', 'once', 'onlyOnce']\n return !!types.filter(t => type === t).length;\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run)', callback, payload, ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName]; // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger('(takeFromStore)', `has ${evt}`, content)\n store.delete(evt)\n return content;\n }\n return false;\n }\n throw new Error(`${storeName} is not supported!`)\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n let fnSet;\n if (store.has(evt)) {\n this.logger('(addToStore)', `${evt} existed`)\n fnSet = store.get(evt)\n } else {\n this.logger('(addToStore)', `create new Set for ${evt}`)\n // this is new\n fnSet = new Set()\n }\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args;\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger('(addToStore)', `insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(l => {\n let [hash,] = l;\n if (hash === args[0]) {\n return true;\n }\n return false;\n }).length;\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true;\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list;\n return type !== t;\n }).length;\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n this.logger('(checkTypeInLazyStore)', store)\n if (store) {\n return !!Array\n .from(store)\n .filter(l => {\n let [,,t] = l;\n return t !== type;\n }).length\n }\n return false;\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger('(addToNormalStore)', evt, type, 'try to add to normal store')\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n this.logger('(addToNormalStore)', `${type} can add to ${evt} normal store`)\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store;\n return size;\n }\n return false;\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store;\n return size;\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg];\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n return genHaskKey(fn.toString()) + '';\n }\n}\n","// The top level\nimport NbStoreService from './store-service'\n// export\nexport default class EventService extends NbStoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on';\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger('($on)', `${evt} callback is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger('($on)', `${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0;\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($on)`, `call run on ${evt}`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n return size;\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n const type = 'once';\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (lazyStoreContent === false) {\n this.logger('($once)', `${evt} not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, type, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger('($once)', `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'only';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($only)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($only)', `${evt} found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( l => {\n const [ payload, ctx, t ] = l;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($only)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n })\n }\n return added;\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD added in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'onlyOnce';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== 'onlyOnce') {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($onlyOnce)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added;\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {}\n */\n $replace(evt, callback, context = null, type = 'on') {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n this.logger(`($replace)`, evt, callback)\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0;\n // first check the normal store\n let nStore = this.normalStore;\n this.logger('($trigger)', 'normalStore', nStore)\n if (nStore.has(evt)) {\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n this.logger('($trigger)', evt, 'found; add to queue: ', added)\n if (added === true) {\n this.logger('($trigger)', evt, 'not executed. Exit now.')\n return false; // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length;\n let hasOnce = false;\n let hasOnly = false;\n for (let i=0; i < ctn; ++i) {\n ++found;\n // this.logger('found', found)\n let [ _, callback, ctx, type ] = nSet[i]\n this.logger(`($trigger)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n if (type === 'once' || type === 'onlyOnce') {\n hasOnce = true;\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found;\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found;\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter around\n * @param {string} evt event name\n * @param {*} params pass to the callback\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, params, type = false, context = null) {\n let args = [evt, params, context, type]\n return Reflect.apply(this.$trigger, this, args)\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n let found = false;\n stores.forEach(store => {\n if (store.has(evt)) {\n found = true;\n this.logger('($off)', evt)\n store.delete(evt)\n }\n })\n return found;\n }\n\n /**\n * return all the listener from the event\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n this.validateEvt(evt)\n let store = this.normalStore;\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l;\n }\n let [key, callback, ] = l;\n return callback;\n })\n }\n return false;\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done)', 'value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value;\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n if (this.keep) {\n this.logger('(get $done)', this.result)\n return this.result[this.result.length - 1]\n }\n return this.result;\n }\n\n\n}\n","// default\nimport NBEventService from './src/event-service'\n\nexport default NBEventService\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// output\nexport default function(debugOn) {\n let logger = debugOn ? (...args) => {\n args.unshift('[NBS]')\n console.log.apply(null, args)\n }: undefined;\n return new NBEventService({ logger })\n}\n","// this is the new Event base interface\n// the export will be different and purposely design for framework that\n// is very hard to use Promise such as Vue\nimport jsonqlStaticGenerator from './core/jsonql-static-generator'\nimport JsonqlBaseClient from './base'\nimport { checkOptions } from './options'\nimport { getContractFromConfig } from './utils'\nimport getEventEmitter from './ee'\n/**\n * this is the slim client without Fly, you pick the version of Fly to use\n * This is a breaking change because it swap the input positions\n * @param {object} fly fly.js\n * @param {object} config configuration\n * @return {object} the jsonql client instance\n */\nexport default function jsonqlStaticClient(fly, config = {}) {\n const { contract } = config;\n const opts = checkOptions(config)\n const jsonqlBase = new JsonqlBaseClient(fly, opts)\n const contractPromise = getContractFromConfig(jsonqlBase, contract)\n const ee = getEventEmitter(opts.debugOn)\n // finally\n let methods = jsonqlStaticGenerator(jsonqlBase, opts, contractPromise, ee)\n methods.eventEmitter = ee;\n return methods;\n}\n","// This is the static version that build with the Fly for Browser\nimport Fly from 'flyio/dist/npm/fly'\nimport jsonqlStaticClient from './static'\n\n// this is the slim client without Fly\nexport default function jsonqlStaticClientFull(config = {}) {\n return jsonqlStaticClient(new Fly(), config)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"jsonql-client.static.js","sources":["../node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"+/hDAAA"} \ No newline at end of file diff --git a/packages/http-client/dist/jsonql-client.umd.js b/packages/http-client/dist/jsonql-client.umd.js index fab4cb49..e1414212 100644 --- a/packages/http-client/dist/jsonql-client.umd.js +++ b/packages/http-client/dist/jsonql-client.umd.js @@ -1,9635 +1,2 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = global || self, global.jsonqlClient = factory()); -}(this, (function () { 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var fly = createCommonjsModule(function (module, exports) { - (function webpackUniversalModuleDefinition(root, factory) { - { module.exports = factory(); } - })(commonjsGlobal, function() { - return /******/ (function(modules) { // webpackBootstrap - /******/ // The module cache - /******/ var installedModules = {}; - /******/ - /******/ // The require function - /******/ function __webpack_require__(moduleId) { - /******/ - /******/ // Check if module is in cache - /******/ if(installedModules[moduleId]) { - /******/ return installedModules[moduleId].exports; - /******/ } - /******/ // Create a new module (and put it into the cache) - /******/ var module = installedModules[moduleId] = { - /******/ i: moduleId, - /******/ l: false, - /******/ exports: {} - /******/ }; - /******/ - /******/ // Execute the module function - /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - /******/ - /******/ // Flag the module as loaded - /******/ module.l = true; - /******/ - /******/ // Return the exports of the module - /******/ return module.exports; - /******/ } - /******/ - /******/ - /******/ // expose the modules object (__webpack_modules__) - /******/ __webpack_require__.m = modules; - /******/ - /******/ // expose the module cache - /******/ __webpack_require__.c = installedModules; - /******/ - /******/ // identity function for calling harmony imports with the correct context - /******/ __webpack_require__.i = function(value) { return value; }; - /******/ - /******/ // define getter function for harmony exports - /******/ __webpack_require__.d = function(exports, name, getter) { - /******/ if(!__webpack_require__.o(exports, name)) { - /******/ Object.defineProperty(exports, name, { - /******/ configurable: false, - /******/ enumerable: true, - /******/ get: getter - /******/ }); - /******/ } - /******/ }; - /******/ - /******/ // getDefaultExport function for compatibility with non-harmony modules - /******/ __webpack_require__.n = function(module) { - /******/ var getter = module && module.__esModule ? - /******/ function getDefault() { return module['default']; } : - /******/ function getModuleExports() { return module; }; - /******/ __webpack_require__.d(getter, 'a', getter); - /******/ return getter; - /******/ }; - /******/ - /******/ // Object.prototype.hasOwnProperty.call - /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; - /******/ - /******/ // __webpack_public_path__ - /******/ __webpack_require__.p = ""; - /******/ - /******/ // Load entry module and return exports - /******/ return __webpack_require__(__webpack_require__.s = 2); - /******/ }) - /************************************************************************/ - /******/ ([ - /* 0 */ - /***/ (function(module, exports, __webpack_require__) { - - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - module.exports = { - type: function type(ob) { - return Object.prototype.toString.call(ob).slice(8, -1).toLowerCase(); - }, - isObject: function isObject(ob, real) { - if (real) { - return this.type(ob) === "object"; - } else { - return ob && (typeof ob === 'undefined' ? 'undefined' : _typeof(ob)) === 'object'; - } - }, - isFormData: function isFormData(val) { - return typeof FormData !== 'undefined' && val instanceof FormData; - }, - trim: function trim(str) { - return str.replace(/(^\s*)|(\s*$)/g, ''); - }, - encode: function encode(val) { - return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); - }, - formatParams: function formatParams(data) { - var str = ""; - var first = true; - var that = this; - if (!this.isObject(data)) { - return data; - } - - function _encode(sub, path) { - var encode = that.encode; - var type = that.type(sub); - if (type == "array") { - sub.forEach(function (e, i) { - if (!that.isObject(e)) { i = ""; } - _encode(e, path + ('%5B' + i + '%5D')); - }); - } else if (type == "object") { - for (var key in sub) { - if (path) { - _encode(sub[key], path + "%5B" + encode(key) + "%5D"); - } else { - _encode(sub[key], encode(key)); - } - } - } else { - if (!first) { - str += "&"; - } - first = false; - str += path + "=" + encode(sub); - } - } - - _encode(data, ""); - return str; - }, - - // Do not overwrite existing attributes - merge: function merge(a, b) { - for (var key in b) { - if (!a.hasOwnProperty(key)) { - a[key] = b[key]; - } else if (this.isObject(b[key], 1) && this.isObject(a[key], 1)) { - this.merge(a[key], b[key]); - } - } - return a; - } - }; - - /***/ }), - /* 1 */, - /* 2 */ - /***/ (function(module, exports, __webpack_require__) { - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - var utils = __webpack_require__(0); - var isBrowser = typeof document !== "undefined"; - - var Fly = function () { - function Fly(engine) { - _classCallCheck(this, Fly); - - this.engine = engine || XMLHttpRequest; - - this.default = this; //For typeScript - - /** - * Add lock/unlock API for interceptor. - * - * Once an request/response interceptor is locked, the incoming request/response - * will be added to a queue before they enter the interceptor, they will not be - * continued until the interceptor is unlocked. - * - * @param [interceptor] either is interceptors.request or interceptors.response - */ - function wrap(interceptor) { - var resolve = void 0; - var reject = void 0; - - function _clear() { - interceptor.p = resolve = reject = null; - } - - utils.merge(interceptor, { - lock: function lock() { - if (!resolve) { - interceptor.p = new Promise(function (_resolve, _reject) { - resolve = _resolve; - reject = _reject; - }); - } - }, - unlock: function unlock() { - if (resolve) { - resolve(); - _clear(); - } - }, - clear: function clear() { - if (reject) { - reject("cancel"); - _clear(); - } - } - }); - } - - var interceptors = this.interceptors = { - response: { - use: function use(handler, onerror) { - this.handler = handler; - this.onerror = onerror; - } - }, - request: { - use: function use(handler) { - this.handler = handler; - } - } - }; - - var irq = interceptors.request; - var irp = interceptors.response; - wrap(irp); - wrap(irq); - - this.config = { - method: "GET", - baseURL: "", - headers: {}, - timeout: 0, - params: {}, // Default Url params - parseJson: true, // Convert response data to JSON object automatically. - withCredentials: false - }; - } - - _createClass(Fly, [{ - key: "request", - value: function request(url, data, options) { - var _this = this; - - var engine = new this.engine(); - var contentType = "Content-Type"; - var contentTypeLowerCase = contentType.toLowerCase(); - var interceptors = this.interceptors; - var requestInterceptor = interceptors.request; - var responseInterceptor = interceptors.response; - var requestInterceptorHandler = requestInterceptor.handler; - var promise = new Promise(function (resolve, reject) { - if (utils.isObject(url)) { - options = url; - url = options.url; - } - options = options || {}; - options.headers = options.headers || {}; - - function isPromise(p) { - // some polyfill implementation of Promise may be not standard, - // so, we test by duck-typing - return p && p.then && p.catch; - } - - /** - * If the request/response interceptor has been locked, - * the new request/response will enter a queue. otherwise, it will be performed directly. - * @param [promise] if the promise exist, means the interceptor is locked. - * @param [callback] - */ - function enqueueIfLocked(promise, callback) { - if (promise) { - promise.then(function () { - callback(); - }); - } else { - callback(); - } - } - - // make the http request - function makeRequest(options) { - data = options.body; - // Normalize the request url - url = utils.trim(options.url); - var baseUrl = utils.trim(options.baseURL || ""); - if (!url && isBrowser && !baseUrl) { url = location.href; } - if (url.indexOf("http") !== 0) { - var isAbsolute = url[0] === "/"; - if (!baseUrl && isBrowser) { - var arr = location.pathname.split("/"); - arr.pop(); - baseUrl = location.protocol + "//" + location.host + (isAbsolute ? "" : arr.join("/")); - } - if (baseUrl[baseUrl.length - 1] !== "/") { - baseUrl += "/"; - } - url = baseUrl + (isAbsolute ? url.substr(1) : url); - if (isBrowser) { - - // Normalize the url which contains the ".." or ".", such as - // "http://xx.com/aa/bb/../../xx" to "http://xx.com/xx" . - var t = document.createElement("a"); - t.href = url; - url = t.href; - } - } - - var responseType = utils.trim(options.responseType || ""); - var needQuery = ["GET", "HEAD", "DELETE", "OPTION"].indexOf(options.method) !== -1; - var dataType = utils.type(data); - var params = options.params || {}; - - // merge url params when the method is "GET" (data is object) - if (needQuery && dataType === "object") { - params = utils.merge(data, params); - } - // encode params to String - params = utils.formatParams(params); - - // save url params - var _params = []; - if (params) { - _params.push(params); - } - // Add data to url params when the method is "GET" (data is String) - if (needQuery && data && dataType === "string") { - _params.push(data); - } - - // make the final url - if (_params.length > 0) { - url += (url.indexOf("?") === -1 ? "?" : "&") + _params.join("&"); - } - - engine.open(options.method, url); - - // try catch for ie >=9 - try { - engine.withCredentials = !!options.withCredentials; - engine.timeout = options.timeout || 0; - if (responseType !== "stream") { - engine.responseType = responseType; - } - } catch (e) {} - - var customContentType = options.headers[contentType] || options.headers[contentTypeLowerCase]; - - // default content type - var _contentType = "application/x-www-form-urlencoded"; - // If the request data is json object, transforming it to json string, - // and set request content-type to "json". In browser, the data will - // be sent as RequestBody instead of FormData - if (utils.trim((customContentType || "").toLowerCase()) === _contentType) { - data = utils.formatParams(data); - } else if (!utils.isFormData(data) && ["object", "array"].indexOf(utils.type(data)) !== -1) { - _contentType = 'application/json;charset=utf-8'; - data = JSON.stringify(data); - } - //If user doesn't set content-type, set default. - if (!(customContentType || needQuery)) { - options.headers[contentType] = _contentType; - } - - for (var k in options.headers) { - if (k === contentType && utils.isFormData(data)) { - // Delete the content-type, Let the browser set it - delete options.headers[k]; - } else { - try { - // In browser environment, some header fields are readonly, - // write will cause the exception . - engine.setRequestHeader(k, options.headers[k]); - } catch (e) {} - } - } - - function onresult(handler, data, type) { - enqueueIfLocked(responseInterceptor.p, function () { - if (handler) { - //如果失败,添加请求信息 - if (type) { - data.request = options; - } - var ret = handler.call(responseInterceptor, data, Promise); - data = ret === undefined ? data : ret; - } - if (!isPromise(data)) { - data = Promise[type === 0 ? "resolve" : "reject"](data); - } - data.then(function (d) { - resolve(d); - }).catch(function (e) { - reject(e); - }); - }); - } - - function onerror(e) { - e.engine = engine; - onresult(responseInterceptor.onerror, e, -1); - } - - function Err(msg, status) { - this.message = msg; - this.status = status; - } - - engine.onload = function () { - try { - // The xhr of IE9 has not response field - var response = engine.response || engine.responseText; - if (response && options.parseJson && (engine.getResponseHeader(contentType) || "").indexOf("json") !== -1 - // Some third engine implementation may transform the response text to json object automatically, - // so we should test the type of response before transforming it - && !utils.isObject(response)) { - response = JSON.parse(response); - } - - var headers = engine.responseHeaders; - // In browser - if (!headers) { - headers = {}; - var items = (engine.getAllResponseHeaders() || "").split("\r\n"); - items.pop(); - items.forEach(function (e) { - if (!e) { return; } - var key = e.split(":")[0]; - headers[key] = engine.getResponseHeader(key); - }); - } - var status = engine.status; - var statusText = engine.statusText; - var _data = { data: response, headers: headers, status: status, statusText: statusText }; - // The _response filed of engine is set in adapter which be called in engine-wrapper.js - utils.merge(_data, engine._response); - if (status >= 200 && status < 300 || status === 304) { - _data.engine = engine; - _data.request = options; - onresult(responseInterceptor.handler, _data, 0); - } else { - var e = new Err(statusText, status); - e.response = _data; - onerror(e); - } - } catch (e) { - onerror(new Err(e.msg, engine.status)); - } - }; - - engine.onerror = function (e) { - onerror(new Err(e.msg || "Network Error", 0)); - }; - - engine.ontimeout = function () { - onerror(new Err("timeout [ " + engine.timeout + "ms ]", 1)); - }; - engine._options = options; - setTimeout(function () { - engine.send(needQuery ? null : data); - }, 0); - } - - enqueueIfLocked(requestInterceptor.p, function () { - utils.merge(options, JSON.parse(JSON.stringify(_this.config))); - var headers = options.headers; - headers[contentType] = headers[contentType] || headers[contentTypeLowerCase] || ""; - delete headers[contentTypeLowerCase]; - options.body = data || options.body; - url = utils.trim(url || ""); - options.method = options.method.toUpperCase(); - options.url = url; - var ret = options; - if (requestInterceptorHandler) { - ret = requestInterceptorHandler.call(requestInterceptor, options, Promise) || options; - } - if (!isPromise(ret)) { - ret = Promise.resolve(ret); - } - ret.then(function (d) { - //if options continue - if (d === options) { - makeRequest(d); - } else { - resolve(d); - } - }, function (err) { - reject(err); - }); - }); - }); - promise.engine = engine; - return promise; - } - }, { - key: "all", - value: function all(promises) { - return Promise.all(promises); - } - }, { - key: "spread", - value: function spread(callback) { - return function (arr) { - return callback.apply(null, arr); - }; - } - }]); - - return Fly; - }(); - - //For typeScript - - - Fly.default = Fly; - - ["get", "post", "put", "patch", "head", "delete"].forEach(function (e) { - Fly.prototype[e] = function (url, data, option) { - return this.request(url, data, utils.merge({ method: e }, option)); - }; - }); - ["lock", "unlock", "clear"].forEach(function (e) { - Fly.prototype[e] = function () { - this.interceptors.request[e](); - }; - }); - module.exports = Fly; - - /***/ }) - /******/ ]); - }); - }); - - var Fly = unwrapExports(fly); - - // the core stuff to id if it's calling with jsonql - var DATA_KEY = 'data'; - var ERROR_KEY = 'error'; - - var JSONQL_PATH = 'jsonql'; - // according to the json query spec - var CONTENT_TYPE = 'application/vnd.api+json'; - var CHARSET = 'charset=utf-8'; - var DEFAULT_HEADER = { - 'Accept': CONTENT_TYPE, - 'Content-Type': [ CONTENT_TYPE, CHARSET ].join(';') - }; - - // export const INDEX = 'index'; use INDEX_KEY instead - var DEFAULT_TYPE = 'any'; - - // @TODO remove this is not in use - // export const CLIENT_CONFIG_FILE = '.clients.json'; - // export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js'; - // type of resolvers - var QUERY_NAME = 'query'; - var MUTATION_NAME = 'mutation'; - var SOCKET_NAME = 'socket'; - // for calling the mutation - var PAYLOAD_PARAM_NAME = 'payload'; // @TODO shortern them - var CONDITION_PARAM_NAME = 'condition'; - var QUERY_ARG_NAME = 'args'; - var TIMESTAMP_PARAM_NAME = 'TS'; - // new jsonp - var JSONP_CALLBACK_NAME = 'jsonqlJsonpCallback'; - - // methods allow - var API_REQUEST_METHODS = ['POST', 'PUT']; - // for contract-cli - var KEY_WORD = 'continue'; - - var TYPE_KEY = 'type'; - var OPTIONAL_KEY = 'optional'; - var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word - var ARGS_KEY = 'args'; - var CHECKER_KEY = 'checker'; - var ALIAS_KEY = 'alias'; - var CHECKED_KEY = '__checked__'; - var LOGIN_NAME = 'login'; - var ISSUER_NAME = LOGIN_NAME; // legacy issue need to replace them later - var LOGOUT_NAME = 'logout'; - - var AUTH_HEADER = 'Authorization'; - var BEARER = 'Bearer'; - - // for client use @TODO need to clean this up some of them are not in use - var CREDENTIAL_STORAGE_KEY = 'jsonqlcredential'; - var CLIENT_STORAGE_KEY = 'jsonqlstore'; - var CLIENT_AUTH_KEY = 'jsonqlauthkey'; - // contract key - var CONTRACT_KEY_NAME = 'X-JSONQL-CV-KEY'; - var SHOW_CONTRACT_DESC_PARAM = {desc: 'y'}; - - var OR_SEPERATOR = '|'; - - var STRING_TYPE = 'string'; - var BOOLEAN_TYPE = 'boolean'; - var ARRAY_TYPE = 'array'; - var OBJECT_TYPE = 'object'; - - var NUMBER_TYPE = 'number'; - var ARRAY_TYPE_LFT = 'array.<'; - var ARRAY_TYPE_RGT = '>'; - - var NO_ERROR_MSG$1 = 'No message'; - var NO_STATUS_CODE = -1; - var HSA_ALGO = 'HS256'; - - /** - * 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; - - 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$1 = root.Symbol; - - /** 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$1 ? Symbol$1.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$1 ? Symbol$1.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); - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** Built-in value references. */ - var getPrototype = overArg(Object.getPrototypeOf, Object); - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @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 objectTag = '[object Object]'; - - /** Used for built-in method references. */ - var funcProto = Function.prototype, - objectProto$2 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty$1.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; - } - - /** - * 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; - } - - /** `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$1 ? Symbol$1.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(''); - } - - // bunch of generic helpers - - /** - * DIY in Array - * @param {array} arr to check from - * @param {*} value to check against - * @return {boolean} true on found - */ - var inArray = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; - - // quick and dirty to turn non array to array - var toArray = function (arg) { return isArray(arg) ? arg : [arg]; }; - - /** - * @param {object} obj for search - * @param {string} key target - * @return {boolean} true on success - */ - var isObjectHasKey = function(obj, key) { - try { - var keys = Object.keys(obj); - return inArray(keys, key) - } catch(e) { - // @BUG when the obj is not an OBJECT we got some weird output - return false; - /* - console.info('obj', obj) - console.error(e) - throw new Error(e) - */ - } - }; - - // just a simple util method to return the error based on the status code - /** - * @param {number} statusCode to check - * @param {boolean} contract if this is a contract call or not - * @return {string} the error name - */ - function getErrorByStatus(statusCode, contract) { - if ( contract === void 0 ) contract = false; - - switch (statusCode) { - case 401: - return contract ? 'JsonqlContractAuthError' : 'JsonqlAuthorisationError'; - case 403: - return 'JsonqlForbiddenError'; - case 404: - return 'JsonqlResolverNotFoundError'; - case 406: - return 'Jsonql406Error'; - case 500: - return 'Jsonql500Error'; - default: - return 'JsonqlError'; - } - } - - /** - * This is a custom error to throw when server throw a 406 - * 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 Jsonql406Error = /*@__PURE__*/(function (Error) { - function Jsonql406Error() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - // We can't access the static name from an instance - // but we can do it like this - this.className = Jsonql406Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql406Error); - } - } - - if ( Error ) Jsonql406Error.__proto__ = Error; - Jsonql406Error.prototype = Object.create( Error && Error.prototype ); - Jsonql406Error.prototype.constructor = Jsonql406Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 406; - }; - - staticAccessors.name.get = function () { - return 'Jsonql406Error'; - }; - - Object.defineProperties( Jsonql406Error, staticAccessors ); - - return Jsonql406Error; - }(Error)); - - /** - * This is a custom error to throw when server throw a 500 - * 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 Jsonql500Error = /*@__PURE__*/(function (Error) { - function Jsonql500Error() { - 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 = Jsonql500Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql500Error); - } - } - - if ( Error ) Jsonql500Error.__proto__ = Error; - Jsonql500Error.prototype = Object.create( Error && Error.prototype ); - Jsonql500Error.prototype.constructor = Jsonql500Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'Jsonql500Error'; - }; - - Object.defineProperties( Jsonql500Error, staticAccessors ); - - return Jsonql500Error; - }(Error)); - - /** - * This is a custom error to throw when pass credential but fail - * 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 JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { - function JsonqlAuthorisationError() { - 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 = JsonqlAuthorisationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlAuthorisationError); - } - } - - if ( Error ) JsonqlAuthorisationError.__proto__ = Error; - JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); - JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlAuthorisationError'; - }; - - Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); - - return JsonqlAuthorisationError; - }(Error)); - - /** - * This is a custom error when not supply the credential and try to get contract - * 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 JsonqlContractAuthError = /*@__PURE__*/(function (Error) { - function JsonqlContractAuthError() { - 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 = JsonqlContractAuthError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlContractAuthError); - } - } - - if ( Error ) JsonqlContractAuthError.__proto__ = Error; - JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); - JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlContractAuthError'; - }; - - Object.defineProperties( JsonqlContractAuthError, staticAccessors ); - - return JsonqlContractAuthError; - }(Error)); - - /** - * This is a custom error to throw when the resolver throw error and capture inside the middleware - * 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 JsonqlResolverAppError = /*@__PURE__*/(function (Error) { - function JsonqlResolverAppError() { - 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 = JsonqlResolverAppError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverAppError); - } - } - - if ( Error ) JsonqlResolverAppError.__proto__ = Error; - JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverAppError'; - }; - - Object.defineProperties( JsonqlResolverAppError, staticAccessors ); - - return JsonqlResolverAppError; - }(Error)); - - /** - * This is a custom error to throw when could not find the resolver - * 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 JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { - function JsonqlResolverNotFoundError() { - 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 = JsonqlResolverNotFoundError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverNotFoundError); - } - } - - if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; - JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 404; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverNotFoundError'; - }; - - Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); - - return JsonqlResolverNotFoundError; - }(Error)); - - // this get throw from within the checkOptions when run through the enum failed - var JsonqlEnumError = /*@__PURE__*/(function (Error) { - function JsonqlEnumError() { - 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 = JsonqlEnumError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlEnumError); - } - } - - if ( Error ) JsonqlEnumError.__proto__ = Error; - JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); - JsonqlEnumError.prototype.constructor = JsonqlEnumError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlEnumError'; - }; - - Object.defineProperties( JsonqlEnumError, staticAccessors ); - - return JsonqlEnumError; - }(Error)); - - // this will throw from inside the checkOptions - var JsonqlTypeError = /*@__PURE__*/(function (Error) { - function JsonqlTypeError() { - 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 = JsonqlTypeError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlTypeError); - } - } - - if ( Error ) JsonqlTypeError.__proto__ = Error; - JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); - JsonqlTypeError.prototype.constructor = JsonqlTypeError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlTypeError'; - }; - - Object.defineProperties( JsonqlTypeError, staticAccessors ); - - return JsonqlTypeError; - }(Error)); - - // allow supply a custom checker function - // if that failed then we throw this error - var JsonqlCheckerError = /*@__PURE__*/(function (Error) { - function JsonqlCheckerError() { - 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 = JsonqlCheckerError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlCheckerError); - } - } - - if ( Error ) JsonqlCheckerError.__proto__ = Error; - JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); - JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlCheckerError'; - }; - - Object.defineProperties( JsonqlCheckerError, staticAccessors ); - - return JsonqlCheckerError; - }(Error)); - - // custom validation error class - // when validaton failed - var JsonqlValidationError = /*@__PURE__*/(function (Error) { - function JsonqlValidationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlValidationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlValidationError); - } - } - - if ( Error ) JsonqlValidationError.__proto__ = Error; - JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); - JsonqlValidationError.prototype.constructor = JsonqlValidationError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlValidationError'; - }; - - Object.defineProperties( JsonqlValidationError, staticAccessors ); - - return JsonqlValidationError; - }(Error)); - - /** - * This is a custom error to throw whenever a error happen inside the jsonql - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlError = /*@__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)); - - // this is from an example from Koa team to use for internal middleware ctx.throw - // but after the test the res.body part is unable to extract the required data - // I keep this one here for future reference - - var JsonqlServerError = /*@__PURE__*/(function (Error) { - function JsonqlServerError(statusCode, message) { - Error.call(this, message); - this.statusCode = statusCode; - this.className = JsonqlServerError.name; - } - - if ( Error ) JsonqlServerError.__proto__ = Error; - JsonqlServerError.prototype = Object.create( Error && Error.prototype ); - JsonqlServerError.prototype.constructor = JsonqlServerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlServerError'; - }; - - Object.defineProperties( JsonqlServerError, staticAccessors ); - - return JsonqlServerError; - }(Error)); - - // server side - - var errors = /*#__PURE__*/Object.freeze({ - __proto__: null, - Jsonql406Error: Jsonql406Error, - Jsonql500Error: Jsonql500Error, - JsonqlAuthorisationError: JsonqlAuthorisationError, - JsonqlContractAuthError: JsonqlContractAuthError, - JsonqlResolverAppError: JsonqlResolverAppError, - JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, - JsonqlEnumError: JsonqlEnumError, - JsonqlTypeError: JsonqlTypeError, - JsonqlCheckerError: JsonqlCheckerError, - JsonqlValidationError: JsonqlValidationError, - JsonqlError: JsonqlError, - JsonqlServerError: JsonqlServerError - }); - - // this will add directly to the then call in each http call - var JsonqlError$1 = JsonqlError; - - /** - * We can not just check something like result.data what if the result if false? - * @param {object} obj the result object - * @param {string} key we want to check if its exist or not - * @return {boolean} true on found - */ - var isObjectHasKey$1 = function (obj, key) { - var keys = Object.keys(obj); - return !!keys.filter(function (k) { return key === k; }).length; - }; - - /** - * It will ONLY have our own jsonql specific implement check - * @param {object} result the server return result - * @return {object} this will just throw error - */ - function clientErrorsHandler(result) { - if (isObjectHasKey$1(result, 'error')) { - var error = result.error; - var className = error.className; - var name = error.name; - var errorName = className || name; - // just throw the whole thing back - var msg = error.message || NO_ERROR_MSG$1; - var detail = error.detail || error; - if (errorName && errors[errorName]) { - throw new errors[className](msg, detail) - } - throw new JsonqlError$1(msg, detail) - } - // pass through to the next - return result; - } - - // get error name by instance - var UNKNOWN_ERROR = 'unknown'; - - /** - * @param {array} errs list of errors to compare from - * @param {object} e the error captured - * @return {array} filtered with name as value - */ - function mapErrToName(errs, e) { - return errs.filter(function (err) { return e instanceof err; }) - .map(function (err) { return err.name; }) - } - - /** - * @param {array} errs list of errors to compare from - * @param {object} e the error captured - * @return {string} name of the error object - */ - function getErrorNameByInstance(errs, e) { - var error = mapErrToName(errs, e); - return error.length ? error[0] : UNKNOWN_ERROR - } - - /** - * the same as above with a default JsonqlError as default - * @param {array} errs same - * @param {object} e error itself - * @return {string} the name of the error - */ - function getErrorNameByInstanceWithDefault(errs, e) { - var name = getErrorNameByInstance(errs, e); - return name === UNKNOWN_ERROR ? 'JsonqlError' : name; - } - - /** - * this will put into generator call at the very end and catch - * the error throw from inside then throw again - * this is necessary because we split calls inside and the throw - * will not reach the actual client unless we do it this way - * @param {object} e Error - * @return {void} just throw - */ - function finalCatch(e) { - // this is a hack to get around the validateAsync not actually throw error - // instead it just rejected it with the array of failed parameters - if (Array.isArray(e)) { - // if we want the message then I will have to create yet another function - // to wrap this function to provide the name prop - throw new JsonqlValidationError('', e) - } - var msg = e.message || NO_ERROR_MSG$1; - var detail = e.detail || e; - switch (true) { - case e instanceof Jsonql406Error: - throw new Jsonql406Error(msg, detail) - case e instanceof Jsonql500Error: - throw new Jsonql500Error(msg, detail) - case e instanceof JsonqlAuthorisationError: - throw new JsonqlAuthorisationError(msg, detail) - case e instanceof JsonqlContractAuthError: - throw new JsonqlContractAuthError(msg, detail) - case e instanceof JsonqlResolverAppError: - throw new JsonqlResolverAppError(msg, detail) - case e instanceof JsonqlResolverNotFoundError: - throw new JsonqlResolverNotFoundError(msg, detail) - case e instanceof JsonqlEnumError: - throw new JsonqlEnumError(msg, detail) - case e instanceof JsonqlTypeError: - throw new JsonqlTypeError(msg, detail) - case e instanceof JsonqlCheckerError: - throw new JsonqlCheckerError(msg, detail) - case e instanceof JsonqlValidationError: - throw new JsonqlValidationError(msg, detail) - case e instanceof JsonqlServerError: - throw new JsonqlServerError(msg, detail) - default: - throw new JsonqlError(msg, detail) - } - } - - // jsonql-errors main interface - var JSONQL_ERRORS_INFO = '__PLACEHOLDER__'; - - var errors$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - JSONQL_ERRORS_INFO: JSONQL_ERRORS_INFO, - UNKNOWN_ERROR: UNKNOWN_ERROR, - getErrorByStatus: getErrorByStatus, - clientErrorsHandler: clientErrorsHandler, - finalCatch: finalCatch, - getErrorNameByInstance: getErrorNameByInstance, - getErrorNameByInstanceWithDefault: getErrorNameByInstanceWithDefault, - Jsonql406Error: Jsonql406Error, - Jsonql500Error: Jsonql500Error, - JsonqlAuthorisationError: JsonqlAuthorisationError, - JsonqlContractAuthError: JsonqlContractAuthError, - JsonqlResolverAppError: JsonqlResolverAppError, - JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, - JsonqlEnumError: JsonqlEnumError, - JsonqlTypeError: JsonqlTypeError, - JsonqlCheckerError: JsonqlCheckerError, - JsonqlValidationError: JsonqlValidationError, - JsonqlError: JsonqlError, - JsonqlServerError: JsonqlServerError - }); - - // split the contract into the node side and the generic side - /** - * Check if the json is a contract file or not - * @param {object} contract json object - * @return {boolean} true - */ - function checkIsContract(contract) { - return isPlainObject(contract) - && ( - isObjectHasKey(contract, QUERY_NAME) - || isObjectHasKey(contract, MUTATION_NAME) - || isObjectHasKey(contract, SOCKET_NAME) - ) - } - - /** - * Wrapper method that check if it's contract then return the contract or false - * @param {object} contract the object to check - * @return {boolean | object} false when it's not - */ - function isContract(contract) { - return checkIsContract(contract) ? contract : false; - } - - /** - * generate a 32bit hash based on the function.toString() - * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery - * @param {string} s the converted to string function - * @return {string} the hashed function string - */ - function hashCode(s) { - return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) - } - - // take only the module part which is what we use here - /** - * @param {object} jsonqlInstance the init instance of jsonql client - * @param {object} contract the static contract - * @return {object} contract may be from server - */ - var getContractFromConfig = function(jsonqlInstance, contract) { - if ( contract === void 0 ) contract = {}; - - if (isContract(contract)) { - return Promise.resolve(contract) - } - return jsonqlInstance.getContract() - }; - // wrapper method to make sure it's a string - var hashCode$1 = function (str) { return hashCode(str) + ''; }; - var USERDATA_TABLE = 'userdata'; - var CLS_LOCAL_STORE_NAME = 'localStore'; - var CLS_SESS_STORE_NAME = 'sessionStore'; - var CLS_CONTRACT_NAME = 'contract'; - var CLS_PROFILE_IDX = 'prof_idx'; - var ZERO_IDX = 0; - - /** - * The code was extracted from: - * https://github.com/davidchambers/Base64.js - */ - - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - - function InvalidCharacterError(message) { - this.message = message; - } - - InvalidCharacterError.prototype = new Error(); - InvalidCharacterError.prototype.name = 'InvalidCharacterError'; - - function polyfill (input) { - var str = String(input).replace(/=+$/, ''); - if (str.length % 4 == 1) { - throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); - } - for ( - // initialize result and counters - var bc = 0, bs, buffer, idx = 0, output = ''; - // get next character - buffer = str.charAt(idx++); - // character found in table? initialize bit storage and add its ascii value; - ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, - // and if not first of each 4 characters, - // convert the first 8 bits to one ascii character - bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 - ) { - // try to find character in table (0-63, not found => -1) - buffer = chars.indexOf(buffer); - } - return output; - } - - - var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; - - function b64DecodeUnicode(str) { - return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { - var code = p.charCodeAt(0).toString(16).toUpperCase(); - if (code.length < 2) { - code = '0' + code; - } - return '%' + code; - })); - } - - var base64_url_decode = function(str) { - var output = str.replace(/-/g, "+").replace(/_/g, "/"); - switch (output.length % 4) { - case 0: - break; - case 2: - output += "=="; - break; - case 3: - output += "="; - break; - default: - throw "Illegal base64url string!"; - } - - try{ - return b64DecodeUnicode(output); - } catch (err) { - return atob(output); - } - }; - - function InvalidTokenError(message) { - this.message = message; - } - - InvalidTokenError.prototype = new Error(); - InvalidTokenError.prototype.name = 'InvalidTokenError'; - - var lib = function (token,options) { - if (typeof token !== 'string') { - throw new InvalidTokenError('Invalid token specified'); - } - - options = options || {}; - var pos = options.header === true ? 0 : 1; - try { - return JSON.parse(base64_url_decode(token.split('.')[pos])); - } catch (e) { - throw new InvalidTokenError('Invalid token specified: ' + e.message); - } - }; - - var InvalidTokenError_1 = InvalidTokenError; - lib.InvalidTokenError = InvalidTokenError_1; - - /** `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; - }; - - // when the user is login with the jwt - - 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 = lib(token); - return validate(t) - } - throw new JsonqlError('Token must be a string!') - } - - /** - * Check several parameter that there is something in the param - * @param {*} param input - * @return {boolean} - */ - var isNotEmpty = function (a) { - if (isArray(a)) { - return true; - } - return a !== undefined && a !== null && trim(a) !== ''; - }; - - /** `Object#toString` result references. */ - var numberTag = '[object Number]'; - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - // validator numbers - /** - * @2015-05-04 found a problem if the value is a number like string - * it will pass, so add a chck if it's string before we pass to next - * @param {number} value expected value - * @return {boolean} true if OK - */ - var checkIsNumber = function(value) { - return isString(value) ? false : !isNaN( parseFloat(value) ) - }; - - // check for boolean - - /** - * @param {boolean} value expected - * @return {boolean} true if OK - */ - var checkIsBoolean = function(value) { - return value !== null && value !== undefined && typeof value === 'boolean' - }; - - // validate any thing only check if there is something - - /** - * @param {*} value the value - * @param {boolean} [checkNull=true] strict check if there is null value - * @return {boolean} true is OK - */ - var checkIsAny = function(value, checkNull) { - if ( checkNull === void 0 ) checkNull = true; - - if (value !== undefined && value !== '' && trim(value) !== '') { - if (checkNull === false || (checkNull === true && value !== null)) { - return true; - } - } - return false; - }; - - // Good practice rule - No magic number - - var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; - var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; - var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; - // @TODO the jsdoc return array. and we should also allow array syntax - var DEFAULT_TYPE$1 = DEFAULT_TYPE; - var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; - var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; - - var TYPE_KEY$1 = TYPE_KEY; - var OPTIONAL_KEY$1 = OPTIONAL_KEY; - var ENUM_KEY$1 = ENUM_KEY; - var ARGS_KEY$1 = ARGS_KEY; - var CHECKER_KEY$1 = CHECKER_KEY; - var ALIAS_KEY$1 = ALIAS_KEY; - - var ARRAY_TYPE$1 = ARRAY_TYPE; - var OBJECT_TYPE$1 = OBJECT_TYPE; - var STRING_TYPE$1 = STRING_TYPE; - var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; - var NUMBER_TYPE$1 = NUMBER_TYPE; - var KEY_WORD$1 = KEY_WORD; - var OR_SEPERATOR$1 = OR_SEPERATOR; - - // not actually in use - // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; - - // primitive types - - /** - * this is a wrapper method to call different one based on their type - * @param {string} type to check - * @return {function} a function to handle the type - */ - var combineFn = function(type) { - switch (type) { - case NUMBER_TYPE$1: - return checkIsNumber; - case STRING_TYPE$1: - return checkIsString; - case BOOLEAN_TYPE$1: - return checkIsBoolean; - default: - return checkIsAny; - } - }; - - // validate array type - - /** - * @param {array} value expected - * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well - * @return {boolean} true if OK - */ - var checkIsArray = function(value, type) { - if ( type === void 0 ) type=''; - - if (isArray(value)) { - if (type === '' || trim(type)==='') { - return true; - } - // we test it in reverse - // @TODO if the type is an array (OR) then what? - // we need to take into account this could be an array - var c = value.filter(function (v) { return !combineFn(type)(v); }); - return !(c.length > 0) - } - return false; - }; - - /** - * check if it matches the array. pattern - * @param {string} type - * @return {boolean|array} false means NO, always return array - */ - var isArrayLike = function(type) { - // @TODO could that have something like array<> instead of array.<>? missing the dot? - // because type script is Array without the dot - if (type.indexOf(ARRAY_TYPE_LFT$1) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { - var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); - if (_type.indexOf(OR_SEPERATOR$1)) { - return _type.split(OR_SEPERATOR$1) - } - return [_type] - } - return false; - }; - - /** - * we might encounter something like array. then we need to take it apart - * @param {object} p the prepared object for processing - * @param {string|array} type the type came from - * @return {boolean} for the filter to operate on - */ - var arrayTypeHandler = function(p, type) { - var arg = p.arg; - // need a special case to handle the OR type - // we need to test the args instead of the type(s) - if (type.length > 1) { - return !arg.filter(function (v) { return ( - !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) - ); }).length; - } - // type is array so this will be or! - return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length; - }; - - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]'; - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** Used for built-in method references. */ - var objectProto$3 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - - /** Built-in value references. */ - var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER$1 = 9007199254740991; - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; - } - - /** `Object#toString` result references. */ - var argsTag$1 = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - mapTag = '[object Map]', - numberTag$1 = '[object Number]', - objectTag$1 = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag$1 = '[object String]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag$1] = - typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag$1] = - typedArrayTags[weakMapTag] = false; - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - - /** Detect free variable `exports`. */ - var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports$1 && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - - /** Used for built-in method references. */ - var objectProto$4 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$3 = objectProto$4.hasOwnProperty; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$3.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$5 = Object.prototype; - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; - - return value === proto; - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeKeys = overArg(Object.keys, Object); - - /** Used for built-in method references. */ - var objectProto$6 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$4 = objectProto$6.hasOwnProperty; - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$4.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** `Object#toString` result references. */ - var asyncTag = '[object AsyncFunction]', - funcTag$1 = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike$1(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype; - - /** Built-in value references. */ - var splice = arrayProto.splice; - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** Used for built-in method references. */ - var funcProto$1 = Function.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$1 = funcProto$1.toString; - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString$1.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used for built-in method references. */ - var funcProto$2 = Function.prototype, - objectProto$7 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$2 = funcProto$2.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$5 = objectProto$7.hasOwnProperty; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString$2.call(hasOwnProperty$5).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /* Built-in method references that are verified to be native. */ - var Map$1 = getNative(root, 'Map'); - - /* Built-in method references that are verified to be native. */ - var nativeCreate = getNative(Object, 'create'); - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used for built-in method references. */ - var objectProto$8 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$6 = objectProto$8.hasOwnProperty; - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty$6.call(data, key) ? data[key] : undefined; - } - - /** Used for built-in method references. */ - var objectProto$9 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$7 = objectProto$9.hasOwnProperty; - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key); - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; - return this; - } - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map$1 || ListCache), - 'string': new Hash - }; - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; - - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED$2); - return this; - } - - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } - - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } - - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } - - /** Built-in value references. */ - var Uint8Array$1 = root.Uint8Array; - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$1 = 1, - COMPARE_UNORDERED_FLAG$1 = 2; - - /** `Object#toString` result references. */ - var boolTag$1 = '[object Boolean]', - dateTag$1 = '[object Date]', - errorTag$1 = '[object Error]', - mapTag$1 = '[object Map]', - numberTag$2 = '[object Number]', - regexpTag$1 = '[object RegExp]', - setTag$1 = '[object Set]', - stringTag$2 = '[object String]', - symbolTag$1 = '[object Symbol]'; - - var arrayBufferTag$1 = '[object ArrayBuffer]', - dataViewTag$1 = '[object DataView]'; - - /** Used to convert symbols to primitives and strings. */ - var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined, - symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag$1: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag$1: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array$1(object), new Uint8Array$1(other))) { - return false; - } - return true; - - case boolTag$1: - case dateTag$1: - case numberTag$2: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag$1: - return object.name == other.name && object.message == other.message; - - case regexpTag$1: - case stringTag$2: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag$1: - var convert = mapToArray; - - case setTag$1: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG$1; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag$1: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** Used for built-in method references. */ - var objectProto$a = Object.prototype; - - /** Built-in value references. */ - var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable$1.call(object, symbol); - }); - }; - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$2 = 1; - - /** Used for built-in method references. */ - var objectProto$b = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$8 = objectProto$b.hasOwnProperty; - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) { - return false; - } - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'); - - /* Built-in method references that are verified to be native. */ - var Promise$1 = getNative(root, 'Promise'); - - /* Built-in method references that are verified to be native. */ - var Set$1 = getNative(root, 'Set'); - - /* Built-in method references that are verified to be native. */ - var WeakMap$1 = getNative(root, 'WeakMap'); - - /** `Object#toString` result references. */ - var mapTag$2 = '[object Map]', - objectTag$2 = '[object Object]', - promiseTag = '[object Promise]', - setTag$2 = '[object Set]', - weakMapTag$1 = '[object WeakMap]'; - - var dataViewTag$2 = '[object DataView]'; - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map$1), - promiseCtorString = toSource(Promise$1), - setCtorString = toSource(Set$1), - weakMapCtorString = toSource(WeakMap$1); - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$2) || - (Map$1 && getTag(new Map$1) != mapTag$2) || - (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || - (Set$1 && getTag(new Set$1) != setTag$2) || - (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag$2 ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag$2; - case mapCtorString: return mapTag$2; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag$2; - case weakMapCtorString: return weakMapTag$1; - } - } - return result; - }; - } - - var getTag$1 = getTag; - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$3 = 1; - - /** `Object#toString` result references. */ - var argsTag$2 = '[object Arguments]', - arrayTag$1 = '[object Array]', - objectTag$3 = '[object Object]'; - - /** Used for built-in method references. */ - var objectProto$c = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$9 = objectProto$c.hasOwnProperty; - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag$1 : getTag$1(object), - othTag = othIsArr ? arrayTag$1 : getTag$1(other); - - objTag = objTag == argsTag$2 ? objectTag$3 : objTag; - othTag = othTag == argsTag$2 ? objectTag$3 : othTag; - - var objIsObj = objTag == objectTag$3, - othIsObj = othTag == objectTag$3, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { - var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$4 = 1, - COMPARE_UNORDERED_FLAG$2 = 2; - - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } - - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - - /** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } - - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } - - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /** Error message constants. */ - var FUNC_ERROR_TEXT = 'Expected a function'; - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** Used to match property names within property paths. */ - var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** Used as references for various `Number` constants. */ - var INFINITY$1 = 1 / 0; - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; - } - - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$5 = 1, - COMPARE_UNORDERED_FLAG$3 = 2; - - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); - }; - } - - /** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ - function identity(value) { - return value; - } - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - - /** - * Creates a function that returns the value at `path` of a given object. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - * @example - * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; - * - * _.map(objects, _.property('a.b')); - * // => [2, 1] - * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] - */ - function property(path) { - return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); - } - - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } - - // validate object type - /** - * @TODO if provide with the keys then we need to check if the key:value type as well - * @param {object} value expected - * @param {array} [keys=null] if it has the keys array to compare as well - * @return {boolean} true if OK - */ - var checkIsObject = function(value, keys) { - if ( keys === void 0 ) keys=null; - - if (isPlainObject(value)) { - if (!keys) { - return true; - } - if (checkIsArray(keys)) { - // please note we DON'T care if some is optional - // plese refer to the contract.json for the keys - return !keys.filter(function (key) { - var _value = value[key.name]; - return !(key.type.length > key.type.filter(function (type) { - var tmp; - if (_value !== undefined) { - if ((tmp = isArrayLike(type)) !== false) { - return !arrayTypeHandler({arg: _value}, tmp) - // return tmp.filter(t => !checkIsArray(_value, t)).length; - // @TODO there might be an object within an object with keys as well :S - } - return !combineFn(type)(_value) - } - return true; - }).length) - }).length; - } - } - return false; - }; - - /** - * fold this into it's own function to handler different object type - * @param {object} p the prepared object for process - * @return {boolean} - */ - var objectTypeHandler = function(p) { - var arg = p.arg; - var param = p.param; - var _args = [arg]; - if (Array.isArray(param.keys) && param.keys.length) { - _args.push(param.keys); - } - // just simple check - return Reflect.apply(checkIsObject, null, _args) - }; - - // move the index.js code here that make more sense to find where things are - // import debug from 'debug' - // const debugFn = debug('jsonql-params-validator:validator') - // also export this for use in other places - - /** - * We need to handle those optional parameter without a default value - * @param {object} params from contract.json - * @return {boolean} for filter operation false is actually OK - */ - var optionalHandler = function( params ) { - var arg = params.arg; - var param = params.param; - if (isNotEmpty(arg)) { - // debug('call optional handler', arg, params); - // loop through the type in param - return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } - ).length) - } - return false; - }; - - /** - * actually picking the validator - * @param {*} type for checking - * @param {*} value for checking - * @return {boolean} true on OK - */ - var validateHandler = function(type, value) { - var tmp; - switch (true) { - case type === OBJECT_TYPE$1: - // debugFn('call OBJECT_TYPE') - return !objectTypeHandler(value) - case type === ARRAY_TYPE$1: - // debugFn('call ARRAY_TYPE') - return !checkIsArray(value.arg) - // @TODO when the type is not present, it always fall through here - // so we need to find a way to actually pre-check the type first - // AKA check the contract.json map before running here - case (tmp = isArrayLike(type)) !== false: - // debugFn('call ARRAY_LIKE: %O', value) - return !arrayTypeHandler(value, tmp) - default: - return !combineFn(type)(value.arg) - } - }; - - /** - * it get too longer to fit in one line so break it out from the fn below - * @param {*} arg value - * @param {object} param config - * @return {*} value or apply default value - */ - var getOptionalValue = function(arg, param) { - if (arg !== undefined) { - return arg; - } - return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null) - }; - - /** - * padding the arguments with defaultValue if the arguments did not provide the value - * this will be the name export - * @param {array} args normalized arguments - * @param {array} params from contract.json - * @return {array} merge the two together - */ - var normalizeArgs = function(args, params) { - // first we should check if this call require a validation at all - // there will be situation where the function doesn't need args and params - if (!checkIsArray(params)) { - // debugFn('params value', params) - throw new JsonqlError(PARAMS_NOT_ARRAY_ERR) - } - if (params.length === 0) { - return []; - } - if (!checkIsArray(args)) { - throw new JsonqlError(ARGS_NOT_ARRAY_ERR) - } - // debugFn(args, params); - // fall through switch - switch(true) { - case args.length == params.length: // standard - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, - param: params[i] - } - ); }) - case params[0].variable === true: // using spread syntax - var type = params[0].type; - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, // keep the index for reference - param: params[i] || { type: type, name: '_' } - } - ); }) - // with optional defaultValue parameters - case args.length < params.length: - return params.map(function (param, i) { return ( - { - param: param, - index: i, - arg: getOptionalValue(args[i], param), - optional: param.optional || false - } - ); }) - // this one pass more than it should have anything after the args.length will be cast as any type - case args.length > params.length: - var ctn = params.length; - // this happens when we have those array. type - var _type = [ DEFAULT_TYPE$1 ]; - // we only looking at the first one, this might be a @BUG - /* - if ((tmp = isArrayLike(params[0].type[0])) !== false) { - _type = tmp; - } */ - // if we use the params as guide then the rest will get throw out - // which is not what we want, instead, anything without the param - // will get a any type and optional flag - return args.map(function (arg, i) { - var optional = i >= ctn ? true : !!params[i].optional; - var param = params[i] || { type: _type, name: ("_" + i) }; - return { - arg: optional ? getOptionalValue(arg, param) : arg, - index: i, - param: param, - optional: optional - } - }) - // @TODO find out if there is more cases not cover - default: // this should never happen - // debugFn('args', args) - // debugFn('params', params) - // this is unknown therefore we just throw it! - throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) - } - }; - - // what we want is after the validaton we also get the normalized result - // which is with the optional property if the argument didn't provide it - /** - * process the array of params back to their arguments - * @param {array} result the params result - * @return {array} arguments - */ - var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; - - /** - * validator main interface - * @param {array} args the arguments pass to the method call - * @param {array} params from the contract for that method - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {array} empty array on success, or failed parameter and reasons - */ - var validateSync = function(args, params, withResult) { - var obj; - - if ( withResult === void 0 ) withResult = false; - var cleanArgs = normalizeArgs(args, params); - var checkResult = cleanArgs.filter(function (p) { - // v1.4.4 this fixed the problem, the root level optional is from the last fn - if (p.optional === true || p.param.optional === true) { - return optionalHandler(p) - } - // because array of types means OR so if one pass means pass - return !(p.param.type.length > p.param.type.filter( - function (type) { return validateHandler(type, p); } - ).length) - }); - // using the same convention we been using all this time - return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) - }; - - /** - * A wrapper method that return promise - * @param {array} args arguments - * @param {array} params from contract.json - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {object} promise.then or catch - */ - var validateAsync = function(args, params, withResult) { - if ( withResult === void 0 ) withResult = false; - - return new Promise(function (resolver, rejecter) { - var result = validateSync(args, params, withResult); - if (withResult) { - return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) - : resolver(result[DATA_KEY]) - } - // the different is just in the then or catch phrase - return result.length ? rejecter(result) : resolver([]) - }) - }; - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** Detect free variable `exports`. */ - var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; - - /** Built-in value references. */ - var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, - allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** Built-in value references. */ - var objectCreate = Object.create; - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike$1(value); - } - - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; - } - - /** Used for built-in method references. */ - var objectProto$d = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$a = objectProto$d.hasOwnProperty; - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$a.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$e = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$b = objectProto$e.hasOwnProperty; - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty$b.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn(object) { - return isArrayLike$1(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } - - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeMax = Math.max; - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ - function constant(value) { - return function() { - return value; - }; - } - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeNow = Date.now; - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike$1(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - - /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; - } - - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; - } - - /** Error message constants. */ - var FUNC_ERROR_TEXT$1 = 'Expected a function'; - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT$1); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols$1 = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = baseIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } - - /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ - function omitBy(object, predicate) { - return pickBy(object, negate(baseIteratee(predicate))); - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } - - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ - function findKey(object, predicate) { - return baseFindKey(object, baseIteratee(predicate), baseForOwn); - } - - /** - * @param {array} arr Array for check - * @param {*} value target - * @return {boolean} true on successs - */ - var isInArray = function(arr, value) { - return !!arr.filter(function (a) { return a === value; }).length; - }; - - var isObjectHasKey$2 = function(obj, key) { - var keys = Object.keys(obj); - return isInArray(keys, key) - }; - - // just not to make my head hurt - var isEmpty = function (value) { return !isNotEmpty(value); }; - - /** - * Map the alias to their key then grab their value over - * @param {object} config the user supplied config - * @param {object} appProps the default option map - * @return {object} the config keys replaced with the appProps key by the ALIAS - */ - function mapAliasConfigKeys(config, appProps) { - // need to do two steps - // 1. take key with alias key - var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$1]; } ); - if (isEqual(aliasMap, {})) { - return config; - } - return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) - } - - /** - * We only want to run the valdiation against the config (user supplied) value - * but keep the defaultOptions untouch - * @param {object} config configuraton supplied by user - * @param {object} appProps the default options map - * @return {object} the pristine values that will add back to the final output - */ - function preservePristineValues(config, appProps) { - // @BUG this will filter out those that is alias key - // we need to first map the alias keys back to their full key - var _config = mapAliasConfigKeys(config, appProps); - // take the default value out - var pristineValues = mapValues( - omitBy(appProps, function (value, key) { return isObjectHasKey$2(_config, key); }), - function (value) { return value.args; } - ); - // for testing the value - var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !isObjectHasKey$2(_config, key); }); - // output - return { - pristineValues: pristineValues, - checkAgainstAppProps: checkAgainstAppProps, - config: _config // passing this correct values back - } - } - - /** - * This will take the value that is ONLY need to check - * @param {object} config that one - * @param {object} props map for creating checking - * @return {object} put that arg into the args - */ - function processConfigAction(config, props) { - // debugFn('processConfigAction', props) - // v.1.2.0 add checking if its mark optional and the value is empty then pass - return mapValues(props, function (value, key) { - var obj, obj$1; - - return ( - config[key] === undefined || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) - ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) - : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) - ); - } - ) - } - - /** - * Quick transform - * @TODO we should only validate those that is pass from the config - * and pass through those values that is from the defaultOptions - * @param {object} opts that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ - function prepareArgsForValidation(opts, appProps) { - var ref = preservePristineValues(opts, appProps); - var config = ref.config; - var pristineValues = ref.pristineValues; - var checkAgainstAppProps = ref.checkAgainstAppProps; - // output - return [ - processConfigAction(config, checkAgainstAppProps), - pristineValues - ] - } - - // breaking the whole thing up to see what cause the multiple calls issue - - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:options:validation') - - /** - * just make sure it returns an array to use - * @param {*} arg input - * @return {array} output - */ - var toArray$1 = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; - - /** - * DIY in array - * @param {array} arr to check against - * @param {*} value to check - * @return {boolean} true on OK - */ - var inArray$1 = function (arr, value) { return ( - !!arr.filter(function (v) { return v === value; }).length - ); }; - - /** - * break out to make the code easier to read - * @param {object} value to process - * @param {function} cb the validateSync - * @return {array} empty on success - */ - function validateHandler$1(value, cb) { - var obj; - - // cb is the validateSync methods - var args = [ - [ value[ARGS_KEY$1] ], - [( obj = {}, obj[TYPE_KEY$1] = toArray$1(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] - ]; - // debugFn('validateHandler', args) - return Reflect.apply(cb, null, args) - } - - /** - * Check against the enum value if it's provided - * @param {*} value to check - * @param {*} enumv to check against if it's not false - * @return {boolean} true on OK - */ - var enumHandler = function (value, enumv) { - if (checkIsArray(enumv)) { - return inArray$1(enumv, value) - } - return true; - }; - - /** - * Allow passing a function to check the value - * There might be a problem here if the function is incorrect - * and that will makes it hard to debug what is going on inside - * @TODO there could be a few feature add to this one under different circumstance - * @param {*} value to check - * @param {function} checker for checking - */ - var checkerHandler = function (value, checker) { - try { - return isFunction(checker) ? checker.apply(null, [value]) : false; - } catch (e) { - return false; - } - }; - - /** - * Taken out from the runValidaton this only validate the required values - * @param {array} args from the config2argsAction - * @param {function} cb validateSync - * @return {array} of configuration values - */ - function runValidationAction(cb) { - return function (value, key) { - // debugFn('runValidationAction', key, value) - if (value[KEY_WORD$1]) { - return value[ARGS_KEY$1] - } - var check = validateHandler$1(value, cb); - if (check.length) { - // log('runValidationAction', key, value) - throw new JsonqlTypeError(key, check) - } - if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { - // log(ENUM_KEY, value[ENUM_KEY]) - throw new JsonqlEnumError(key) - } - if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { - // log(CHECKER_KEY, value[CHECKER_KEY]) - throw new JsonqlCheckerError(key) - } - return value[ARGS_KEY$1] - } - } - - /** - * @param {object} args from the config2argsAction - * @param {function} cb validateSync - * @return {object} of configuration values - */ - function runValidation(args, cb) { - var argsForValidate = args[0]; - var pristineValues = args[1]; - // turn the thing into an array and see what happen here - // debugFn('_args', argsForValidate) - var result = mapValues(argsForValidate, runValidationAction(cb)); - return merge(result, pristineValues) - } - - /// this is port back from the client to share across all projects - - // import debug from 'debug' - // const debugFn = debug('jsonql-params-validator:check-options-async') - - /** - * Quick transform - * @param {object} config that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ - var configToArgs = function (config, appProps) { - return Promise.resolve( - prepareArgsForValidation(config, appProps) - ) - }; - - /** - * @param {object} config user provide configuration option - * @param {object} appProps mutation configuration options - * @param {object} constProps the immutable configuration options - * @param {function} cb the validateSync method - * @return {object} Promise resolve merge config object - */ - function checkOptionsAsync(config, appProps, constProps, cb) { - if ( config === void 0 ) config = {}; - - return configToArgs(config, appProps) - .then(function (args1) { return runValidation(args1, cb); }) - // next if every thing good then pass to final merging - .then(function (args2) { return merge({}, args2, constProps); }) - } - - // create function to construct the config entry so we don't need to keep building object - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:construct-config'); - /** - * @param {*} args value - * @param {string} type for value - * @param {boolean} [optional=false] - * @param {boolean|array} [enumv=false] - * @param {boolean|function} [checker=false] - * @return {object} config entry - */ - function constructConfig(args, type, optional, enumv, checker, alias) { - if ( optional === void 0 ) optional=false; - if ( enumv === void 0 ) enumv=false; - if ( checker === void 0 ) checker=false; - if ( alias === void 0 ) alias=false; - - var base = {}; - base[ARGS_KEY] = args; - base[TYPE_KEY] = type; - if (optional === true) { - base[OPTIONAL_KEY] = true; - } - if (checkIsArray(enumv)) { - base[ENUM_KEY] = enumv; - } - if (isFunction(checker)) { - base[CHECKER_KEY] = checker; - } - if (isString(alias)) { - base[ALIAS_KEY] = alias; - } - return base; - } - - // export also create wrapper methods - - /** - * This has a different interface - * @param {*} value to supply - * @param {string|array} type for checking - * @param {object} params to map against the config check - * @param {array} params.enumv NOT enum - * @param {boolean} params.optional false then nothing - * @param {function} params.checker need more work on this one later - * @param {string} params.alias mostly for cmd - */ - var createConfig = function (value, type, params) { - if ( params === void 0 ) params = {}; - - // Note the enumv not ENUM - // const { enumv, optional, checker, alias } = params; - // let args = [value, type, optional, enumv, checker, alias]; - var o = params[OPTIONAL_KEY]; - var e = params[ENUM_KEY]; - var c = params[CHECKER_KEY]; - var a = params[ALIAS_KEY]; - return constructConfig.apply(null, [value, type, o, e, c, a]) - }; - - /** - * We recreate the method here to avoid the circlar import - * @param {object} config user supply configuration - * @param {object} appProps mutation options - * @param {object} [constantProps={}] optional: immutation options - * @return {object} all checked configuration - */ - var checkConfigAsync = function(validateSync) { - return function(config, appProps, constantProps) { - if ( constantProps === void 0 ) constantProps= {}; - - return checkOptionsAsync(config, appProps, constantProps, validateSync) - } - }; - - // export - var isString$1 = checkIsString; - var isNumber$1 = checkIsNumber; - var validateAsync$1 = validateAsync; - - var createConfig$1 = createConfig; - - var checkConfigAsync$1 = checkConfigAsync(validateSync); - - var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; - - var appProps = { - algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), - expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), - notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), - audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), - subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), - issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), - noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), - header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), - keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), - mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) - }; - - /** - * @param {boolean} sec return in second or not - * @return {number} timestamp - */ - var timestamp$1 = function (sec) { - if ( sec === void 0 ) sec = false; - - var time = Date.now(); - return sec ? Math.floor( time / 1000 ) : time; - }; - - var assign = make_assign(); - var create = make_create(); - var trim$1 = make_trim(); - var Global = (typeof window !== 'undefined' ? window : commonjsGlobal); - - var util = { - assign: assign, - create: create, - trim: trim$1, - bind: bind, - slice: slice, - each: each, - map: map, - pluck: pluck, - isList: isList, - isFunction: isFunction$1, - isObject: isObject$1, - Global: Global - }; - - function make_assign() { - if (Object.assign) { - return Object.assign - } else { - return function shimAssign(obj, props1, props2, etc) { - var arguments$1 = arguments; - - for (var i = 1; i < arguments.length; i++) { - each(Object(arguments$1[i]), function(val, key) { - obj[key] = val; - }); - } - return obj - } - } - } - - function make_create() { - if (Object.create) { - return function create(obj, assignProps1, assignProps2, etc) { - var assignArgsList = slice(arguments, 1); - return assign.apply(this, [Object.create(obj)].concat(assignArgsList)) - } - } else { - function F() {} // eslint-disable-line no-inner-declarations - return function create(obj, assignProps1, assignProps2, etc) { - var assignArgsList = slice(arguments, 1); - F.prototype = obj; - return assign.apply(this, [new F()].concat(assignArgsList)) - } - } - } - - function make_trim() { - if (String.prototype.trim) { - return function trim(str) { - return String.prototype.trim.call(str) - } - } else { - return function trim(str) { - return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '') - } - } - } - - function bind(obj, fn) { - return function() { - return fn.apply(obj, Array.prototype.slice.call(arguments, 0)) - } - } - - function slice(arr, index) { - return Array.prototype.slice.call(arr, index || 0) - } - - function each(obj, fn) { - pluck(obj, function(val, key) { - fn(val, key); - return false - }); - } - - function map(obj, fn) { - var res = (isList(obj) ? [] : {}); - pluck(obj, function(v, k) { - res[k] = fn(v, k); - return false - }); - return res - } - - function pluck(obj, fn) { - if (isList(obj)) { - for (var i=0; i= 0; i--) { - var key = localStorage().key(i); - fn(read(key), key); - } - } - - function remove(key) { - return localStorage().removeItem(key) - } - - function clearAll() { - return localStorage().clear() - } - - // cookieStorage is useful Safari private browser mode, where localStorage - // doesn't work but cookies do. This implementation is adopted from - // https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage - - - var Global$2 = util.Global; - var trim$2 = util.trim; - - var cookieStorage = { - name: 'cookieStorage', - read: read$1, - write: write$1, - each: each$3, - remove: remove$1, - clearAll: clearAll$1, - }; - - var doc = Global$2.document; - - function read$1(key) { - if (!key || !_has(key)) { return null } - var regexpStr = "(?:^|.*;\\s*)" + - escape(key).replace(/[\-\.\+\*]/g, "\\$&") + - "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"; - return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")) - } - - function each$3(callback) { - var cookies = doc.cookie.split(/; ?/g); - for (var i = cookies.length - 1; i >= 0; i--) { - if (!trim$2(cookies[i])) { - continue - } - var kvp = cookies[i].split('='); - var key = unescape(kvp[0]); - var val = unescape(kvp[1]); - callback(val, key); - } - } - - function write$1(key, data) { - if(!key) { return } - doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; - } - - function remove$1(key) { - if (!key || !_has(key)) { - return - } - doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; - } - - function clearAll$1() { - each$3(function(_, key) { - remove$1(key); - }); - } - - function _has(key) { - return (new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie) - } - - var defaults = defaultsPlugin; - - function defaultsPlugin() { - var defaultValues = {}; - - return { - defaults: defaults, - get: get - } - - function defaults(_, values) { - defaultValues = values; - } - - function get(super_fn, key) { - var val = super_fn(); - return (val !== undefined ? val : defaultValues[key]) - } - } - - var bind$2 = util.bind; - var each$4 = util.each; - var create$2 = util.create; - var slice$2 = util.slice; - - var events = eventsPlugin; - - function eventsPlugin() { - var pubsub = _newPubSub(); - - return { - watch: watch, - unwatch: unwatch, - once: once, - - set: set, - remove: remove, - clearAll: clearAll - } - - // new pubsub functions - function watch(_, key, listener) { - return pubsub.on(key, bind$2(this, listener)) - } - function unwatch(_, subId) { - pubsub.off(subId); - } - function once(_, key, listener) { - pubsub.once(key, bind$2(this, listener)); - } - - // overwrite function to fire when appropriate - function set(super_fn, key, val) { - var oldVal = this.get(key); - super_fn(); - pubsub.fire(key, val, oldVal); - } - function remove(super_fn, key) { - var oldVal = this.get(key); - super_fn(); - pubsub.fire(key, undefined, oldVal); - } - function clearAll(super_fn) { - var oldVals = {}; - this.each(function(val, key) { - oldVals[key] = val; - }); - super_fn(); - each$4(oldVals, function(oldVal, key) { - pubsub.fire(key, undefined, oldVal); - }); - } - } - - - function _newPubSub() { - return create$2(_pubSubBase, { - _id: 0, - _subSignals: {}, - _subCallbacks: {} - }) - } - - var _pubSubBase = { - _id: null, - _subCallbacks: null, - _subSignals: null, - on: function(signal, callback) { - if (!this._subCallbacks[signal]) { - this._subCallbacks[signal] = {}; - } - this._id += 1; - this._subCallbacks[signal][this._id] = callback; - this._subSignals[this._id] = signal; - return this._id - }, - off: function(subId) { - var signal = this._subSignals[subId]; - delete this._subCallbacks[signal][subId]; - delete this._subSignals[subId]; - }, - once: function(signal, callback) { - var subId = this.on(signal, bind$2(this, function() { - callback.apply(this, arguments); - this.off(subId); - })); - }, - fire: function(signal) { - var args = slice$2(arguments, 1); - each$4(this._subCallbacks[signal], function(callback) { - callback.apply(this, args); - }); - } - }; - - var lzString = createCommonjsModule(function (module) { - /* eslint-disable */ - // Copyright (c) 2013 Pieroxy - // This work is free. You can redistribute it and/or modify it - // under the terms of the WTFPL, Version 2 - // For more information see LICENSE.txt or http://www.wtfpl.net/ - // - // For more information, the home page: - // http://pieroxy.net/blog/pages/lz-string/testing.html - // - // LZ-based compression algorithm, version 1.4.4 - var LZString = (function() { - - // private property - var f = String.fromCharCode; - var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; - var baseReverseDic = {}; - - function getBaseValue(alphabet, character) { - if (!baseReverseDic[alphabet]) { - baseReverseDic[alphabet] = {}; - for (var i=0 ; i>> 8; - buf[i*2+1] = current_value % 256; - } - return buf; - }, - - //decompress from uint8array (UCS-2 big endian format) - decompressFromUint8Array:function (compressed) { - if (compressed===null || compressed===undefined){ - return LZString.decompress(compressed); - } else { - var buf=new Array(compressed.length/2); // 2 bytes per character - for (var i=0, TotalLen=buf.length; i> 1; - } - } else { - value = 1; - for (i=0 ; i> 1; - } - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - delete context_dictionaryToCreate[context_w]; - } else { - value = context_dictionary[context_w]; - for (i=0 ; i> 1; - } - - - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - // Add wc to the dictionary. - context_dictionary[context_wc] = context_dictSize++; - context_w = String(context_c); - } - } - - // Output the code for w. - if (context_w !== "") { - if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) { - if (context_w.charCodeAt(0)<256) { - for (i=0 ; i> 1; - } - } else { - value = 1; - for (i=0 ; i> 1; - } - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - delete context_dictionaryToCreate[context_w]; - } else { - value = context_dictionary[context_w]; - for (i=0 ; i> 1; - } - - - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - } - - // Mark the end of the stream - value = 2; - for (i=0 ; i> 1; - } - - // Flush the last char - while (true) { - context_data_val = (context_data_val << 1); - if (context_data_position == bitsPerChar-1) { - context_data.push(getCharFromInt(context_data_val)); - break; - } - else { context_data_position++; } - } - return context_data.join(''); - }, - - decompress: function (compressed) { - if (compressed == null) { return ""; } - if (compressed == "") { return null; } - return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); }); - }, - - _decompress: function (length, resetValue, getNextValue) { - var dictionary = [], - next, - enlargeIn = 4, - dictSize = 4, - numBits = 3, - entry = "", - result = [], - i, - w, - bits, resb, maxpower, power, - c, - data = {val:getNextValue(0), position:resetValue, index:1}; - - for (i = 0; i < 3; i += 1) { - dictionary[i] = i; - } - - bits = 0; - maxpower = Math.pow(2,2); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - switch (next = bits) { - case 0: - bits = 0; - maxpower = Math.pow(2,8); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - c = f(bits); - break; - case 1: - bits = 0; - maxpower = Math.pow(2,16); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - c = f(bits); - break; - case 2: - return ""; - } - dictionary[3] = c; - w = c; - result.push(c); - while (true) { - if (data.index > length) { - return ""; - } - - bits = 0; - maxpower = Math.pow(2,numBits); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - switch (c = bits) { - case 0: - bits = 0; - maxpower = Math.pow(2,8); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - dictionary[dictSize++] = f(bits); - c = dictSize-1; - enlargeIn--; - break; - case 1: - bits = 0; - maxpower = Math.pow(2,16); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - dictionary[dictSize++] = f(bits); - c = dictSize-1; - enlargeIn--; - break; - case 2: - return result.join(''); - } - - if (enlargeIn == 0) { - enlargeIn = Math.pow(2, numBits); - numBits++; - } - - if (dictionary[c]) { - entry = dictionary[c]; - } else { - if (c === dictSize) { - entry = w + w.charAt(0); - } else { - return null; - } - } - result.push(entry); - - // Add w+entry[0] to the dictionary. - dictionary[dictSize++] = w + entry.charAt(0); - enlargeIn--; - - w = entry; - - if (enlargeIn == 0) { - enlargeIn = Math.pow(2, numBits); - numBits++; - } - - } - } - }; - return LZString; - })(); - - if( module != null ) { - module.exports = LZString; - } - }); - - var compression = compressionPlugin; - - function compressionPlugin() { - return { - get: get, - set: set, - } - - function get(super_fn, key) { - var val = super_fn(key); - if (!val) { return val } - var decompressed = lzString.decompress(val); - // fallback to existing values that are not compressed - return (decompressed == null) ? val : this._deserialize(decompressed) - } - - function set(super_fn, key, val) { - var compressed = lzString.compress(this._serialize(val)); - super_fn(key, compressed); - } - } - - // sort of persist on the user side - - var storages = [localStorage_1, cookieStorage]; - var plugins = [defaults, events, compression]; - - var localStore = storeEngine.createStore(storages, plugins); - - var Global$3 = util.Global; - - var sessionStorage_1 = { - name: 'sessionStorage', - read: read$2, - write: write$2, - each: each$5, - remove: remove$2, - clearAll: clearAll$2 - }; - - function sessionStorage() { - return Global$3.sessionStorage - } - - function read$2(key) { - return sessionStorage().getItem(key) - } - - function write$2(key, data) { - return sessionStorage().setItem(key, data) - } - - function each$5(fn) { - for (var i = sessionStorage().length - 1; i >= 0; i--) { - var key = sessionStorage().key(i); - fn(read$2(key), key); - } - } - - function remove$2(key) { - return sessionStorage().removeItem(key) - } - - function clearAll$2() { - return sessionStorage().clear() - } - - // session store with watch - // @1.5.0 stop using the expired plugin and deal it ourself - // import expiredPlugin from 'store/plugins/expire' - - var storages$1 = [sessionStorage_1, cookieStorage]; - var plugins$1 = [defaults, compression]; - - var sessionStore = storeEngine.createStore(storages$1, plugins$1); - - // export store interface - - // export back the raw version for development purposes - var localStore$1 = localStore; - var sessionStore$1 = sessionStore; - - // ported from jsonql-params-validator - - /** - * @param {*} args arguments to send - *@return {object} formatted payload - */ - var formatPayload = function (args) { - var obj; - - return ( - ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) - ); - }; - - /** - * Get name from the payload (ported back from jsonql-koa) - * @param {*} payload to extract from - * @return {string} name - */ - function getNameFromPayload(payload) { - return Object.keys(payload)[0] - } - - /** - * wrapper method to add the timestamp as well - * @param {string} resolverName - * @param {*} payload - * @return {object} delierable - */ - function createDeliverable(resolverName, payload) { - var obj; - - return ( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME] = [ timestamp$1() ], obj ) - } - - /** - * @param {string} resolverName name of function - * @param {array} [args=[]] from the ...args - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createQuery(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - - if (isString(resolverName) && isArray(args)) { - var payload = formatPayload(args); - if (jsonp === true) { - return payload; - } - return createDeliverable(resolverName, payload) - } - throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) - } - - /** - * @param {string} resolverName name of function - * @param {*} payload to send - * @param {object} [condition={}] for what - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createMutation(resolverName, payload, condition, jsonp) { - if ( condition === void 0 ) condition = {}; - if ( jsonp === void 0 ) jsonp = false; - - var _payload = {}; - _payload[PAYLOAD_PARAM_NAME] = payload; - _payload[CONDITION_PARAM_NAME] = condition; - if (jsonp === true) { - return _payload; - } - if (isString(resolverName)) { - return createDeliverable(resolverName, _payload) - } - throw new JsonqlValidationError("[createMutation] expect resolverName to be string!", { resolverName: resolverName, payload: payload, condition: condition }) - } - - /** - * @return {object} _cb as key with timestamp - */ - var cacheBurst = function () { return ({ _cb: timestamp$1() }); }; - - // break up from node-middleware - - // ported from http-client - - /** - * handle the return data - * @TODO how to handle the return timestamp and calculate the diff? - * @param {object} result return from server - * @return {object} strip the data part out, or if the error is presented - */ - var resultHandler = function (result) { return ( - (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result - ); }; - - // new 1.5.0 - - // this becomes the base class instead of the HttpCls - var StoreClass = function StoreClass(opts) { - this.opts = opts; - // make it a string - this.instanceKey = hashCode$1(this.opts.hostname); - // pass this store for use later - this.localStore = localStore$1; - this.sessionStore = sessionStore$1; - /* - if (this.opts.debugOn) { // reuse this to clear out the data - this.log('clear all stores') - localStore.clearAll() - sessionStore.clearAll() - - localStore.set('TEST', Date.now()) - sessionStore.set('TEST', Date.now()) - } - */ - }; - - var prototypeAccessors = { lset: { configurable: true },lget: { configurable: true },sset: { configurable: true },sget: { configurable: true } }; - // store in local storage id by the instanceKey - // values should be an object so with key so we just merge - // into the existing store without going through the keys - StoreClass.prototype.__setMethod = function __setMethod (storeType, values) { - var obj; - - var store = this[storeType]; - var data = this.__getMethod(storeType); - var skey = this.opts.storageKey; - var ikey = this.instanceKey; - store.set(skey, ( obj = {}, obj[ikey] = data ? merge({}, data, values) : values, obj )); - }; - // return the data id by the instaceKey - StoreClass.prototype.__getMethod = function __getMethod (storeType) { - var store = this[storeType]; - var data = store.get(this.opts.storageKey); - return data ? data[this.instanceKey] : false - }; - // remove from local store id by instanceKey - StoreClass.prototype.__delMethod = function __delMethod (storeType, key) { - var data = this.__getMethod(storeType); - if (data) { - var store = {}; - for (var k in data) { - if (k !== key) { - store[k] = data[k]; - } - } - this.__setMethod(storeType, store); - } - }; - // clear everything by this instanceKey - StoreClass.prototype.__clearMethod = function __clearMethod (storeKey) { - var skey = this.opts.storageKey; - var store = this[storeKey]; - var data = store.get(skey); - if (data) { - var _store = {}; - for (var k in data) { - if (k !== this.instanceKey) { - _store[k] = data[k]; - } - } - store.set(skey, _store); - } - }; - // Alias for different store - prototypeAccessors.lset.set = function (values) { - return this.__setMethod(CLS_LOCAL_STORE_NAME, values) - }; - - prototypeAccessors.lget.get = function () { - return this.__getMethod(CLS_LOCAL_STORE_NAME) - }; - - StoreClass.prototype.ldel = function ldel (key) { - return this.__delMethod(CLS_LOCAL_STORE_NAME, key) - }; - - StoreClass.prototype.lclear = function lclear () { - return this.__clearMethod(CLS_LOCAL_STORE_NAME) - }; - - // store in session store id by the instanceKey - prototypeAccessors.sset.set = function (values) { - // this.log('--- sset ---', values) - return this.__setMethod(CLS_SESS_STORE_NAME, values) - }; - - prototypeAccessors.sget.get = function () { - return this.__getMethod(CLS_SESS_STORE_NAME) - }; - - StoreClass.prototype.sdel = function sdel (key) { - return this.__delMethod(CLS_SESS_STORE_NAME, key) - }; - - StoreClass.prototype.sclear = function sclear () { - return this.__clearMethod(CLS_SESS_STORE_NAME) - }; - - Object.defineProperties( StoreClass.prototype, prototypeAccessors ); - - // base HttpClass - /** - * It will ONLY have our own jsonql specific implement check - * @param {object} result the server return result - * @return {object} this will just throw error - */ - function clientErrorsHandler$1(result) { - if (isObjectHasKey(result, 'error')) { - var error = result.error; - var className = error.className; - var name = error.name; - var errorName = className || name; - // just throw the whole thing back - var msg = error.message || NO_ERROR_MSG; - var detail = error.detail || error; - console.info('--- errorName ---', errorName, errors$1); - - if (errorName && errors$1[errorName]) { - throw new errors$1[className](msg, detail) - } - throw new JsonqlError(msg, detail) - } - // pass through to the next - return result; - } - - - - // extract the one we need - var POST = API_REQUEST_METHODS[0]; - var PUT = API_REQUEST_METHODS[1]; - - var HttpClass = /*@__PURE__*/(function (StoreClass) { - function HttpClass(opts) { - StoreClass.call(this, opts); - // change the way how we init Fly - // flyio now become external depedencies and it makes it easier to switch - // @BUG should we run test to check if we have the windows object? - // this.log(opts) - // this.fly = opts.Fly ? new opts.Fly() : new Fly() - // to a different environment like WeChat mini app - - this.extraHeader = {}; - // @1.2.1 for adding query to the call on the fly - this.extraParams = {}; - // this.log('start up opts', opts); - this.reqInterceptor(); - this.resInterceptor(); - } - - if ( StoreClass ) HttpClass.__proto__ = StoreClass; - HttpClass.prototype = Object.create( StoreClass && StoreClass.prototype ); - HttpClass.prototype.constructor = HttpClass; - - var prototypeAccessors = { headers: { configurable: true } }; - - // set headers for that one call - prototypeAccessors.headers.set = function (header) { - this.extraHeader = header; - }; - - /** - * Create the reusage request method - * @param {object} payload jsonql payload - * @param {object} options extra options add the request - * @param {object} headers extra headers add to the call - * @return {object} the fly request instance - */ - HttpClass.prototype.request = function request (payload, options, headers) { - var obj; - - if ( options === void 0 ) options = {}; - if ( headers === void 0 ) headers = {}; - this.headers = headers; - var params = merge({}, cacheBurst(), this.extraParams); - // @TODO need to add a jsonp url and payload - if (this.opts.enableJsonp) { - var resolverName = getNameFromPayload(payload); - params = merge({}, params, ( obj = {}, obj[JSONP_CALLBACK_NAME] = resolverName, obj )); - payload = payload[resolverName]; - } - // double up the url param and see what happen @TODO remove later - var reqParams = merge({}, { method: POST, params: params }, options); - this.log('request params', reqParams, this.jsonqlEndpoint); - - return this.fly.request(this.jsonqlEndpoint, payload, reqParams) - }; - - /** - * This will replace the create baseRequest method - * - */ - HttpClass.prototype.reqInterceptor = function reqInterceptor () { - var this$1 = this; - - this.fly.interceptors.request.use( - function (req) { - var headers = this$1.getHeaders(); - this$1.log('request interceptor call', headers); - - for (var key in headers) { - req.headers[key] = headers[key]; - } - return req; - } - ); - }; - - // @TODO - HttpClass.prototype.processJsonp = function processJsonp (result) { - return resultHandler(result) - }; - - /** - * This will be replacement of the first then call - * - */ - HttpClass.prototype.resInterceptor = function resInterceptor () { - var this$1 = this; - - var self = this; - var jsonp = self.opts.enableJsonp; - this.fly.interceptors.response.use( - function (res) { - this$1.log('response interceptor call', res); - self.cleanUp(); - // now more processing here - // there is a problem if we throw the result.error here - // the original data is lost, so we need to do what we did before - // deal with that error in the first then instead - var result = isString$1(res.data) ? JSON.parse(res.data) : res.data; - if (jsonp) { - return self.processJsonp(result) - } - return resultHandler(result) - }, - // this get call when it's not 200 - function (err) { - self.cleanUp(); - console.error(err); - throw new JsonqlServerError('Server side error', err) - } - ); - }; - - /** - * Get the headers inject into the call - * @return {object} headers - */ - HttpClass.prototype.getHeaders = function getHeaders () { - if (this.opts.enableAuth) { - return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader) - } - return merge({}, DEFAULT_HEADER, this.extraHeader) - }; - - /** - * Post http call operation to clean up things we need - */ - HttpClass.prototype.cleanUp = function cleanUp () { - this.extraHeader = {}; - this.extraParams = {}; - }; - - /** - * GET for contract only - * @return {promise} resolve the contract - */ - HttpClass.prototype.getRemoteContract = function getRemoteContract () { - var this$1 = this; - - if (this.opts.showContractDesc) { - this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM); - } - return this.request({}, {method: 'GET'}, this.contractHeader) - .then(clientErrorsHandler$1) - .then(function (result) { - this$1.log('get contract result', result); - // when refresh the window the result is different! - // @TODO need to check the Koa side about why is that - // also it should set a flag if we want the description or not - if (result.cache && result.contract) { - return result.contract; - } - // just the normal result - return result - }) - .catch(function (err) { - console.error('getRemoteContract err', err); - throw new JsonqlServerError('getRemoteContract', err) - }) - }; - - /** - * POST to server - query - * @param {object} name of the resolver - * @param {array} args arguments - * @return {object} promise resolve to the resolver return - */ - HttpClass.prototype.query = function query (name, args) { - if ( args === void 0 ) args = []; - - return this.request(createQuery(name, args)) - .then(clientErrorsHandler$1) - }; - - /** - * PUT to server - mutation - * @param {string} name of resolver - * @param {object} payload what it said - * @param {object} conditions what it said - * @return {object} promise resolve to the resolver return - */ - HttpClass.prototype.mutation = function mutation (name, payload, conditions) { - if ( payload === void 0 ) payload = {}; - if ( conditions === void 0 ) conditions = {}; - - return this.request(createMutation(name, payload, conditions), {method: PUT}) - .then(clientErrorsHandler$1) - }; - - Object.defineProperties( HttpClass.prototype, prototypeAccessors ); - - return HttpClass; - }(StoreClass)); - - // all the contract related methods will be here - - // export - var ContractClass = /*@__PURE__*/(function (HttpClass) { - function ContractClass(opts) { - HttpClass.call(this, opts); - } - - if ( HttpClass ) ContractClass.__proto__ = HttpClass; - ContractClass.prototype = Object.create( HttpClass && HttpClass.prototype ); - ContractClass.prototype.constructor = ContractClass; - - var prototypeAccessors = { contractHeader: { configurable: true } }; - - /** - * return the contract public api - * @return {object} contract - */ - ContractClass.prototype.getContract = function getContract () { - var contract = this.readContract(); - this.log('getContract first call', contract); - return contract ? Promise.resolve(contract) - : this.getRemoteContract().then(this.storeContract.bind(this)) - }; - - /** - * We are changing the way how to auth to get the contract.json - * Instead of in the url, we will be putting that key value in the header - * @return {object} header - */ - prototypeAccessors.contractHeader.get = function () { - var base = {}; - if (this.opts.contractKey !== false) { - base[this.opts.contractKeyName] = this.opts.contractKey; - } - return base; - }; - - /** - * Save the contract to local store - * @param {object} contract to save - * @return {object|boolean} false when its not a contract or contract on OK - */ - ContractClass.prototype.storeContract = function storeContract (contract) { - var obj; - - // first need to check if the contract is a contract - if (!isContract(contract)) { - throw new JsonqlValidationError("Contract is malformed!") - //return false; - } - /* @TODO need to rethink how to expired the contract - let args = [contract] - if (this.opts.contractExpired) { - let expired = parseFloat(this.opts.contractExpired) - if (!isNaN(expired) && expired > 0) { - args.push(expired) - } - } - // calling the setter - this.jsonqlContract = args; - */ - this.lset = ( obj = {}, obj[CLS_CONTRACT_NAME] = contract, obj ); - // return it - this.log('storeContract return result', contract); - return contract; - }; - - /** - * return the contract from options or localStore - * @return {object|boolean} false on not found - */ - ContractClass.prototype.readContract = function readContract () { - var contract = isContract(this.opts.contract); - if (contract !== false) { - return contract; - } - var data = this.lget; - if (data) { - return data[CLS_CONTRACT_NAME] - } - return false; - }; - - Object.defineProperties( ContractClass.prototype, prototypeAccessors ); - - return ContractClass; - }(HttpClass)); - - // this is the new auth class that integrate with the jsonql-jwt - // export - var AuthClass = /*@__PURE__*/(function (ContractClass) { - function AuthClass(opts) { - ContractClass.call(this, opts); - if (opts.enableAuth) { - this.setDecoder = jwtDecode; - } - } - - if ( ContractClass ) AuthClass.__proto__ = ContractClass; - AuthClass.prototype = Object.create( ContractClass && ContractClass.prototype ); - AuthClass.prototype.constructor = AuthClass; - - var prototypeAccessors = { profileIndex: { configurable: true },setDecoder: { configurable: true },saveProfile: { configurable: true },readProfile: { configurable: true },jsonqlToken: { configurable: true },jsonqlUserdata: { configurable: true } }; - - /** - * for overwrite - * @param {string} token stored token - * @return {string} token - */ - AuthClass.prototype.decoder = function decoder (token) { - return token; - }; - - /** - * set the profile index - * @param {number} idx - */ - prototypeAccessors.profileIndex.set = function (idx) { - var obj; - - var key = CLS_PROFILE_IDX; - if (isNumber$1(idx)) { - this[key] = idx; - if (this.opts.persistToken) { - this.lset = ( obj = {}, obj[key] = idx, obj ); - } - return; - } - throw new JsonqlValidationError('profileIndex', ("Expect idx to be number but got " + (typeof idx))) - }; - - /** - * get the profile index - * @return {number} idx - */ - prototypeAccessors.profileIndex.get = function () { - var key = CLS_PROFILE_IDX; - if (this.opts.persistToken) { - var data = this.lget; - if (data[key]) { - return data[key] - } - } - return this[key] ? this[key] : ZERO_IDX - }; - - /** - * Return the token from session store - * @param {number} [idx=false] profile index - * @return {string} token - */ - AuthClass.prototype.rawAuthToken = function rawAuthToken (idx) { - if ( idx === void 0 ) idx = false; - - if (idx !== false) { - this.profileIndex = idx; - } - // this should return from the base - return this.jsonqlToken; // see base-cls - }; - - /** - * Setter to add a decoder when retrieve user token - * @param {function} d a decoder - */ - prototypeAccessors.setDecoder.set = function (d) { - if (typeof d === 'function') { - this.decoder = d; - } - }; - - /** - * getter to return the session or local store set method - * @param {*} data to save - * @return {object} set method - */ - prototypeAccessors.saveProfile.set = function (data) { - if (this.opts.persistToken) { - // this.log('--- saveProfile lset ---', data) - this.lset = data; - } else { - // this.log('--- saveProfile sset ---', data) - this.sset = data; - } - }; - - /** - * getter to return the session or local store get method - * @return {object} get method - */ - prototypeAccessors.readProfile.get = function () { - return this.opts.persistToken ? this.lget : this.sget - }; - - // these were in the base class before but it should be here - /** - * save token - * @param {string} token to store - * @return {string|boolean} false on failed - */ - prototypeAccessors.jsonqlToken.set = function (token) { - var obj; - - var data = this.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - // @TODO also have to make sure the token is not already existed! - var tokens = (data && data[key]) ? data[key] : []; - tokens.push(token); - this.saveProfile = ( obj = {}, obj[key] = tokens, obj ); - // store the userdata - this.jsonqlUserdata = this.decoder(token); - }; - - /** - * Jsonql token getter - * 1.5.1 each token associate with the same profileIndex - * @return {string|boolean} false when failed - */ - prototypeAccessors.jsonqlToken.get = function () { - var data = this.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - if (data && data[key]) { - this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex]); - return data[key][this.profileIndex] - } - return false - }; - - /** - * this one will use the sessionStore - * basically we hook this onto the token store and decode it to store here - * we only store one decoded user data at a time, but the token can be multiple - */ - prototypeAccessors.jsonqlUserdata.set = function (userdata) { - var obj; - - this.sset = ( obj = {}, obj[USERDATA_TABLE] = userdata, obj ); - }; - - /** - * this one store in the session store - * get login userdata decoded jwt - * 1.5.1 each userdata associate with the same profileIndex - * @return {object|null} - */ - prototypeAccessors.jsonqlUserdata.get = function () { - var data = this.sget; - return data ? data[USERDATA_TABLE] : false - }; - - /** - * Construct the auth header - * @return {object} header - */ - AuthClass.prototype.getAuthHeader = function getAuthHeader () { - var obj; - - var token = this.jsonqlToken; // only call the getter to get the default one - return token ? ( obj = {}, obj[this.opts.AUTH_HEADER] = (BEARER + " " + token), obj ) : {}; - }; - - /** - * return all the stored token and decode it - * @param {number} [idx=false] profile index - * @return {array|boolean|string} false not found or array - */ - AuthClass.prototype.getProfiles = function getProfiles (idx) { - if ( idx === void 0 ) idx = false; - - var self = this; // just in case the scope problem - var data = self.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - if (data && data[key]) { - if (idx !== false && isNumber$1(idx)) { - return data[key][idx] || false - } - return data[key].map(self.decoder.bind(self)) - } - return false - }; - - /** - * call after the login - * @param {string} token return from server - * @return {object} decoded token to userdata object - */ - AuthClass.prototype.postLoginAction = function postLoginAction (token) { - this.jsonqlToken = token; - return token - }; - - /** - * call after the logout @TODO - */ - AuthClass.prototype.postLogoutAction = function postLogoutAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - console.info("postLogoutAction", args); - }; - - Object.defineProperties( AuthClass.prototype, prototypeAccessors ); - - return AuthClass; - }(ContractClass)); - - // this the core of the internal storage management - - // This class will only focus on the storage system - var JsonqlBaseClient = /*@__PURE__*/(function (AuthCls) { - function JsonqlBaseClient(fly, opts) { - // change at 1.4.10 pass it directly without init it - this.fly = fly; - AuthCls.call(this, opts); - } - - if ( AuthCls ) JsonqlBaseClient.__proto__ = AuthCls; - JsonqlBaseClient.prototype = Object.create( AuthCls && AuthCls.prototype ); - JsonqlBaseClient.prototype.constructor = JsonqlBaseClient; - - var prototypeAccessors = { jsonqlEndpoint: { configurable: true } }; - - /** - * construct the end point - * @return {string} the end point to call - */ - prototypeAccessors.jsonqlEndpoint.get = function () { - var baseUrl = this.opts.hostname || ''; - return [baseUrl, this.opts.jsonqlPath].join('/') - }; - - /** - * simple log - */ - JsonqlBaseClient.prototype.log = function log () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - if (this.opts.debugOn === true) { - Reflect.apply(console.info, console, args); - } - }; - - Object.defineProperties( JsonqlBaseClient.prototype, prototypeAccessors ); - - return JsonqlBaseClient; - }(AuthClass)); - - // export interface - - /** - * using just the map reduce to chain multiple functions together - * @param {function} mainFn the init function - * @param {array} moreFns as many as you want to take the last value and return a new one - * @return {function} accept value for the mainFn - */ - var chainFns = function (mainFn) { - var moreFns = [], len = arguments.length - 1; - while ( len-- > 0 ) moreFns[ len ] = arguments[ len + 1 ]; - - return ( - function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return ( - moreFns.reduce(function (value, nextFn) { return ( - // change here to check if the return value is array then we spread it - Reflect.apply(nextFn, null, toArray(value)) - ); }, Reflect.apply(mainFn, null, args)) - ); - } - ); - }; - - /** - * check if the object has name property - * @param {object} obj the object to check - * @param {string} name the prop name - * @return {*} the value or undefined - */ - function objHasProp(obj, name) { - var prop = Object.getOwnPropertyDescriptor(obj, name); - return prop !== undefined && prop.value ? prop.value : prop; - } - - /** - * 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 {string} name the name of the object to get inject also for checking - * @param {object} data to inject into the function static interface - * @param {boolean} [overwrite=false] if we want to overwrite the existing data - * @return {function} added property resolver - */ - function injectToFn(resolver, name, data, overwrite) { - if ( overwrite === void 0 ) overwrite = false; - - var check = objHasProp(resolver, name); - if (overwrite === false && check !== undefined) { - // console.info(`NOT INJECTED`) - return resolver; - } - /* this will throw error! - if (overwrite === true && check !== undefined) { - delete resolver[name] // delete this property - } - */ - // console.info(`INJECTED`) - Object.defineProperty(resolver, name, { - value: data, - writable: overwrite // if its set to true then we should able to overwrite it - }); - - return resolver; - } - - // breaking out the inner methods generator in here - - /** - * generate authorisation specific methods - * @param {object} jsonqlInstance instance of this - * @param {string} name of method - * @param {object} opts configuration - * @param {object} contract to match - * @return {function} for use - */ - var authMethodGenerator = function (jsonqlInstance, name, opts, contract) { - return function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var params = contract.auth[name].params; - var values = params.map(function (p, i) { return args[i]; }); - var header = args[params.length] || {}; - return validateAsync$1(args, params) - .then(function () { return jsonqlInstance - .query - .apply(jsonqlInstance, [name, values, header]); } - ) - .catch(finalCatch) - } - }; - - /** - * Break up the different type each - create query methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createQueryMethods = function (obj, jsonqlInstance, ee, config, contract) { - var query = {}; - var loop = function ( queryFn ) { - // to keep it clean we use a param to id the auth method - // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; - // generate the query method - query = injectToFn(query, queryFn, function queryFnHandler() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var params = contract.query[queryFn].params; - var _args = params.map(function (param, i) { return args[i]; }); - // debug('query', queryFn, _params); - // @TODO this need to change to a different way to add an extra header - var header = {}; - // @TODO validate against the type - return validateAsync$1(_args, params) - .then(function () { return jsonqlInstance - .query - .apply(jsonqlInstance, [queryFn, _args, header]); } - ) - .catch(finalCatch) - }); - }; - - for (var queryFn in contract.query) loop( queryFn ); - obj.query = query; - // create an alias to the helloWorld method - obj.helloWorld = query.helloWorld; - return [ obj, jsonqlInstance, ee, config, contract ] - }; - - /** - * create mutation methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createMutationMethods = function (obj, jsonqlInstance, ee, config, contract) { - var mutation = {}; - // process the mutation, the reason the mutation has a fixed number of parameters - // there is only the payload, and conditions parameters - // plus a header at the end - var loop = function ( mutationFn ) { - mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header) { - if ( header === void 0 ) header = {}; - - var args = [payload, conditions]; - var params = contract.mutation[mutationFn].params; - return validateAsync$1(args, params) - .then(function () { return jsonqlInstance - .mutation - .apply(jsonqlInstance, [mutationFn, payload, conditions, header]); } - ) - .catch(function (e) { - console.error('--- mutation fn catch ---', e); - return finalCatch(e) - }) - }); - }; - - for (var mutationFn in contract.mutation) loop( mutationFn ); - obj.mutation = mutation; - return [ obj, jsonqlInstance, ee, config, contract ] - }; - - /** - * create auth methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createAuthMethods = function (obj, jsonqlInstance, ee, config, contract) { - if (config.enableAuth && contract.auth) { - var auth = {}; // v1.3.1 add back the auth prop name in contract - var loginHandlerName = config.loginHandlerName; - var logoutHandlerName = config.logoutHandlerName; - if (contract.auth[loginHandlerName]) { - // changing to the name the config specify - auth[loginHandlerName] = function loginHandlerFn() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract); - return fn.apply(null, args) - .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance)) - .then(function (token) { - ee.$trigger(LOGIN_NAME, token); - return token; - }) - }; - } - // @TODO allow to logout one particular profile or all of them - if (contract.auth[logoutHandlerName]) { - auth[logoutHandlerName] = function logoutHandlerFn() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract); - return fn.apply(null, args) - .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance)) - .then(function (r) { - ee.$trigger(LOGOUT_NAME, r); - return r; - }) - }; - } else { - auth[logoutHandlerName] = function logoutHandlerFn() { - jsonqlInstance.postLogoutAction(KEY_WORD); - ee.$trigger(LOGOUT_NAME, KEY_WORD); - }; - } - obj.auth = auth; - } - - return obj; - }; - - /** - * Here just generate the methods calls - * @param {object} jsonqlInstance what it said - * @param {object} ee event emitter - * @param {object} config configuration - * @param {object} contract the map - * @return {object} with mapped methods - */ - function methodsGenerator(jsonqlInstance, ee, config, contract) { - var obj = {}; - var executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods); - return executor(obj, jsonqlInstance, ee, config, contract) - } - - // Generate the resolver for developer to use - - /** - * @param {object} jsonqlInstance jsonql class instance - * @param {object} config options - * @param {object} contract the contract - * @param {object} ee eventEmitter - * @return {object} constructed functions call - */ - var generator = function (jsonqlInstance, config, contract, ee) { - // V1.3.0 - now everything wrap inside this method - var client = methodsGenerator(jsonqlInstance, ee, config, contract); - // create the rest of the methods - if (config.enableAuth) { - /** - * new method to allow retrieve the current login user data - * @TODO allow to pass an id to switch to different userdata - * @return {*} userdata - */ - client.userdata = function () { return jsonqlInstance.jsonqlUserdata; }; - // allow getting the token for valdiate agains the socket - // if it's not require auth there is no point of calling getToken - client.getToken = function (idx) { - if ( idx === void 0 ) idx = false; - - return jsonqlInstance.rawAuthToken(idx); - }; - // switch profile or read back what is the currenct index - client.profileIndex = function (idx) { - if ( idx === void 0 ) idx = false; - - if (idx === false) { - return jsonqlInstance.profileIndex - } - jsonqlInstance.profileIndex = idx; - }; - // new in 1.5.1 to return different profiles - client.getProfiles = function (idx) { - if ( idx === void 0 ) idx = false; - - return jsonqlInstance.getProfiles(idx); - }; - } - // this will pass to the ws-client if needed - // client.eventEmitter = ee; - // this will require a param - if (config.exposeContract) { - // 1.4.0 change from the get (raw) to the getContract cache and raw version - client.getContract = function () { return jsonqlInstance.getContract(); }; - } - // allow developer to access the store api - if (config.exposeStore) { - // @TODO in 1.5.2 - client.tmpSave = function (data) {}; - client.tmpGet = function (key) { - }; - client.tmpDel = function (key) { - }; - - client.persistSave = function (data) {}; - client.persistGet = function (key) { - }; - client.persistDel = function (key) { - }; - } - // this is for the ws to use later - but this could be dangerous because it's expose the internal - client.eventEmitter = ee; - client.version = '1.5.1'; - // use this method then we can hook into the debugOn at the same time - client.log = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return Reflect.apply(jsonqlInstance.log, jsonqlInstance, ['[DEV DEBUG]'].concat(args)); - }; - // output - return client; - }; - - // all the client configuration options here - var constProps = { - contract: false, - MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong? - CONTENT_TYPE: CONTENT_TYPE, - BEARER: BEARER, - AUTH_HEADER: AUTH_HEADER - }; - - // grab the localhost name and put into the hostname as default - var getHostName = function () { - try { - return [window.location.protocol, window.location.host].join('//') - } catch(e) { - return null - } - }; - - var appProps$1 = { - - hostname: createConfig$1(getHostName(), [STRING_TYPE]), // required the hostname - jsonqlPath: createConfig$1(JSONQL_PATH, [STRING_TYPE]), // The path on the server - - loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), - logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), - // add to koa v1.3.0 - this might remove in the future - enableJsonp: createConfig$1(false, [BOOLEAN_TYPE]), - enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), - // enable useJwt by default @TODO replace with something else and remove them later - useJwt: createConfig$1(true, [BOOLEAN_TYPE]), - // when true then store infinity or pass a time in seconds then we check against - // the token date of creation - persistToken: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE]), - // the header - // v1.2.0 we are using this option during the dev - // so it won't save anything to the localstorage and fetch a new contract - // whenever the browser reload - useLocalstorage: createConfig$1(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage - storageKey: createConfig$1(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage - authKey: createConfig$1(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage - contractExpired: createConfig$1(0, [NUMBER_TYPE]),// -1 always fetch contract, - // 0 never expired, - // > 0 then compare the timestamp with the current one to see if we need to get contract again - // useful during development - keepContract: createConfig$1(true, [BOOLEAN_TYPE]), - exposeContract: createConfig$1(false, [BOOLEAN_TYPE]), - exposeStore: createConfig$1(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn - // @1.2.1 new option for the contract-console to fetch the contract with description - showContractDesc: createConfig$1(false, [BOOLEAN_TYPE]), - contractKey: createConfig$1(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this - contractKeyName: createConfig$1(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs - enableTimeout: createConfig$1(false, [BOOLEAN_TYPE]), // @TODO - timeout: createConfig$1(5000, [NUMBER_TYPE]), // 5 seconds - returnInstance: createConfig$1(false, [BOOLEAN_TYPE]), - allowReturnRawToken: createConfig$1(false, [BOOLEAN_TYPE]), - debugOn: createConfig$1(false, [BOOLEAN_TYPE]) - }; - - // we must ensure the user passing the correct options - - function checkOptionsAsync$1(config) { - var contract = config.contract; - return checkConfigAsync$1(config, appProps$1, constProps) - .then(function (opts) { - opts.contract = contract; - return opts; - }) - } - - // export interface - /** - * 1.5.0 overload the orginal functions to pass over the check - */ - function checkOptionsAsync$2(config) { - return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsync$1(config) - } - - // this is new for the flyio and normalize the name from now on - - /** - * Main interface for jsonql fetch api - * @param {object} ee EventEmitter - * @param {object} config - * @param {object} fly this is really pain in the backside ... long story - * @return {object} jsonql client - */ - function jsonqlAsync(ee, config, fly) { - if ( config === void 0 ) config = {}; - - return checkOptionsAsync$2(config) - .then(function (opts) { return ( - { - baseClient: new JsonqlBaseClient(fly, opts), - opts: opts - } - ); }) - .then( function (ref) { - var baseClient = ref.baseClient; - var opts = ref.opts; - - return ( - getContractFromConfig(baseClient, opts.contract) - .then(function (contract) { return generator(baseClient, opts, contract, ee); }) - ); - } - ) - } - - var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); - var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); - - // making all the functionality on it's own - // import { WatchClass } from './watch' - - var SuspendClass = function SuspendClass() { - // suspend, release and queue - this.__suspend__ = null; - this.queueStore = new Set(); - /* - this.watch('suspend', function(value, prop, oldValue) { - this.logger(`${prop} set from ${oldValue} to ${value}`) - // it means it set the suspend = true then release it - if (oldValue === true && value === false) { - // we want this happen after the return happens - setTimeout(() => { - this.release() - }, 1) - } - return value; // we need to return the value to store it - }) - */ - }; - - var prototypeAccessors$1 = { $suspend: { configurable: true },$queues: { configurable: true } }; - - /** - * setter to set the suspend and check if it's boolean value - * @param {boolean} value to trigger - */ - prototypeAccessors$1.$suspend.set = function (value) { - var this$1 = this; - - if (typeof value === 'boolean') { - var lastValue = this.__suspend__; - this.__suspend__ = value; - this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); - if (lastValue === true && value === false) { - setTimeout(function () { - this$1.release(); - }, 1); - } - } else { - throw new Error("$suspend only accept Boolean value!") - } - }; - - /** - * queuing call up when it's in suspend mode - * @param {any} value - * @return {Boolean} true when added or false when it's not - */ - SuspendClass.prototype.$queue = function $queue () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - if (this.__suspend__ === true) { - this.logger('($queue)', 'added to $queue', args); - // there shouldn't be any duplicate ... - this.queueStore.add(args); - } - return this.__suspend__; - }; - - /** - * a getter to get all the store queue - * @return {array} Set turn into Array before return - */ - prototypeAccessors$1.$queues.get = function () { - var size = this.queueStore.size; - this.logger('($queues)', ("size: " + size)); - if (size > 0) { - return Array.from(this.queueStore) - } - return [] - }; - - /** - * Release the queue - * @return {int} size if any - */ - SuspendClass.prototype.release = function release () { - var this$1 = this; - - var size = this.queueStore.size; - this.logger('(release)', ("Release was called " + size)); - if (size > 0) { - var queue = Array.from(this.queueStore); - this.queueStore.clear(); - this.logger('queue', queue); - queue.forEach(function (args) { - this$1.logger(args); - Reflect.apply(this$1.$trigger, this$1, args); - }); - this.logger(("Release size " + (this.queueStore.size))); - } - }; - - Object.defineProperties( SuspendClass.prototype, prototypeAccessors$1 ); - - // break up the main file because its getting way too long - - var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { - function NbEventServiceBase(config) { - if ( config === void 0 ) config = {}; - - SuspendClass.call(this); - if (config.logger && typeof config.logger === 'function') { - this.logger = config.logger; - } - this.keep = config.keep; - // for the $done setter - this.result = config.keep ? [] : null; - // we need to init the store first otherwise it could be a lot of checking later - this.normalStore = new Map(); - this.lazyStore = new Map(); - } - - if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; - NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); - NbEventServiceBase.prototype.constructor = NbEventServiceBase; - - var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; - - /** - * validate the event name(s) - * @param {string[]} evt event name - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validateEvt = function validateEvt () { - var this$1 = this; - var evt = [], len = arguments.length; - while ( len-- ) evt[ len ] = arguments[ len ]; - - evt.forEach(function (e) { - if (typeof e !== 'string') { - this$1.logger('(validateEvt)', e); - throw new Error("event name must be string type!") - } - }); - return true; - }; - - /** - * Simple quick check on the two main parameters - * @param {string} evt event name - * @param {function} callback function to call - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validate = function validate (evt, callback) { - if (this.validateEvt(evt)) { - if (typeof callback === 'function') { - return true; - } - } - throw new Error("callback required to be function type!") - }; - - /** - * Check if this type is correct or not added in V1.5.0 - * @param {string} type for checking - * @return {boolean} true on OK - */ - NbEventServiceBase.prototype.validateType = function validateType (type) { - var types = ['on', 'only', 'once', 'onlyOnce']; - return !!types.filter(function (t) { return type === t; }).length; - }; - - /** - * Run the callback - * @param {function} callback function to execute - * @param {array} payload for callback - * @param {object} ctx context or null - * @return {void} the result store in $done - */ - NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { - this.logger('(run)', callback, payload, ctx); - this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); - }; - - /** - * Take the content out and remove it from store id by the name - * @param {string} evt event name - * @param {string} [storeName = lazyStore] name of store - * @return {object|boolean} content or false on not found - */ - NbEventServiceBase.prototype.takeFromStore = function takeFromStore (evt, storeName) { - if ( storeName === void 0 ) storeName = 'lazyStore'; - - var store = this[storeName]; // it could be empty at this point - if (store) { - this.logger('(takeFromStore)', storeName, store); - if (store.has(evt)) { - var content = store.get(evt); - this.logger('(takeFromStore)', ("has " + evt), content); - store.delete(evt); - return content; - } - return false; - } - throw new Error((storeName + " is not supported!")) - }; - - /** - * The add to store step is similar so make it generic for resuse - * @param {object} store which store to use - * @param {string} evt event name - * @param {spread} args because the lazy store and normal store store different things - * @return {array} store and the size of the store - */ - NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { - var args = [], len = arguments.length - 2; - while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; - - var fnSet; - if (store.has(evt)) { - this.logger('(addToStore)', (evt + " existed")); - fnSet = store.get(evt); - } else { - this.logger('(addToStore)', ("create new Set for " + evt)); - // this is new - fnSet = new Set(); - } - // lazy only store 2 items - this is not the case in V1.6.0 anymore - // we need to check the first parameter is string or not - if (args.length > 2) { - if (Array.isArray(args[0])) { // lazy store - // check if this type of this event already register in the lazy store - var t = args[2]; - if (!this.checkTypeInLazyStore(evt, t)) { - fnSet.add(args); - } - } else { - if (!this.checkContentExist(args, fnSet)) { - this.logger('(addToStore)', "insert new", args); - fnSet.add(args); - } - } - } else { // add straight to lazy store - fnSet.add(args); - } - store.set(evt, fnSet); - return [store, fnSet.size] - }; - - /** - * @param {array} args for compare - * @param {object} fnSet A Set to search from - * @return {boolean} true on exist - */ - NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { - var list = Array.from(fnSet); - return !!list.filter(function (l) { - var hash = l[0]; - if (hash === args[0]) { - return true; - } - return false; - }).length; - }; - - /** - * get the existing type to make sure no mix type add to the same store - * @param {string} evtName event name - * @param {string} type the type to check - * @return {boolean} true you can add, false then you can't add this type - */ - NbEventServiceBase.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { - this.validateEvt(evtName, type); - var all = this.$get(evtName, true); - if (all === false) { - // pristine it means you can add - return true; - } - // it should only have ONE type in ONE event store - return !all.filter(function (list) { - var t = list[3]; - return type !== t; - }).length; - }; - - /** - * This is checking just the lazy store because the structure is different - * therefore we need to use a new method to check it - */ - NbEventServiceBase.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { - this.validateEvt(evtName, type); - var store = this.lazyStore.get(evtName); - this.logger('(checkTypeInLazyStore)', store); - if (store) { - return !!Array - .from(store) - .filter(function (l) { - var t = l[2]; - return t !== type; - }).length - } - return false; - }; - - /** - * wrapper to re-use the addToStore, - * V1.3.0 add extra check to see if this type can add to this evt - * @param {string} evt event name - * @param {string} type on or once - * @param {function} callback function - * @param {object} context the context the function execute in or null - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { - if ( context === void 0 ) context = null; - - this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); - // @TODO we need to check the existing store for the type first! - if (this.checkTypeInStore(evt, type)) { - this.logger('(addToNormalStore)', (type + " can add to " + evt + " normal store")); - var key = this.hashFnToKey(callback); - var args = [this.normalStore, evt, key, callback, context, type]; - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.normalStore = _store; - return size; - } - return false; - }; - - /** - * Add to lazy store this get calls when the callback is not register yet - * so we only get a payload object or even nothing - * @param {string} evt event name - * @param {array} payload of arguments or empty if there is none - * @param {object} [context=null] the context the callback execute in - * @param {string} [type=false] register a type so no other type can add to this evt - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - // this is add in V1.6.0 - // when there is type then we will need to check if this already added in lazy store - // and no other type can add to this lazy store - var args = [this.lazyStore, evt, this.toArray(payload), context]; - if (type) { - args.push(type); - } - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.lazyStore = _store; - return size; - }; - - /** - * make sure we store the argument correctly - * @param {*} arg could be array - * @return {array} make sured - */ - NbEventServiceBase.prototype.toArray = function toArray (arg) { - return Array.isArray(arg) ? arg : [arg]; - }; - - /** - * setter to store the Set in private - * @param {object} obj a Set - */ - prototypeAccessors.normalStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); - }; - - /** - * @return {object} Set object - */ - prototypeAccessors.normalStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) - }; - - /** - * setter to store the Set in lazy store - * @param {object} obj a Set - */ - prototypeAccessors.lazyStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); - }; - - /** - * @return {object} the lazy store Set - */ - prototypeAccessors.lazyStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) - }; - - /** - * generate a hashKey to identify the function call - * The build-in store some how could store the same values! - * @param {function} fn the converted to string function - * @return {string} hashKey - */ - NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { - return hashCode(fn.toString()) + ''; - }; - - Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); - - return NbEventServiceBase; - }(SuspendClass)); - - // The top level - // export - var EventService = /*@__PURE__*/(function (NbStoreService) { - function EventService(config) { - if ( config === void 0 ) config = {}; - - NbStoreService.call(this, config); - } - - if ( NbStoreService ) EventService.__proto__ = NbStoreService; - EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); - EventService.prototype.constructor = EventService; - - var prototypeAccessors = { $done: { configurable: true } }; - - /** - * logger function for overwrite - */ - EventService.prototype.logger = function logger () {}; - - ////////////////////////// - // PUBLIC METHODS // - ////////////////////////// - - /** - * Register your evt handler, note we don't check the type here, - * we expect you to be sensible and know what you are doing. - * @param {string} evt name of event - * @param {function} callback bind method --> if it's array or not - * @param {object} [context=null] to execute this call in - * @return {number} the size of the store - */ - EventService.prototype.$on = function $on (evt , callback , context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - var type = 'on'; - this.validate(evt, callback); - // first need to check if this evt is in lazy store - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register first then call later - if (lazyStoreContent === false) { - this.logger('($on)', (evt + " callback is not in lazy store")); - // @TODO we need to check if there was other listener to this - // event and are they the same type then we could solve that - // register the different type to the same event name - - return this.addToNormalStore(evt, type, callback, context) - } - this.logger('($on)', (evt + " found in lazy store")); - // this is when they call $trigger before register this callback - var size = 0; - lazyStoreContent.forEach(function (content) { - var payload = content[0]; - var ctx = content[1]; - var t = content[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.logger("($on)", ("call run on " + evt)); - this$1.run(callback, payload, context || ctx); - size += this$1.addToNormalStore(evt, type, callback, context || ctx); - }); - return size; - }; - - /** - * once only registered it once, there is no overwrite option here - * @NOTE change in v1.3.0 $once can add multiple listeners - * but once the event fired, it will remove this event (see $only) - * @param {string} evt name - * @param {function} callback to execute - * @param {object} [context=null] the handler execute in - * @return {boolean} result - */ - EventService.prototype.$once = function $once (evt , callback , context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'once'; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (lazyStoreContent === false) { - this.logger('($once)', (evt + " not in the lazy store")); - // v1.3.0 $once now allow to add multiple listeners - return this.addToNormalStore(evt, type, callback, context) - } else { - // now this is the tricky bit - // there is a potential bug here that cause by the developer - // if they call $trigger first, the lazy won't know it's a once call - // so if in the middle they register any call with the same evt name - // then this $once call will be fucked - add this to the documentation - this.logger('($once)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.logger('($once)', ("call run for " + evt)); - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - }; - - /** - * This one event can only bind one callbackback - * @param {string} evt event name - * @param {function} callback event handler - * @param {object} [context=null] the context the event handler execute in - * @return {boolean} true bind for first time, false already existed - */ - EventService.prototype.$only = function $only (evt, callback, context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'only'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($only)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($only)', (evt + " found data in lazy store to execute")); - var list = Array.from(lazyStoreContent); - // $only allow to trigger this multiple time on the single handler - list.forEach( function (l) { - var payload = l[0]; - var ctx = l[1]; - var t = l[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.logger("($only)", ("call run for " + evt)); - this$1.run(callback, payload, context || ctx); - }); - } - return added; - }; - - /** - * $only + $once this is because I found a very subtile bug when we pass a - * resolver, rejecter - and it never fire because that's OLD added in v1.4.0 - * @param {string} evt event name - * @param {function} callback to call later - * @param {object} [context=null] exeucte context - * @return {void} - */ - EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'onlyOnce'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($onlyOnce)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($onlyOnce)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== 'onlyOnce') { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.logger("($onlyOnce)", ("call run for " + evt)); - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - return added; - }; - - /** - * This is a shorthand of $off + $on added in V1.5.0 - * @param {string} evt event name - * @param {function} callback to exeucte - * @param {object} [context = null] or pass a string as type - * @param {string} [type=on] what type of method to replace - * @return {} - */ - EventService.prototype.$replace = function $replace (evt, callback, context, type) { - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = 'on'; - - if (this.validateType(type)) { - this.$off(evt); - var method = this['$' + type]; - this.logger("($replace)", evt, callback); - return Reflect.apply(method, this, [evt, callback, context]) - } - throw new Error((type + " is not supported!")) - }; - - /** - * trigger the event - * @param {string} evt name NOT allow array anymore! - * @param {mixed} [payload = []] pass to fn - * @param {object|string} [context = null] overwrite what stored - * @param {string} [type=false] if pass this then we need to add type to store too - * @return {number} if it has been execute how many times - */ - EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - this.validateEvt(evt); - var found = 0; - // first check the normal store - var nStore = this.normalStore; - this.logger('($trigger)', 'normalStore', nStore); - if (nStore.has(evt)) { - // @1.8.0 to add the suspend queue - var added = this.$queue(evt, payload, context, type); - this.logger('($trigger)', evt, 'found; add to queue: ', added); - if (added === true) { - this.logger('($trigger)', evt, 'not executed. Exit now.'); - return false; // not executed - } - var nSet = Array.from(nStore.get(evt)); - var ctn = nSet.length; - var hasOnce = false; - for (var i=0; i < ctn; ++i) { - ++found; - // this.logger('found', found) - var ref = nSet[i]; - var _ = ref[0]; - var callback = ref[1]; - var ctx = ref[2]; - var type$1 = ref[3]; - this.logger("($trigger)", ("call run for " + evt)); - this.run(callback, payload, context || ctx); - if (type$1 === 'once' || type$1 === 'onlyOnce') { - hasOnce = true; - } - } - if (hasOnce) { - nStore.delete(evt); - } - return found; - } - // now this is not register yet - this.addToLazyStore(evt, payload, context, type); - return found; - }; - - /** - * this is an alias to the $trigger - * @NOTE breaking change in V1.6.0 we swap the parameter around - * @param {string} evt event name - * @param {*} params pass to the callback - * @param {string} type of call - * @param {object} context what context callback execute in - * @return {*} from $trigger - */ - EventService.prototype.$call = function $call (evt, params, type, context) { - if ( type === void 0 ) type = false; - if ( context === void 0 ) context = null; - - var args = [evt, params, context, type]; - return Reflect.apply(this.$trigger, this, args) - }; - - /** - * remove the evt from all the stores - * @param {string} evt name - * @return {boolean} true actually delete something - */ - EventService.prototype.$off = function $off (evt) { - var this$1 = this; - - this.validateEvt(evt); - var stores = [ this.lazyStore, this.normalStore ]; - var found = false; - stores.forEach(function (store) { - if (store.has(evt)) { - found = true; - this$1.logger('($off)', evt); - store.delete(evt); - } - }); - return found; - }; - - /** - * return all the listener from the event - * @param {string} evtName event name - * @param {boolean} [full=false] if true then return the entire content - * @return {array|boolean} listerner(s) or false when not found - */ - EventService.prototype.$get = function $get (evt, full) { - if ( full === void 0 ) full = false; - - this.validateEvt(evt); - var store = this.normalStore; - if (store.has(evt)) { - return Array - .from(store.get(evt)) - .map( function (l) { - if (full) { - return l; - } - var key = l[0]; - var callback = l[1]; - return callback; - }) - } - return false; - }; - - /** - * store the return result from the run - * @param {*} value whatever return from callback - */ - prototypeAccessors.$done.set = function (value) { - this.logger('($done)', 'value: ', value); - if (this.keep) { - this.result.push(value); - } else { - this.result = value; - } - }; - - /** - * @TODO is there any real use with the keep prop? - * getter for $done - * @return {*} whatever last store result - */ - prototypeAccessors.$done.get = function () { - if (this.keep) { - this.logger('(get $done)', this.result); - return this.result[this.result.length - 1] - } - return this.result; - }; - - Object.defineProperties( EventService.prototype, prototypeAccessors ); - - return EventService; - }(NbEventServiceBase)); - - // default - - // this will generate a event emitter and will be use everywhere - // output - function getEventEmitter(debugOn) { - var logger = debugOn ? function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - args.unshift('[NBS]'); - console.log.apply(null, args); - }: undefined; - return new EventService({ logger: logger }) - } - - // main export interface - /** - * When pass a static contract then it return a static interface - * otherwise it will become the async interface - * @param {object} fly the http engine - already init object not the class! - * @param {object} config configuration - * @return {object} jsonqlClient - */ - function jsonqlClient(fly, config) { - var ee = getEventEmitter(config.debugOn); - return jsonqlAsync(ee, config, fly) - } - - // this one will bring the fly.js in - - function full(config) { - if ( config === void 0 ) config = {}; - - return jsonqlClient(new Fly(), config) - } - - return full; - -}))); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClient=e()}(this,(function(){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r,n=e((function(t,e){var r;r=function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=2)}([function(t,e,r){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};t.exports={type:function(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()},isObject:function(t,e){return e?"object"===this.type(t):t&&"object"===(void 0===t?"undefined":n(t))},isFormData:function(t){return"undefined"!=typeof FormData&&t instanceof FormData},trim:function(t){return t.replace(/(^\s*)|(\s*$)/g,"")},encode:function(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")},formatParams:function(t){var e="",r=!0,n=this;return this.isObject(t)?(function t(o,i){var a=n.encode,u=n.type(o);if("array"==u)o.forEach((function(e,r){n.isObject(e)||(r=""),t(e,i+"%5B"+r+"%5D")}));else if("object"==u)for(var c in o)t(o[c],i?i+"%5B"+a(c)+"%5D":a(c));else r||(e+="&"),r=!1,e+=i+"="+a(o)}(t,""),e):t},merge:function(t,e){for(var r in e)t.hasOwnProperty(r)?this.isObject(e[r],1)&&this.isObject(t[r],1)&&this.merge(t[r],e[r]):t[r]=e[r];return t}}},,function(t,e,r){var n=function(){function t(t,e){for(var r=0;r0&&(t+=(-1===t.indexOf("?")?"?":"&")+w.join("&")),a.open(r.method,t);try{a.withCredentials=!!r.withCredentials,a.timeout=r.timeout||0,"stream"!==y&&(a.responseType=y)}catch(t){}var j=r.headers[u]||r.headers[c],S="application/x-www-form-urlencoded";for(var O in o.trim((j||"").toLowerCase())===S?e=o.formatParams(e):o.isFormData(e)||-1===["object","array"].indexOf(o.type(e))||(S="application/json;charset=utf-8",e=JSON.stringify(e)),j||b||(r.headers[u]=S),r.headers)if(O===u&&o.isFormData(e))delete r.headers[O];else try{a.setRequestHeader(O,r.headers[O])}catch(t){}function k(t,e,n){v(l.p,(function(){if(t){n&&(e.request=r);var o=t.call(l,e,Promise);e=void 0===o?e:o}d(e)||(e=Promise[0===n?"resolve":"reject"](e)),e.then((function(t){s(t)})).catch((function(t){h(t)}))}))}function E(t){t.engine=a,k(l.onerror,t,-1)}function A(t,e){this.message=t,this.status=e}a.onload=function(){try{var t=a.response||a.responseText;t&&r.parseJson&&-1!==(a.getResponseHeader(u)||"").indexOf("json")&&!o.isObject(t)&&(t=JSON.parse(t));var e=a.responseHeaders;if(!e){e={};var n=(a.getAllResponseHeaders()||"").split("\r\n");n.pop(),n.forEach((function(t){if(t){var r=t.split(":")[0];e[r]=a.getResponseHeader(r)}}))}var i=a.status,c=a.statusText,s={data:t,headers:e,status:i,statusText:c};if(o.merge(s,a._response),i>=200&&i<300||304===i)s.engine=a,s.request=r,k(l.handler,s,0);else{var f=new A(c,i);f.response=s,E(f)}}catch(f){E(new A(f.msg,a.status))}},a.onerror=function(t){E(new A(t.msg||"Network Error",0))},a.ontimeout=function(){E(new A("timeout [ "+a.timeout+"ms ]",1))},a._options=r,setTimeout((function(){a.send(b?null:e)}),0)}(n):s(n)}),(function(t){h(t)}))}))}));return h.engine=a,h}},{key:"all",value:function(t){return Promise.all(t)}},{key:"spread",value:function(t){return function(e){return t.apply(null,e)}}}]),t}();a.default=a,["get","post","put","patch","head","delete"].forEach((function(t){a.prototype[t]=function(e,r,n){return this.request(e,r,o.merge({method:t},n))}})),["lock","unlock","clear"].forEach((function(t){a.prototype[t]=function(){this.interceptors.request[t]()}})),t.exports=a}])},t.exports=r()})),o=(r=n)&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r,i="application/vnd.api+json",a={Accept:i,"Content-Type":[i,"charset=utf-8"].join(";")},u="query",c="mutation",s="socket",f="payload",l="condition",p="TS",h=["POST","PUT"],d="type",v="optional",g="enumv",y="args",b="checker",m="alias",_="__checked__",w={desc:"y"},j="No message",S=Array.isArray,O="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},k="object"==typeof O&&O&&O.Object===Object&&O,E="object"==typeof self&&self&&self.Object===Object&&self,A=k||E||Function("return this")(),x=A.Symbol,T=Object.prototype,P=T.hasOwnProperty,q=T.toString,C=x?x.toStringTag:void 0;var $=Object.prototype.toString;var z="[object Null]",N="[object Undefined]",R=x?x.toStringTag:void 0;function M(t){return null==t?void 0===t?N:z:R&&R in Object(t)?function(t){var e=P.call(t,C),r=t[C];try{t[C]=void 0;var n=!0}catch(t){}var o=q.call(t);return n&&(e?t[C]=r:delete t[C]),o}(t):function(t){return $.call(t)}(t)}function F(t,e){return function(r){return t(e(r))}}var I=F(Object.getPrototypeOf,Object);function J(t){return null!=t&&"object"==typeof t}var D="[object Object]",U=Function.prototype,H=Object.prototype,L=U.toString,B=H.hasOwnProperty,K=L.call(Object);function G(t){if(!J(t)||M(t)!=D)return!1;var e=I(t);if(null===e)return!0;var r=B.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&L.call(r)==K}function V(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&nt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var mt=function(t){return S(t)?t:[t]},_t=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),xt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),Pt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),qt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Ct=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),$t=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),zt=Object.freeze({__proto__:null,Jsonql406Error:wt,Jsonql500Error:jt,JsonqlForbiddenError:St,JsonqlAuthorisationError:Ot,JsonqlContractAuthError:kt,JsonqlResolverAppError:Et,JsonqlResolverNotFoundError:At,JsonqlEnumError:xt,JsonqlTypeError:Tt,JsonqlCheckerError:Pt,JsonqlValidationError:qt,JsonqlError:Ct,JsonqlServerError:$t}),Nt=Ct,Rt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function Mt(t){if(Rt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||j,a=e.detail||e;if(o&&zt[o])throw new zt[r](i,a);throw new Nt(i,a)}return t}function Ft(t){return!!function(t){return G(t)&&(_t(t,u)||_t(t,c)||_t(t,s))}(t)&&t}function It(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var Jt=function(t,e){return void 0===e&&(e={}),Ft(e)?Promise.resolve(e):t.getContract()},Dt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function Ut(t){this.message=t}Ut.prototype=new Error,Ut.prototype.name="InvalidCharacterError";var Ht="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new Ut("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=Dt.indexOf(n);return a};var Lt=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Ht(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return Ht(e)}};function Bt(t){this.message=t}Bt.prototype=new Error,Bt.prototype.name="InvalidTokenError";var Kt=function(t,e){if("string"!=typeof t)throw new Bt("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(Lt(t.split(".")[r]))}catch(t){throw new Bt("Invalid token specified: "+t.message)}},Gt=Bt;Kt.InvalidTokenError=Gt;var Vt="[object String]";function Wt(t){return"string"==typeof t||!S(t)&&J(t)&&M(t)==Vt}var Yt=function(t){return""!==bt(t)&&Wt(t)},Qt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Xt(t){if(Yt(t))return function(t){var e=t.iat||Qt(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Ct("Token has expired on "+r,t)}return t}(Kt(t));throw new Ct("Token must be a string!")}var Zt=function(t){return!!S(t)||null!=t&&""!==bt(t)},te="[object Number]";function ee(t){return function(t){return"number"==typeof t||J(t)&&M(t)==te}(t)&&t!=+t}var re=function(t){return!Wt(t)&&!ee(parseFloat(t))},ne=function(t){return null!=t&&"boolean"==typeof t},oe=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==bt(t)&&(!1===e||!0===e&&null!==t)},ie=d,ae=v,ue=g,ce=y,se=b,fe=m,le="continue",pe=function(t){switch(t){case"number":return re;case"string":return Yt;case"boolean":return ne;default:return oe}},he=function(t,e){return void 0===e&&(e=""),!!S(t)&&(""===e||""===bt(e)||!(t.filter((function(t){return!pe(e)(t)})).length>0))},de=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ve=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!pe(e)(t)})).length)})).length:e.length>e.filter((function(t){return!he(r,t)})).length};var ge,ye=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[ge?a:++n];if(!1===e(o[u],u,o))break}return t};var be="[object Arguments]";function me(t){return J(t)&&M(t)==be}var _e=Object.prototype,we=_e.hasOwnProperty,je=_e.propertyIsEnumerable,Se=me(function(){return arguments}())?me:function(t){return J(t)&&we.call(t,"callee")&&!je.call(t,"callee")};var Oe="object"==typeof exports&&exports&&!exports.nodeType&&exports,ke=Oe&&"object"==typeof module&&module&&!module.nodeType&&module,Ee=ke&&ke.exports===Oe?A.Buffer:void 0,Ae=(Ee?Ee.isBuffer:void 0)||function(){return!1},xe=9007199254740991,Te=/^(?:0|[1-9]\d*)$/;function Pe(t,e){var r=typeof t;return!!(e=null==e?xe:e)&&("number"==r||"symbol"!=r&&Te.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=qe}var $e={};$e["[object Float32Array]"]=$e["[object Float64Array]"]=$e["[object Int8Array]"]=$e["[object Int16Array]"]=$e["[object Int32Array]"]=$e["[object Uint8Array]"]=$e["[object Uint8ClampedArray]"]=$e["[object Uint16Array]"]=$e["[object Uint32Array]"]=!0,$e["[object Arguments]"]=$e["[object Array]"]=$e["[object ArrayBuffer]"]=$e["[object Boolean]"]=$e["[object DataView]"]=$e["[object Date]"]=$e["[object Error]"]=$e["[object Function]"]=$e["[object Map]"]=$e["[object Number]"]=$e["[object Object]"]=$e["[object RegExp]"]=$e["[object Set]"]=$e["[object String]"]=$e["[object WeakMap]"]=!1;var ze,Ne="object"==typeof exports&&exports&&!exports.nodeType&&exports,Re=Ne&&"object"==typeof module&&module&&!module.nodeType&&module,Me=Re&&Re.exports===Ne&&k.process,Fe=function(){try{var t=Re&&Re.require&&Re.require("util").types;return t||Me&&Me.binding&&Me.binding("util")}catch(t){}}(),Ie=Fe&&Fe.isTypedArray,Je=Ie?(ze=Ie,function(t){return ze(t)}):function(t){return J(t)&&Ce(t.length)&&!!$e[M(t)]},De=Object.prototype.hasOwnProperty;function Ue(t,e){var r=S(t),n=!r&&Se(t),o=!r&&!n&&Ae(t),i=!r&&!n&&!o&&Je(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},ir.prototype.set=function(t,e){var r=this.__data__,n=nr(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var ar,ur=A["__core-js_shared__"],cr=(ar=/[^.]+$/.exec(ur&&ur.keys&&ur.keys.IE_PROTO||""))?"Symbol(src)_1."+ar:"";var sr=Function.prototype.toString;function fr(t){if(null!=t){try{return sr.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var lr=/^\[object .+?Constructor\]$/,pr=Function.prototype,hr=Object.prototype,dr=pr.toString,vr=hr.hasOwnProperty,gr=RegExp("^"+dr.call(vr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function yr(t){return!(!Ge(t)||function(t){return!!cr&&cr in t}(t))&&(Xe(t)?gr:lr).test(fr(t))}function br(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return yr(r)?r:void 0}var mr=br(A,"Map"),_r=br(Object,"create");var wr="__lodash_hash_undefined__",jr=Object.prototype.hasOwnProperty;var Sr=Object.prototype.hasOwnProperty;var Or="__lodash_hash_undefined__";function kr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&zr?new qr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=de(t))?!ve({arg:r},e):!pe(t)(r))})).length)})).length}return!1},eo=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(to,null,a);case"array"===t:return!he(e.arg);case!1!==(r=de(t)):return!ve(e,r);default:return!pe(t)(e.arg)}},ro=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},no=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!he(e))throw new Ct("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!he(t))throw new Ct("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?ro(t,a):t,index:r,param:a,optional:i}}));default:throw new Ct("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Zt(e)&&!(r.type.length>r.type.filter((function(e){return eo(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return eo(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},oo=function(){try{var t=br(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function io(t,e,r){"__proto__"==e&&oo?oo(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function ao(t,e,r){(void 0===r||rr(t[e],r))&&(void 0!==r||e in t)||io(t,e,r)}var uo="object"==typeof exports&&exports&&!exports.nodeType&&exports,co=uo&&"object"==typeof module&&module&&!module.nodeType&&module,so=co&&co.exports===uo?A.Buffer:void 0,fo=so?so.allocUnsafe:void 0;function lo(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new Rr(n).set(new Rr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var po=Object.create,ho=function(){function t(){}return function(e){if(!Ge(e))return{};if(po)return po(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function vo(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var go=Object.prototype.hasOwnProperty;function yo(t,e,r){var n=t[e];go.call(t,e)&&rr(n,r)&&(void 0!==r||e in t)||io(t,e,r)}var bo=Object.prototype.hasOwnProperty;function mo(t){if(!Ge(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Le(t),r=[];for(var n in t)("constructor"!=n||!e&&bo.call(t,n))&&r.push(n);return r}function _o(t){return Ze(t)?Ue(t,!0):mo(t)}function wo(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=Ao)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Eo);function qo(t,e){return Po(function(t,e,r){return e=ko(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=ko(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Co.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!Ge(r))return!1;var n=typeof e;return!!("number"==n?Ze(r)&&Pe(e,r.length):"string"==n&&e in r)&&rr(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=0;e--){var r=Ni().key(e);t(Ri(r),r)}},remove:function(t){return Ni().removeItem(t)},clearAll:function(){return Ni().clear()}};function Ni(){return $i.localStorage}function Ri(t){return Ni().getItem(t)}var Mi=yi.trim,Fi={name:"cookieStorage",read:function(t){if(!t||!Ui(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Ii.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Ii.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Ji,remove:Di,clearAll:function(){Ji((function(t,e){Di(e)}))}},Ii=yi.Global.document;function Ji(t){for(var e=Ii.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Mi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Di(t){t&&Ui(t)&&(Ii.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Ui(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Ii.cookie)}var Hi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Li=yi.bind,Bi=yi.each,Ki=yi.create,Gi=yi.slice,Vi=function(){var t=Ki(Wi,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Li(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Li(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),Bi(r,(function(e,r){t.fire(r,void 0,e)}))}}};var Wi={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Li(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Gi(arguments,1);Bi(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},Yi=e((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),Qi=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=Yi.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=Yi.compress(this._serialize(r));t(e,n)}}};var Xi=[zi,Fi],Zi=[Hi,Vi,Qi],ta=Pi.createStore(Xi,Zi),ea=yi.Global;function ra(){return ea.sessionStorage}function na(t){return ra().getItem(t)}var oa=[{name:"sessionStorage",read:na,write:function(t,e){return ra().setItem(t,e)},each:function(t){for(var e=ra().length-1;e>=0;e--){var r=ra().key(e);t(na(r),r)}},remove:function(t){return ra().removeItem(t)},clearAll:function(){return ra().clear()}},Fi],ia=[Hi,Qi],aa=Pi.createStore(oa,ia),ua=ta,ca=aa,sa=function(t){var e;return(e={}).args=t,e};function fa(t,e){var r;return(r={})[t]=e,r[p]=[pi()],r}var la=function(t){return _t(t,"data")&&!_t(t,"error")?t.data:t},pa=function(t){this.opts=t,this.instanceKey=It(this.opts.hostname)+"",this.localStore=ua,this.sessionStore=ca},ha={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};pa.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?$o({},o,e):e,r))},pa.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},pa.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},pa.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},ha.lset.set=function(t){return this.__setMethod("localStore",t)},ha.lget.get=function(){return this.__getMethod("localStore")},pa.prototype.ldel=function(t){return this.__delMethod("localStore",t)},pa.prototype.lclear=function(){return this.__clearMethod("localStore")},ha.sset.set=function(t){return this.__setMethod("sessionStore",t)},ha.sget.get=function(){return this.__getMethod("sessionStore")},pa.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},pa.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(pa.prototype,ha);var da=h[0],va=h[1],ga=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Xt)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(ci(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new qt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&ci(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!Ft(t))throw new qt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=Ft(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={headers:{configurable:!0}};return r.headers.set=function(t){this.extraHeader=t},e.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=$o({},{_cb:pi()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=$o({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=$o({},{method:da,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},e.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},e.prototype.processJsonp=function(t){return la(t)},e.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=ui(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):la(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new $t("Server side error",r)}))},e.prototype.getHeaders=function(){return this.opts.enableAuth?$o({},a,this.getAuthHeader(),this.extraHeader):$o({},a,this.extraHeader)},e.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},e.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=$o({},this.extraParams,w)),this.request({},{method:"GET"},this.contractHeader).then(Mt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new $t("getRemoteContract",e)}))},e.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Wt(t)&&S(e)){var n=sa(e);return!0===r?n:fa(t,n)}throw new qt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(Mt)},e.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[f]=e,o[l]=r,!0===n)return o;if(Wt(t))return fa(t,o);throw new qt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:va}).then(Mt)},Object.defineProperties(e.prototype,r),e}(pa)))),ya=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,mt(t))}),Reflect.apply(t,null,r))}};function ba(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function ma(t,e,r,n){void 0===n&&(n=!1);var o=ba(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var _a=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return si(r,i).then((function(){return t.query.apply(t,[e,a,u])}))}},wa=function(t,e,r,n,o){var i={},a=function(t){i=ma(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return si(a,i).then((function(){return e.query.apply(e,[t,a,u])}))}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},ja=function(t,e,r,n,o){var i={},a=function(t){i=ma(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return si(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])}))}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Sa=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=_a(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=_a(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var Oa=function(t,e,r,n){var o=function(t,e,r,n){return ya(wa,ja,Sa)({},t,e,r,n)}(t,n,e,r);return e.enableAuth&&(o.userdata=function(){return t.jsonqlUserdata},o.getToken=function(e){return void 0===e&&(e=!1),t.rawAuthToken(e)},o.profileIndex=function(e){if(void 0===e&&(e=!1),!1===e)return t.profileIndex;t.profileIndex=e},o.getProfiles=function(e){return void 0===e&&(e=!1),t.getProfiles(e)}),e.exposeContract&&(o.getContract=function(){return t.getContract()}),e.exposeStore&&(o.tmpSave=function(t){},o.tmpGet=function(t){},o.tmpDel=function(t){},o.persistSave=function(t){},o.persistGet=function(t){},o.persistDel=function(t){}),o.eventEmitter=n,o.version="1.5.1",o.log=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return Reflect.apply(t.log,t,["[DEV DEBUG]"].concat(e))},o},ka={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:i,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Ea={hostname:fi(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:fi("jsonql",["string"]),loginHandlerName:fi("login",["string"]),logoutHandlerName:fi("logout",["string"]),enableJsonp:fi(!1,["boolean"]),enableAuth:fi(!1,["boolean"]),useJwt:fi(!0,["boolean"]),persistToken:fi(!1,["boolean","number"]),useLocalstorage:fi(!0,["boolean"]),storageKey:fi("jsonqlstore",["string"]),authKey:fi("jsonqlauthkey",["string"]),contractExpired:fi(0,["number"]),keepContract:fi(!0,["boolean"]),exposeContract:fi(!1,["boolean"]),exposeStore:fi(!1,["boolean"]),showContractDesc:fi(!1,["boolean"]),contractKey:fi(!1,["boolean"]),contractKeyName:fi("X-JSONQL-CV-KEY",["string"]),enableTimeout:fi(!1,["boolean"]),timeout:fi(5e3,["number"]),returnInstance:fi(!1,["boolean"]),allowReturnRawToken:fi(!1,["boolean"]),debugOn:fi(!1,["boolean"])};function Aa(t){return ba(t,_)?Promise.resolve(t):function(t){var e=t.contract;return li(t,Ea,ka).then((function(t){return t.contract=e,t}))}(t)}var xa=new WeakMap,Ta=new WeakMap,Pa=function(){this.__suspend__=null,this.queueStore=new Set},qa={$suspend:{configurable:!0},$queues:{configurable:!0}};qa.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Pa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},qa.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Pa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Pa.prototype,qa);var Ca=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){xa.set(this,t)},r.normalStore.get=function(){return xa.get(this)},r.lazyStore.set=function(t){Ta.set(this,t)},r.lazyStore.get=function(){return Ta.get(this)},e.prototype.hashFnToKey=function(t){return It(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Pa));function $a(t,e){var r;return function(t,e,r){return void 0===e&&(e={}),Aa(e).then((function(t){return{baseClient:new ga(r,t),opts:t}})).then((function(e){var r=e.baseClient,n=e.opts;return Jt(r,n.contract).then((function(e){return Oa(r,n,e,t)}))}))}((r=e.debugOn,new Ca({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),e,t)}return function(t){return void 0===t&&(t={}),$a(new o,t)}})); //# sourceMappingURL=jsonql-client.umd.js.map diff --git a/packages/http-client/dist/jsonql-client.umd.js.map b/packages/http-client/dist/jsonql-client.umd.js.map index 904c3af6..cb67906c 100644 --- a/packages/http-client/dist/jsonql-client.umd.js.map +++ b/packages/http-client/dist/jsonql-client.umd.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client.umd.js","sources":["../node_modules/lodash-es/isArray.js","../node_modules/rollup-plugin-node-globals/src/global.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/lodash-es/_arrayMap.js","../node_modules/lodash-es/_baseSlice.js","../node_modules/lodash-es/_baseFindIndex.js","../node_modules/lodash-es/_baseIsNaN.js","../node_modules/lodash-es/_strictIndexOf.js","../node_modules/lodash-es/_asciiToArray.js","../node_modules/lodash-es/_hasUnicode.js","../node_modules/lodash-es/_unicodeToArray.js","../node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-errors/src/get-error-by-status.js","../node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-errors/src/resolver-not-found-error.js","../node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-errors/src/index.js","../node_modules/jsonql-errors/src/client-errors-handler.js","../node_modules/jsonql-errors/src/get-error-name-by-instance.js","../node_modules/jsonql-errors/index.js","../node_modules/jsonql-utils/src/contract.js","../node_modules/nb-event-service/src/hash-code.js","../src/utils.js","../node_modules/jwt-decode/lib/atob.js","../node_modules/jsonql-params-validator/src/string.js","../node_modules/jsonql-jwt/src/client/decode-token/decode-token.js","../node_modules/jsonql-params-validator/src/number.js","../node_modules/jsonql-params-validator/src/boolean.js","../node_modules/jsonql-params-validator/src/any.js","../node_modules/jsonql-params-validator/src/constants.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/_listCacheClear.js","../node_modules/lodash-es/eq.js","../node_modules/lodash-es/_stackDelete.js","../node_modules/lodash-es/_stackGet.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-params-validator/src/validator.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/negate.js","../node_modules/lodash-es/_baseFindKey.js","../node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-params-validator/src/options/check-options-async.js","../node_modules/jsonql-params-validator/src/options/construct-config.js","../node_modules/jsonql-params-validator/src/options/index.js","../node_modules/jsonql-params-validator/index.js","../node_modules/jsonql-utils/src/timestamp.js","../node_modules/store/plugins/defaults.js","../src/stores/local-store.js","../src/stores/session-store.js","../src/stores/index.js","../node_modules/jsonql-utils/src/params-api.js","../node_modules/jsonql-utils/src/results.js","../src/base/store-cls.js","../src/base/http-cls.js","../src/base/contract-cls.js","../src/base/auth-cls.js","../src/base/base-cls.js","../src/base/index.js","../src/core/methods-generator.js","../src/core/jsonql-api-generator.js","../src/options/base-options.js","../src/options/check-options-async.js","../src/options/index.js","../src/jsonql-async.js","../node_modules/nb-event-service/src/suspend.js","../node_modules/nb-event-service/src/store-service.js","../node_modules/nb-event-service/src/event-service.js","../node_modules/nb-event-service/index.js","../src/ee.js","../index.js","../full.js"],"sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length;\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg];\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @return {*} json object on success\n */\nconst parse = function(n) {\n try {\n return JSON.parse(n)\n } catch(e) {\n return n;\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false;\n /*\n console.info('obj', obj)\n console.error(e)\n throw new Error(e)\n */\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = (n) => {\n if (typeof n === 'string') {\n return parse(n)\n }\n return JSON.parse(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== '';\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n","// just a simple util method to return the error based on the status code\n/**\n * @param {number} statusCode to check\n * @param {boolean} contract if this is a contract call or not\n * @return {string} the error name\n */\nexport default function getErrorByStatus(statusCode, contract = false) {\n switch (statusCode) {\n case 401:\n return contract ? 'JsonqlContractAuthError' : 'JsonqlAuthorisationError';\n case 403:\n return 'JsonqlForbiddenError';\n case 404:\n return 'JsonqlResolverNotFoundError';\n case 406:\n return 'Jsonql406Error';\n case 500:\n return 'Jsonql500Error';\n default:\n return 'JsonqlError';\n }\n}\n","/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error)\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","/**\n * This is a custom error to throw when could not find the resolver\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class JsonqlResolverNotFoundError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlResolverNotFoundError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlResolverNotFoundError);\n }\n }\n\n static get statusCode() {\n return 404;\n }\n\n static get name() {\n return 'JsonqlResolverNotFoundError';\n }\n}\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError);\n }\n }\n\n static get name() {\n return 'JsonqlEnumError';\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlTypeError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError);\n }\n }\n\n static get name() {\n return 'JsonqlTypeError';\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args)\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError)\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError';\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError';\n }\n}\n","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message)\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// server side\nimport Jsonql406Error from './406-error';\nimport Jsonql500Error from './500-error';\nimport JsonqlAuthorisationError from './authorisation-error';\nimport JsonqlContractAuthError from './contract-auth-error';\nimport JsonqlResolverAppError from './resolver-app-error';\nimport JsonqlResolverNotFoundError from './resolver-not-found-error';\n\n// check options error\nimport JsonqlEnumError from './enum-error';\nimport JsonqlTypeError from './type-error';\nimport JsonqlCheckerError from './checker-error';\n// share\nimport JsonqlValidationError from './validation-error';\nimport JsonqlError from './error';\n\nimport JsonqlServerError from './server-error';\n\nexport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n};\n","// this will add directly to the then call in each http call\n\nimport * as errors from './index';\nimport getErrorByStatus from './get-error-by-status';\nimport { NO_ERROR_MSG } from 'jsonql-constants';\nconst { JsonqlError } = errors;\n\n/**\n * We can not just check something like result.data what if the result if false?\n * @param {object} obj the result object\n * @param {string} key we want to check if its exist or not\n * @return {boolean} true on found\n */\nconst isObjectHasKey = (obj, key) => {\n const keys = Object.keys(obj)\n return !!keys.filter(k => key === k).length;\n}\n\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nexport default function clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n","// get error name by instance\nconst UNKNOWN_ERROR = 'unknown'\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {array} filtered with name as value\n */\nfunction mapErrToName(errs, e) {\n return errs.filter(err => e instanceof err)\n .map(err => err.name)\n}\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {string} name of the error object\n */\nfunction getErrorNameByInstance(errs, e) {\n let error = mapErrToName(errs, e)\n return error.length ? error[0] : UNKNOWN_ERROR\n}\n\n/**\n * the same as above with a default JsonqlError as default\n * @param {array} errs same\n * @param {object} e error itself\n * @return {string} the name of the error\n */\nfunction getErrorNameByInstanceWithDefault(errs, e) {\n let name = getErrorNameByInstance(errs, e)\n return name === UNKNOWN_ERROR ? 'JsonqlError' : name;\n}\n\n\nexport {\n getErrorNameByInstanceWithDefault,\n getErrorNameByInstance,\n UNKNOWN_ERROR\n}\n","// jsonql-errors main interface\nimport getErrorByStatus from './src/get-error-by-status'\nimport clientErrorsHandler from './src/client-errors-handler'\nimport {\n getErrorNameByInstance,\n getErrorNameByInstanceWithDefault,\n UNKNOWN_ERROR\n} from './src/get-error-name-by-instance'\nimport finalCatch from './src/final-catch.js'\nconst JSONQL_ERRORS_INFO = '__PLACEHOLDER__'\nimport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n JsonqlValidationError,\n JsonqlError,\n JsonqlServerError\n} from './src'\n// export\nexport {\n JSONQL_ERRORS_INFO,\n UNKNOWN_ERROR,\n\n getErrorByStatus,\n clientErrorsHandler,\n finalCatch,\n getErrorNameByInstance,\n getErrorNameByInstanceWithDefault,\n\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n}\n","// split the contract into the node side and the generic side\nimport { isObjectHasKey } from './generic'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n SOCKET_NAME,\n QUERY_ARG_NAME,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlResolverNotFoundError } from 'jsonql-errors'\n/**\n * Check if the json is a contract file or not\n * @param {object} contract json object\n * @return {boolean} true\n */\nexport function checkIsContract(contract) {\n return isPlainObject(contract)\n && (\n isObjectHasKey(contract, QUERY_NAME)\n || isObjectHasKey(contract, MUTATION_NAME)\n || isObjectHasKey(contract, SOCKET_NAME)\n )\n}\n\n/**\n * Wrapper method that check if it's contract then return the contract or false\n * @param {object} contract the object to check\n * @return {boolean | object} false when it's not\n */\nexport function isContract(contract) {\n return checkIsContract(contract) ? contract : false;\n}\n\n/**\n * Ported from jsonql-params-validator but different\n * if we don't find the socket part then return false\n * @param {object} contract the contract object\n * @return {object|boolean} false on failed\n */\nexport function extractSocketPart(contract) {\n if (isObjectHasKey(contract, 'socket')) {\n return contract.socket;\n }\n return false;\n}\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @param {boolean} [fallback=false] this is a fall back option for old code\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport function groupByNamespace(contract, fallback = false) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n if (fallback) {\n return contract; // just return the whole contract\n }\n throw new JsonqlError(`socket not found in contract!`)\n }\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\n}\n\n/**\n * @NOTE ported from jsonql-ws-client\n * Got to make sure the connection order otherwise\n * it will hang\n * @param {object} nspSet contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspSet, publicNamespace) {\n let names = []; // need to make sure the order!\n for (let namespace in nspSet) {\n if (namespace === publicNamespace) {\n names[1] = namespace;\n } else {\n names[0] = namespace;\n }\n }\n return names;\n}\n\n\n/**\n * Extract the args from the payload\n * @param {object} payload to work with\n * @param {string} type of call\n * @return {array} args\n */\nexport function extractArgsFromPayload(payload, type) {\n switch (type) {\n case QUERY_NAME:\n return payload[QUERY_ARG_NAME];\n case MUTATION_NAME:\n return [\n payload[PAYLOAD_PARAM_NAME],\n payload[CONDITION_PARAM_NAME]\n ];\n default:\n throw new JsonqlError(`Unknown ${type} to extract argument from!`)\n }\n}\n\n/**\n * Like what the name said\n * @param {object} contract the contract json\n * @param {string} type query|mutation\n * @param {string} name of the function\n * @return {object} the params part of the contract\n */\nexport function extractParamsFromContract(contract, type, name) {\n try {\n const result = contract[type][name];\n // debug('extractParamsFromContract', result)\n if (!result) {\n // debug(name, type, contract)\n throw new JsonqlResolverNotFoundError(name, type)\n }\n return result;\n } catch(e) {\n throw new JsonqlResolverNotFoundError(name, e)\n }\n}\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport default function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n","// take only the module part which is what we use here\n// and export it again to use through out the client\n// this way we avoid those that we don't want node.js module got build into the code\nimport { isContract } from 'jsonql-utils/src/contract'\nimport hashCodeFn from 'nb-event-service/src/hash-code'\n/**\n * @param {object} jsonqlInstance the init instance of jsonql client\n * @param {object} contract the static contract\n * @return {object} contract may be from server\n */\nconst getContractFromConfig = function(jsonqlInstance, contract = {}) {\n if (isContract(contract)) {\n return Promise.resolve(contract)\n }\n return jsonqlInstance.getContract()\n}\n// wrapper method to make sure it's a string\nconst hashCode = str => hashCodeFn(str) + ''\n\n// simple util to check if an object has any properties\n// const hasProp = obj => isObject(obj) && Object.keys(obj).length\n\n// export some constants as well\n// since it's only use here there is no point of adding it to the constants module\n// or may be we add it back later\nconst ENDPOINT_TABLE = 'endpoint' // not in use anymore delete later @TODO\nconst USERDATA_TABLE = 'userdata'\nconst CLS_LOCAL_STORE_NAME = 'localStore'\nconst CLS_SESS_STORE_NAME = 'sessionStore'\nconst CLS_CONTRACT_NAME = 'contract'\nconst CLS_PROFILE_IDX = 'prof_idx'\nconst ZERO_IDX = 0\n// export\nexport {\n hashCode,\n getContractFromConfig,\n ENDPOINT_TABLE,\n USERDATA_TABLE,\n CLS_LOCAL_STORE_NAME,\n CLS_SESS_STORE_NAME,\n CLS_CONTRACT_NAME,\n CLS_PROFILE_IDX,\n ZERO_IDX\n}\n","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\nfunction polyfill (input) {\n var str = String(input).replace(/=+$/, '');\n if (str.length % 4 == 1) {\n throw new InvalidCharacterError(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = '';\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n return output;\n}\n\n\nmodule.exports = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill;\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false;\n}\n\nexport default checkIsString\n","// when the user is login with the jwt\n// we use call this to decode the token and then add the payload\n// to the resolver so the user can call ResolverName.userdata\n// and get back the payload\nimport jwt_decode from 'jwt-decode'\nimport isString from 'jsonql-params-validator/src/string'\nimport JsonqlError from 'jsonql-errors/src/error'\n\nconst timestamp = function (sec = false) {\n var time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n\n/**\n * We only check the nbf and exp\n * @param {object} token for checking\n * @return {object} token on success\n */\nfunction validate(token) {\n const start = token.iat || timestamp(true)\n // we only check the exp for the time being\n if (token.exp) {\n if (start >= token.exp) {\n const expired = new Date(token.exp).toISOString()\n throw new JsonqlError(`Token has expired on ${expired}`, token)\n }\n }\n return token;\n}\n\n/**\n * The browser client version it has far fewer options and it doesn't verify it\n * because it couldn't this is the job for the server\n * @TODO we need to add some extra proessing here to check for the exp field\n * @param {string} token to decrypted\n * @return {object} decrypted object\n */\nexport default function jwtDecode(token) {\n if (isString(token)) {\n const t = jwt_decode(token)\n return validate(t)\n }\n throw new JsonqlError('Token must be a string!')\n}\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nexport const ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\n","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber;\n case STRING_TYPE:\n return checkIsString;\n case BOOLEAN_TYPE:\n return checkIsBoolean;\n default:\n return checkIsAny;\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false;\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false;\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p;\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length;\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length;\n}\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport filter from 'lodash-es/filter'\n\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true;\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (_value !== undefined) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true;\n }).length)\n }).length;\n }\n }\n return false;\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p;\n let _args = [arg];\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return Reflect.apply(checkIsObject, null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\n\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n checkIsObject,\n combineFn,\n notEmpty\n} from './index'\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params;\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false;\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (arg !== undefined) {\n return arg;\n }\n return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ))\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ))\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ))\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length:\n let ctn = params.length;\n // this happens when we have those array. type\n let _type = [ DEFAULT_TYPE ]\n // we only looking at the first one, this might be a @BUG\n /*\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n } */\n // if we use the params as guide then the rest will get throw out\n // which is not what we want, instead, anything without the param\n // will get a any type and optional flag\n return args.map((arg, i) => {\n let optional = i >= ctn ? true : !!params[i].optional\n let param = params[i] || { type: _type, name: `_${i}` }\n return {\n arg: optional ? getOptionalValue(arg, param) : arg,\n index: i,\n param,\n optional\n }\n })\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n // v1.4.4 this fixed the problem, the root level optional is from the last fn\n if (p.optional === true || p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length;\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport isFunction from 'lodash-es/isFunction'\nimport merge from 'lodash-es/merge'\nimport mapValues from 'lodash-es/mapValues'\n\nimport JsonqlEnumError from 'jsonql-errors/src/enum-error'\nimport JsonqlTypeError from 'jsonql-errors/src/type-error'\nimport JsonqlCheckerError from 'jsonql-errors/src/checker-error'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true;\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // log('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n // log(ENUM_KEY, value[ENUM_KEY])\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n // log(CHECKER_KEY, value[CHECKER_KEY])\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args;\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","/// this is port back from the client to share across all projects\n\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:check-options-async')\n\n/**\n * Quick transform\n * @param {object} config that one\n * @param {object} appProps mutation configuration options\n * @return {object} put that arg into the args\n */\nconst configToArgs = (config, appProps) => {\n return Promise.resolve(\n prepareArgsForValidation(config, appProps)\n )\n}\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return configToArgs(config, appProps)\n .then(args1 => runValidation(args1, cb))\n // next if every thing good then pass to final merging\n .then(args2 => merge({}, args2, constProps))\n}\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\nimport checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n };\n if (optional === true) {\n base[OPTIONAL_KEY] = true;\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv;\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker;\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias;\n }\n return base;\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__';\n\n/**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n checkConfigAsync,\n checkConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nexport const inArray = isInArray;\nexport const isObjectHasKey = isObjectHasKeyFn;\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n","module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n","// sort of persist on the user side\nimport engine from 'store/src/store-engine'\n\nimport localStorage from 'store/storages/localStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// @1.5.0 stop using the expired plugin, and deal with it ourself\n// import expiredPlugin from 'store/plugins/expire'\nimport eventsPlugin from 'store/plugins/events'\nimport compressionPlugin from 'store/plugins/compression'\n\nconst storages = [localStorage, cookieStorage]\nconst plugins = [defaultPlugin, eventsPlugin, compressionPlugin]\n\nconst localStore = engine.createStore(storages, plugins)\n\nexport default localStore\n","// session store with watch\nimport engine from 'store/src/store-engine'\n\nimport sessionStorage from 'store/storages/sessionStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// start using compression in 1.5.0 \nimport compressionPlugin from 'store/plugins/compression'\n// @1.5.0 stop using the expired plugin and deal it ourself\n// import expiredPlugin from 'store/plugins/expire'\n\nconst storages = [sessionStorage, cookieStorage]\nconst plugins = [defaultPlugin, compressionPlugin]\n\nconst sessionStore = engine.createStore(storages, plugins)\n\nexport default sessionStore\n","// export store interface\n// @TODO need to figure out how to make this as a outside dependencies instead of built into it\nimport localStoreEngine from './local-store'\nimport sessionStoreEngine from './session-store'\n\n// export back the raw version for development purposes\nexport const localStore = localStoreEngine\nexport const sessionStore = sessionStoreEngine\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport isString from 'lodash-es/isString'\n\nimport { timestamp } from './timestamp'\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? JSON.parse(payload) : payload;\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName\n * @param {*} payload\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload) {\n return {\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload;\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload;\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getNameFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// break up from node-middleware\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n API_REQUEST_METHODS,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME ,\n QUERY_ARG_NAME,\n DATA_KEY,\n ERROR_KEY,\n INDEX_KEY,\n EXT,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport { isObjectHasKey } from './generic'\nimport { timestamp } from './timestamp'\nimport isArray from 'lodash-es/isArray'\nimport merge from 'lodash-es/merge'\n/**\n * getting what is calling after the above check\n * @param {string} method of call\n * @return {mixed} false on failed\n */\nexport const getCallMethod = method => {\n const [ POST, PUT ] = API_REQUEST_METHODS;\n switch (true) {\n case method === POST:\n return QUERY_NAME;\n case method === PUT:\n return MUTATION_NAME;\n default:\n return false;\n }\n}\n\n/**\n * wrapper method\n * @param {mixed} result of fn return\n * @param {boolean|array} [ts=false] when pass this then we append a new value to the end\n * @return {string} stringify data\n */\nexport const packResult = function(result, ts = false) {\n let payload = { [DATA_KEY]: result }\n if (ts && isArray(ts)) {\n ts.push(timestamp())\n payload[TIMESTAMP_PARAM_NAME] = ts\n }\n return JSON.stringify(payload)\n}\n\n/**\n * Check if the error object contain out custom key\n * @param {*} e object\n * @return {boolean} true\n */\nexport const isJsonqlErrorObj = e => {\n const searchFields = ['detail', 'className']\n const test = !!searchFields.filter(field => isObjectHasKey(e, field)).length\n if (test) {\n return ['className', 'message', 'statusCode']\n .filter(field => isObjectHasKey(e, field))\n .map(field => (\n {\n [field]: typeof e[field] === 'object' ? e[field].toString() : e[field]\n }\n ))\n .reduce(merge, {detail: e.toString()}) // can only get as much as possible\n }\n return false;\n}\n\n/**\n * wrapper method - the output is trying to match up the structure of the Error sub class\n * @param {mixed} detail of fn error\n * @param {string} [className=JsonqlError] the errorName\n * @param {number} [statusCode=500] the original error code\n * @return {string} stringify error\n */\nexport const packError = function(detail, className = 'JsonqlError', statusCode = 0, message = '') {\n let errorObj = { detail, className, statusCode, message }\n // we need to check the detail object to see if it has detail, className and message\n // if it has then we should merge the object instead\n return JSON.stringify({\n [ERROR_KEY]: isJsonqlErrorObj(detail) || errorObj,\n [TIMESTAMP_PARAM_NAME]: timestamp()\n })\n}\n\n// ported from http-client\n\n/**\n * handle the return data\n * @TODO how to handle the return timestamp and calculate the diff?\n * @param {object} result return from server\n * @return {object} strip the data part out, or if the error is presented\n */\nexport const resultHandler = result => (\n (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result\n)\n","// new 1.5.0\n// create a class method to handle all the saving and retriving data\n// using the instanceKey to id the data hence allow to use multiple instance\nimport merge from 'lodash-es/merge'\nimport { localStore, sessionStore } from '../stores'\nimport { CLS_SESS_STORE_NAME, CLS_LOCAL_STORE_NAME, hashCode } from '../utils'\n\n// this becomes the base class instead of the HttpCls\nexport default class StoreClass {\n\n constructor(opts) {\n this.opts = opts\n // make it a string\n this.instanceKey = hashCode(this.opts.hostname)\n // pass this store for use later\n this.localStore = localStore\n this.sessionStore = sessionStore\n /*\n if (this.opts.debugOn) { // reuse this to clear out the data\n this.log('clear all stores')\n localStore.clearAll()\n sessionStore.clearAll()\n\n localStore.set('TEST', Date.now())\n sessionStore.set('TEST', Date.now())\n }\n */\n }\n // store in local storage id by the instanceKey\n // values should be an object so with key so we just merge\n // into the existing store without going through the keys\n __setMethod(storeType, values) {\n let store = this[storeType]\n let data = this.__getMethod(storeType)\n const skey = this.opts.storageKey\n const ikey = this.instanceKey\n store.set(skey, {\n [ikey]: data ? merge({}, data, values) : values\n })\n }\n // return the data id by the instaceKey\n __getMethod(storeType) {\n let store = this[storeType]\n let data = store.get(this.opts.storageKey)\n return data ? data[this.instanceKey] : false\n }\n // remove from local store id by instanceKey\n __delMethod(storeType, key) {\n let data = this.__getMethod(storeType)\n if (data) {\n let store = {}\n for (let k in data) {\n if (k !== key) {\n store[k] = data[k]\n }\n }\n this.__setMethod(storeType, store)\n }\n }\n // clear everything by this instanceKey\n __clearMethod(storeKey) {\n const skey = this.opts.storageKey\n const store = this[storeKey]\n let data = store.get(skey)\n if (data) {\n let _store = {}\n for (let k in data) {\n if (k !== this.instanceKey) {\n _store[k] = data[k]\n }\n }\n store.set(skey, _store)\n }\n }\n // Alias for different store\n set lset(values) {\n return this.__setMethod(CLS_LOCAL_STORE_NAME, values)\n }\n\n get lget() {\n return this.__getMethod(CLS_LOCAL_STORE_NAME)\n }\n\n ldel(key) {\n return this.__delMethod(CLS_LOCAL_STORE_NAME, key)\n }\n\n lclear() {\n return this.__clearMethod(CLS_LOCAL_STORE_NAME)\n }\n\n // store in session store id by the instanceKey\n set sset(values) {\n // this.log('--- sset ---', values)\n return this.__setMethod(CLS_SESS_STORE_NAME, values)\n }\n\n get sget() {\n return this.__getMethod(CLS_SESS_STORE_NAME)\n }\n\n sdel(key) {\n return this.__delMethod(CLS_SESS_STORE_NAME, key)\n }\n\n sclear() {\n return this.__clearMethod(CLS_SESS_STORE_NAME)\n }\n\n\n}\n","// base HttpClass\nimport merge from 'lodash-es/merge'\nimport {\n createQuery,\n createMutation,\n getNameFromPayload\n} from 'jsonql-utils/src/params-api'\nimport { cacheBurst, urlParams } from 'jsonql-utils/src/urls'\nimport { resultHandler } from 'jsonql-utils/src/results'\nimport { isObject, isString } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlServerError,\n JsonqlError,\n // clientErrorsHandler\n} from 'jsonql-errors'\nimport {\n API_REQUEST_METHODS,\n DEFAULT_HEADER,\n JSONP_CALLBACK_NAME,\n SHOW_CONTRACT_DESC_PARAM\n} from 'jsonql-constants'\n\n// @DEBUG\nimport * as errors from 'jsonql-errors'\nimport { isObjectHasKey } from 'jsonql-utils/src/generic'\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nfunction clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n console.info('--- errorName ---', errorName, errors)\n\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n\n\n\n// extract the one we need\nconst [ POST, PUT ] = API_REQUEST_METHODS\n\nimport StoreClass from './store-cls'\n\nexport default class HttpClass extends StoreClass {\n /**\n * The opts has been check at the init stage\n * @param {object} opts configuration options\n */\n constructor(opts) {\n super(opts)\n // change the way how we init Fly\n // flyio now become external depedencies and it makes it easier to switch\n // @BUG should we run test to check if we have the windows object?\n // this.log(opts)\n // this.fly = opts.Fly ? new opts.Fly() : new Fly()\n // to a different environment like WeChat mini app\n\n this.extraHeader = {};\n // @1.2.1 for adding query to the call on the fly\n this.extraParams = {};\n // this.log('start up opts', opts);\n this.reqInterceptor()\n this.resInterceptor()\n }\n\n // set headers for that one call\n set headers(header) {\n this.extraHeader = header;\n }\n\n /**\n * Create the reusage request method\n * @param {object} payload jsonql payload\n * @param {object} options extra options add the request\n * @param {object} headers extra headers add to the call\n * @return {object} the fly request instance\n */\n request(payload, options = {}, headers = {}) {\n this.headers = headers;\n let params = merge({}, cacheBurst(), this.extraParams)\n // @TODO need to add a jsonp url and payload\n if (this.opts.enableJsonp) {\n let resolverName = getNameFromPayload(payload)\n params = merge({}, params, {[JSONP_CALLBACK_NAME]: resolverName})\n payload = payload[resolverName]\n }\n // double up the url param and see what happen @TODO remove later\n const reqParams = merge({}, { method: POST, params }, options)\n this.log('request params', reqParams, this.jsonqlEndpoint)\n\n return this.fly.request(this.jsonqlEndpoint, payload, reqParams)\n }\n\n /**\n * This will replace the create baseRequest method\n *\n */\n reqInterceptor() {\n this.fly.interceptors.request.use(\n req => {\n const headers = this.getHeaders()\n this.log('request interceptor call', headers)\n\n for (let key in headers) {\n req.headers[key] = headers[key]\n }\n return req;\n }\n )\n }\n\n // @TODO\n processJsonp(result) {\n return resultHandler(result)\n }\n\n /**\n * This will be replacement of the first then call\n *\n */\n resInterceptor() {\n const self = this;\n const jsonp = self.opts.enableJsonp;\n this.fly.interceptors.response.use(\n res => {\n this.log('response interceptor call', res)\n self.cleanUp()\n // now more processing here\n // there is a problem if we throw the result.error here\n // the original data is lost, so we need to do what we did before\n // deal with that error in the first then instead\n const result = isString(res.data) ? JSON.parse(res.data) : res.data;\n if (jsonp) {\n return self.processJsonp(result)\n }\n return resultHandler(result)\n },\n // this get call when it's not 200\n err => {\n self.cleanUp()\n console.error(err)\n throw new JsonqlServerError('Server side error', err)\n }\n )\n }\n\n /**\n * Get the headers inject into the call\n * @return {object} headers\n */\n getHeaders() {\n if (this.opts.enableAuth) {\n return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader)\n }\n return merge({}, DEFAULT_HEADER, this.extraHeader)\n }\n\n /**\n * Post http call operation to clean up things we need\n */\n cleanUp() {\n this.extraHeader = {}\n this.extraParams = {}\n }\n\n /**\n * GET for contract only\n * @return {promise} resolve the contract\n */\n getRemoteContract() {\n if (this.opts.showContractDesc) {\n this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM)\n }\n return this.request({}, {method: 'GET'}, this.contractHeader)\n .then(clientErrorsHandler)\n .then(result => {\n this.log('get contract result', result)\n // when refresh the window the result is different!\n // @TODO need to check the Koa side about why is that\n // also it should set a flag if we want the description or not\n if (result.cache && result.contract) {\n return result.contract;\n }\n // just the normal result\n return result\n })\n .catch(err => {\n console.error('getRemoteContract err', err)\n throw new JsonqlServerError('getRemoteContract', err)\n })\n }\n\n /**\n * POST to server - query\n * @param {object} name of the resolver\n * @param {array} args arguments\n * @return {object} promise resolve to the resolver return\n */\n query(name, args = []) {\n return this.request(createQuery(name, args))\n .then(clientErrorsHandler)\n }\n\n /**\n * PUT to server - mutation\n * @param {string} name of resolver\n * @param {object} payload what it said\n * @param {object} conditions what it said\n * @return {object} promise resolve to the resolver return\n */\n mutation(name, payload = {}, conditions = {}) {\n return this.request(createMutation(name, payload, conditions), {method: PUT})\n .then(clientErrorsHandler)\n }\n\n}\n","// all the contract related methods will be here\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { timestamp } from 'jsonql-utils/src/timestamp'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { ENDPOINT_TABLE, CLS_CONTRACT_NAME } from '../utils'\nimport { localStore } from '../stores'\nimport HttpClass from './http-cls'\n\n// export\nexport default class ContractClass extends HttpClass {\n\n constructor(opts) {\n super(opts)\n }\n\n /**\n * return the contract public api\n * @return {object} contract\n */\n getContract() {\n const contract = this.readContract()\n this.log('getContract first call', contract)\n return contract ? Promise.resolve(contract)\n : this.getRemoteContract().then(this.storeContract.bind(this))\n }\n\n /**\n * We are changing the way how to auth to get the contract.json\n * Instead of in the url, we will be putting that key value in the header\n * @return {object} header\n */\n get contractHeader() {\n let base = {};\n if (this.opts.contractKey !== false) {\n base[this.opts.contractKeyName] = this.opts.contractKey;\n }\n return base;\n }\n\n /**\n * Save the contract to local store\n * @param {object} contract to save\n * @return {object|boolean} false when its not a contract or contract on OK\n */\n storeContract(contract) {\n // first need to check if the contract is a contract\n if (!isContract(contract)) {\n throw new JsonqlValidationError(`Contract is malformed!`)\n //return false;\n }\n /* @TODO need to rethink how to expired the contract\n let args = [contract]\n if (this.opts.contractExpired) {\n let expired = parseFloat(this.opts.contractExpired)\n if (!isNaN(expired) && expired > 0) {\n args.push(expired)\n }\n }\n // calling the setter\n this.jsonqlContract = args;\n */\n this.lset = {[CLS_CONTRACT_NAME]: contract}\n // return it\n this.log('storeContract return result', contract)\n return contract;\n }\n\n /**\n * return the contract from options or localStore\n * @return {object|boolean} false on not found\n */\n readContract() {\n let contract = isContract(this.opts.contract)\n if (contract !== false) {\n return contract;\n }\n let data = this.lget\n if (data) {\n return data[CLS_CONTRACT_NAME]\n }\n return false;\n }\n}\n","// this is the new auth class that integrate with the jsonql-jwt\n// all the auth related methods will be here\nimport { decodeToken } from 'jsonql-jwt/src/client'\nimport { isNumber } from 'jsonql-params-validator'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { CREDENTIAL_STORAGE_KEY, AUTH_HEADER, BEARER } from 'jsonql-constants'\nimport { CLS_PROFILE_IDX, ZERO_IDX, USERDATA_TABLE } from '../utils'\nimport ContractClass from './contract-cls'\n// export\nexport default class AuthClass extends ContractClass {\n\n constructor(opts) {\n super(opts)\n if (opts.enableAuth) {\n this.setDecoder = decodeToken;\n }\n }\n\n /**\n * for overwrite\n * @param {string} token stored token\n * @return {string} token\n */\n decoder(token) {\n return token;\n }\n\n /**\n * set the profile index\n * @param {number} idx\n */\n set profileIndex(idx) {\n const key = CLS_PROFILE_IDX\n if (isNumber(idx)) {\n this[key] = idx;\n if (this.opts.persistToken) {\n this.lset = {[key]: idx}\n }\n return;\n }\n throw new JsonqlValidationError('profileIndex', `Expect idx to be number but got ${typeof idx}`)\n }\n\n /**\n * get the profile index\n * @return {number} idx\n */\n get profileIndex() {\n const key = CLS_PROFILE_IDX\n if (this.opts.persistToken) {\n const data = this.lget;\n if (data[key]) {\n return data[key]\n }\n }\n return this[key] ? this[key] : ZERO_IDX\n }\n\n /**\n * Return the token from session store\n * @param {number} [idx=false] profile index\n * @return {string} token\n */\n rawAuthToken(idx = false) {\n if (idx !== false) {\n this.profileIndex = idx;\n }\n // this should return from the base\n return this.jsonqlToken; // see base-cls\n }\n\n /**\n * Setter to add a decoder when retrieve user token\n * @param {function} d a decoder\n */\n set setDecoder(d) {\n if (typeof d === 'function') {\n this.decoder = d;\n }\n }\n\n /**\n * getter to return the session or local store set method\n * @param {*} data to save\n * @return {object} set method\n */\n set saveProfile(data) {\n if (this.opts.persistToken) {\n // this.log('--- saveProfile lset ---', data)\n this.lset = data\n } else {\n // this.log('--- saveProfile sset ---', data)\n this.sset = data\n }\n }\n\n /**\n * getter to return the session or local store get method\n * @return {object} get method\n */\n get readProfile() {\n return this.opts.persistToken ? this.lget : this.sget\n }\n\n // these were in the base class before but it should be here\n /**\n * save token\n * @param {string} token to store\n * @return {string|boolean} false on failed\n */\n set jsonqlToken(token) {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n // @TODO also have to make sure the token is not already existed!\n let tokens = (data && data[key]) ? data[key] : []\n tokens.push(token)\n this.saveProfile = {[key]: tokens}\n // store the userdata\n this.jsonqlUserdata = this.decoder(token)\n }\n\n /**\n * Jsonql token getter\n * 1.5.1 each token associate with the same profileIndex\n * @return {string|boolean} false when failed\n */\n get jsonqlToken() {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex])\n return data[key][this.profileIndex]\n }\n return false\n }\n\n /**\n * this one will use the sessionStore\n * basically we hook this onto the token store and decode it to store here\n * we only store one decoded user data at a time, but the token can be multiple\n */\n set jsonqlUserdata(userdata) {\n this.sset = {[USERDATA_TABLE]: userdata}\n }\n\n /**\n * this one store in the session store\n * get login userdata decoded jwt\n * 1.5.1 each userdata associate with the same profileIndex\n * @return {object|null}\n */\n get jsonqlUserdata() {\n const data = this.sget\n return data ? data[USERDATA_TABLE] : false\n }\n\n /**\n * Construct the auth header\n * @return {object} header\n */\n getAuthHeader() {\n const token = this.jsonqlToken // only call the getter to get the default one\n return token ? {[this.opts.AUTH_HEADER]: `${BEARER} ${token}`} : {};\n }\n\n /**\n * return all the stored token and decode it\n * @param {number} [idx=false] profile index\n * @return {array|boolean|string} false not found or array\n */\n getProfiles(idx = false) {\n const self = this; // just in case the scope problem\n const data = self.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n if (idx !== false && isNumber(idx)) {\n return data[key][idx] || false\n }\n return data[key].map(self.decoder.bind(self))\n }\n return false\n }\n\n /**\n * call after the login\n * @param {string} token return from server\n * @return {object} decoded token to userdata object\n */\n postLoginAction(token) {\n this.jsonqlToken = token\n return token\n }\n\n /**\n * call after the logout @TODO\n */\n postLogoutAction(...args) {\n console.info(`postLogoutAction`, args)\n }\n}\n","// this the core of the internal storage management\nimport { CREDENTIAL_STORAGE_KEY } from 'jsonql-constants'\n// import { isObject, isArray } from 'jsonql-params-validator'\n// import { JsonqlValidationError } from 'jsonql-errors'\n// import { timestamp } from 'jsonql-utils/src/timestamp'\n// import { inArray } from 'jsonql-utils/src/generic'\nimport { USERDATA_TABLE } from '../utils'\nimport AuthCls from './auth-cls'\n\n// This class will only focus on the storage system\nexport default class JsonqlBaseClient extends AuthCls {\n // change the order of the interface in 1.4.10 to match up the top level\n constructor(fly, opts) {\n // change at 1.4.10 pass it directly without init it\n this.fly = fly;\n super(opts)\n }\n\n /**\n * construct the end point\n * @return {string} the end point to call\n */\n get jsonqlEndpoint() {\n const baseUrl = this.opts.hostname || ''\n return [baseUrl, this.opts.jsonqlPath].join('/')\n }\n\n /**\n * simple log\n */\n log(...args) {\n if (this.opts.debugOn === true) {\n Reflect.apply(console.info, console, args)\n }\n }\n\n}\n","// export interface\n// @public\nimport JsonqlBaseClient from './base-cls'\n\nexport default JsonqlBaseClient\n","// breaking out the inner methods generator in here\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { LOGOUT_NAME, LOGIN_NAME, KEY_WORD } from 'jsonql-constants'\nimport { chainFns } from 'jsonql-utils/src/chain-fns'\nimport { injectToFn } from 'jsonql-utils/src/obj-define-props'\n\n/**\n * generate authorisation specific methods\n * @param {object} jsonqlInstance instance of this\n * @param {string} name of method\n * @param {object} opts configuration\n * @param {object} contract to match\n * @return {function} for use\n */\nconst authMethodGenerator = (jsonqlInstance, name, opts, contract) => {\n return (...args) => {\n const params = contract.auth[name].params;\n const values = params.map((p, i) => args[i])\n const header = args[params.length] || {};\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [name, values, header])\n )\n .catch(finalCatch)\n }\n}\n\n/**\n * Break up the different type each - create query methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let query = {}\n for (let queryFn in contract.query) {\n // to keep it clean we use a param to id the auth method\n // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn;\n // generate the query method\n query = injectToFn(query, queryFn, function queryFnHandler(...args) {\n const params = contract.query[queryFn].params;\n const _args = params.map((param, i) => args[i])\n // debug('query', queryFn, _params);\n // @TODO this need to change to a different way to add an extra header\n const header = {}\n // @TODO validate against the type\n return validateAsync(_args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [queryFn, _args, header])\n )\n .catch(finalCatch)\n })\n }\n obj.query = query;\n // create an alias to the helloWorld method\n obj.helloWorld = query.helloWorld;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create mutation methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let mutation = {}\n // process the mutation, the reason the mutation has a fixed number of parameters\n // there is only the payload, and conditions parameters\n // plus a header at the end\n for (let mutationFn in contract.mutation) {\n mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header = {}) {\n const args = [payload, conditions];\n const params = contract.mutation[mutationFn].params;\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .mutation\n .apply(jsonqlInstance, [mutationFn, payload, conditions, header])\n )\n .catch(e => {\n console.error('--- mutation fn catch ---', e)\n return finalCatch(e)\n })\n })\n }\n obj.mutation = mutation;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create auth methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createAuthMethods = (obj, jsonqlInstance, ee, config, contract) => {\n if (config.enableAuth && contract.auth) {\n let auth = {} // v1.3.1 add back the auth prop name in contract\n const { loginHandlerName, logoutHandlerName } = config;\n if (contract.auth[loginHandlerName]) {\n // changing to the name the config specify\n auth[loginHandlerName] = function loginHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance))\n .then(token => {\n ee.$trigger(LOGIN_NAME, token)\n return token;\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) {\n auth[logoutHandlerName] = function logoutHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance))\n .then(r => {\n ee.$trigger(LOGOUT_NAME, r)\n return r;\n })\n }\n } else {\n auth[logoutHandlerName] = function logoutHandlerFn() {\n jsonqlInstance.postLogoutAction(KEY_WORD)\n ee.$trigger(LOGOUT_NAME, KEY_WORD)\n }\n }\n obj.auth = auth;\n }\n\n return obj;\n}\n\n/**\n * Here just generate the methods calls\n * @param {object} jsonqlInstance what it said\n * @param {object} ee event emitter\n * @param {object} config configuration\n * @param {object} contract the map\n * @return {object} with mapped methods\n */\nexport function methodsGenerator(jsonqlInstance, ee, config, contract) {\n let obj = {}\n const executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods)\n return executor(obj, jsonqlInstance, ee, config, contract)\n}\n","// Generate the resolver for developer to use\n\n// @TODO when enableAuth we need to add one extra check\n// before the resolver call make it to the core\n// which is checking the login state, if the developer\n// is calling a private method without logging in\n// then we should throw the JsonqlForbiddenError at this point\n// instead of making a round trip to the server\nimport { LOGOUT_NAME, ISSUER_NAME, KEY_WORD } from 'jsonql-constants'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\n\nimport { methodsGenerator } from './methods-generator'\n\n/**\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} config options\n * @param {object} contract the contract\n * @param {object} ee eventEmitter\n * @return {object} constructed functions call\n */\nconst generator = (jsonqlInstance, config, contract, ee) => {\n // V1.3.0 - now everything wrap inside this method\n let client = methodsGenerator(jsonqlInstance, ee, config, contract)\n // create the rest of the methods\n if (config.enableAuth) {\n /**\n * new method to allow retrieve the current login user data\n * @TODO allow to pass an id to switch to different userdata\n * @return {*} userdata\n */\n client.userdata = () => jsonqlInstance.jsonqlUserdata;\n // allow getting the token for valdiate agains the socket\n // if it's not require auth there is no point of calling getToken\n client.getToken = (idx = false) => jsonqlInstance.rawAuthToken(idx);\n // switch profile or read back what is the currenct index\n client.profileIndex = (idx = false) => {\n if (idx === false) {\n return jsonqlInstance.profileIndex\n }\n jsonqlInstance.profileIndex = idx\n }\n // new in 1.5.1 to return different profiles\n client.getProfiles = (idx = false) => jsonqlInstance.getProfiles(idx);\n }\n // this will pass to the ws-client if needed\n // client.eventEmitter = ee;\n // this will require a param\n if (config.exposeContract) {\n // 1.4.0 change from the get (raw) to the getContract cache and raw version\n client.getContract = () => jsonqlInstance.getContract()\n }\n // allow developer to access the store api\n if (config.exposeStore) {\n // @TODO in 1.5.2\n client.tmpSave = data => {}\n client.tmpGet = (key = false) => {}\n client.tmpDel = (key = false) => {}\n\n client.persistSave = data => {}\n client.persistGet = (key = false) => {}\n client.persistDel = (key = false) => {}\n }\n // this is for the ws to use later - but this could be dangerous because it's expose the internal\n client.eventEmitter = ee;\n client.version = '__VERSION__';\n // use this method then we can hook into the debugOn at the same time\n client.log = (...args) => Reflect.apply(jsonqlInstance.log, jsonqlInstance, ['[DEV DEBUG]'].concat(args))\n // output\n return client;\n}\n// export\nexport default generator\n","// all the client configuration options here\nimport {\n JSONQL_PATH,\n CONTENT_TYPE,\n BEARER,\n CLIENT_STORAGE_KEY,\n CLIENT_AUTH_KEY,\n CONTRACT_KEY_NAME,\n AUTH_HEADER,\n ISSUER_NAME,\n LOGOUT_NAME,\n BOOLEAN_TYPE,\n STRING_TYPE,\n NUMBER_TYPE,\n DEFAULT_HEADER\n} from 'jsonql-constants'\nimport { createConfig } from 'jsonql-params-validator'\nexport const constProps = {\n contract: false,\n MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong?\n CONTENT_TYPE,\n BEARER,\n AUTH_HEADER\n}\n\n// grab the localhost name and put into the hostname as default\nconst getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n return null\n }\n}\n\nexport const appProps = {\n\n hostname: createConfig(getHostName(), [STRING_TYPE]), // required the hostname\n jsonqlPath: createConfig(JSONQL_PATH, [STRING_TYPE]), // The path on the server\n\n loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]),\n logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]),\n // add to koa v1.3.0 - this might remove in the future\n enableJsonp: createConfig(false, [BOOLEAN_TYPE]),\n enableAuth: createConfig(false, [BOOLEAN_TYPE]),\n // enable useJwt by default @TODO replace with something else and remove them later\n useJwt: createConfig(true, [BOOLEAN_TYPE]),\n // when true then store infinity or pass a time in seconds then we check against\n // the token date of creation\n persistToken: createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE]),\n // the header\n // v1.2.0 we are using this option during the dev\n // so it won't save anything to the localstorage and fetch a new contract\n // whenever the browser reload\n useLocalstorage: createConfig(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage\n storageKey: createConfig(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage\n authKey: createConfig(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage\n contractExpired: createConfig(0, [NUMBER_TYPE]),// -1 always fetch contract,\n // 0 never expired,\n // > 0 then compare the timestamp with the current one to see if we need to get contract again\n // useful during development\n keepContract: createConfig(true, [BOOLEAN_TYPE]),\n exposeContract: createConfig(false, [BOOLEAN_TYPE]),\n exposeStore: createConfig(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn \n // @1.2.1 new option for the contract-console to fetch the contract with description\n showContractDesc: createConfig(false, [BOOLEAN_TYPE]),\n contractKey: createConfig(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this\n contractKeyName: createConfig(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs\n enableTimeout: createConfig(false, [BOOLEAN_TYPE]), // @TODO\n timeout: createConfig(5000, [NUMBER_TYPE]), // 5 seconds\n returnInstance: createConfig(false, [BOOLEAN_TYPE]),\n allowReturnRawToken: createConfig(false, [BOOLEAN_TYPE]),\n debugOn: createConfig(false, [BOOLEAN_TYPE])\n}\n","// we must ensure the user passing the correct options\n// therefore we need to validate against the properties as well\n\nimport { appProps, constProps } from './base-options'\nimport { checkConfigAsync } from 'jsonql-params-validator'\n\nexport default function checkOptionsAsync(config) {\n let { contract } = config;\n return checkConfigAsync(config, appProps, constProps)\n .then(opts => {\n opts.contract = contract;\n return opts;\n })\n}\n","// export interface\nimport checkOptionsAsyncLocal from './check-options-async'\nimport checkOptionsLocal from './check-options'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport { objHasProp } from 'jsonql-utils/src/obj-define-props'\n/**\n * 1.5.0 overload the orginal functions to pass over the check\n */\nfunction checkOptionsAsync(config) {\n return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsyncLocal(config)\n}\n\n// sync version without needing the promise\nfunction checkOptions(config) {\n return objHasProp(config, CHECKED_KEY) ? config : checkOptionsLocal(config)\n}\n\nexport {\n checkOptionsAsync,\n checkOptions\n}\n","// this is new for the flyio and normalize the name from now on\nimport JsonqlBaseClient from './base'\nimport generator from './core/jsonql-api-generator'\nimport { checkOptionsAsync } from './options'\nimport { getContractFromConfig } from './utils'\n\n/**\n * Main interface for jsonql fetch api\n * @param {object} ee EventEmitter\n * @param {object} config\n * @param {object} fly this is really pain in the backside ... long story\n * @return {object} jsonql client\n */\nexport default function(ee, config = {}, fly) {\n return checkOptionsAsync(config)\n .then(opts => (\n {\n baseClient: new JsonqlBaseClient(fly, opts),\n opts: opts\n }\n ))\n .then( ({baseClient, opts}) => (\n getContractFromConfig(baseClient, opts.contract)\n .then(contract => generator(baseClient, opts, contract, ee))\n )\n )\n}\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n\nexport default class SuspendClass {\n\n constructor() {\n // suspend, release and queue\n this.__suspend__ = null;\n this.queueStore = new Set()\n /*\n this.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n })\n */\n }\n\n /**\n * setter to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n set $suspend(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend__;\n this.__suspend__ = value;\n this.logger('($suspend)', `Change from ${lastValue} --> ${value}`)\n if (lastValue === true && value === false) {\n setTimeout(() => {\n this.release()\n }, 1)\n }\n } else {\n throw new Error(`$suspend only accept Boolean value!`)\n }\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {any} value\n * @return {Boolean} true when added or false when it's not\n */\n $queue(...args) {\n if (this.__suspend__ === true) {\n this.logger('($queue)', 'added to $queue', args)\n // there shouldn't be any duplicate ...\n this.queueStore.add(args)\n }\n return this.__suspend__;\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size;\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n release() {\n let size = this.queueStore.size\n this.logger('(release)', `Release was called ${size}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('queue', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport genHaskKey from './hash-code'\nimport SuspendClass from './suspend'\n\nexport default class NbEventServiceBase extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger;\n }\n this.keep = config.keep;\n // for the $done setter\n this.result = config.keep ? [] : null;\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (typeof e !== 'string') {\n this.logger('(validateEvt)', e)\n throw new Error(`event name must be string type!`)\n }\n })\n return true;\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n return true;\n }\n }\n throw new Error(`callback required to be function type!`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n const types = ['on', 'only', 'once', 'onlyOnce']\n return !!types.filter(t => type === t).length;\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run)', callback, payload, ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName]; // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger('(takeFromStore)', `has ${evt}`, content)\n store.delete(evt)\n return content;\n }\n return false;\n }\n throw new Error(`${storeName} is not supported!`)\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n let fnSet;\n if (store.has(evt)) {\n this.logger('(addToStore)', `${evt} existed`)\n fnSet = store.get(evt)\n } else {\n this.logger('(addToStore)', `create new Set for ${evt}`)\n // this is new\n fnSet = new Set()\n }\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args;\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger('(addToStore)', `insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(l => {\n let [hash,] = l;\n if (hash === args[0]) {\n return true;\n }\n return false;\n }).length;\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true;\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list;\n return type !== t;\n }).length;\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n this.logger('(checkTypeInLazyStore)', store)\n if (store) {\n return !!Array\n .from(store)\n .filter(l => {\n let [,,t] = l;\n return t !== type;\n }).length\n }\n return false;\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger('(addToNormalStore)', evt, type, 'try to add to normal store')\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n this.logger('(addToNormalStore)', `${type} can add to ${evt} normal store`)\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store;\n return size;\n }\n return false;\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store;\n return size;\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg];\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n return genHaskKey(fn.toString()) + '';\n }\n}\n","// The top level\nimport NbStoreService from './store-service'\n// export\nexport default class EventService extends NbStoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on';\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger('($on)', `${evt} callback is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger('($on)', `${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0;\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($on)`, `call run on ${evt}`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n return size;\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n const type = 'once';\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (lazyStoreContent === false) {\n this.logger('($once)', `${evt} not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, type, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger('($once)', `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'only';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($only)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($only)', `${evt} found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( l => {\n const [ payload, ctx, t ] = l;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($only)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n })\n }\n return added;\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD added in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'onlyOnce';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== 'onlyOnce') {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($onlyOnce)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added;\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {}\n */\n $replace(evt, callback, context = null, type = 'on') {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n this.logger(`($replace)`, evt, callback)\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0;\n // first check the normal store\n let nStore = this.normalStore;\n this.logger('($trigger)', 'normalStore', nStore)\n if (nStore.has(evt)) {\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n this.logger('($trigger)', evt, 'found; add to queue: ', added)\n if (added === true) {\n this.logger('($trigger)', evt, 'not executed. Exit now.')\n return false; // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length;\n let hasOnce = false;\n let hasOnly = false;\n for (let i=0; i < ctn; ++i) {\n ++found;\n // this.logger('found', found)\n let [ _, callback, ctx, type ] = nSet[i]\n this.logger(`($trigger)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n if (type === 'once' || type === 'onlyOnce') {\n hasOnce = true;\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found;\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found;\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter around\n * @param {string} evt event name\n * @param {*} params pass to the callback\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, params, type = false, context = null) {\n let args = [evt, params, context, type]\n return Reflect.apply(this.$trigger, this, args)\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n let found = false;\n stores.forEach(store => {\n if (store.has(evt)) {\n found = true;\n this.logger('($off)', evt)\n store.delete(evt)\n }\n })\n return found;\n }\n\n /**\n * return all the listener from the event\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n this.validateEvt(evt)\n let store = this.normalStore;\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l;\n }\n let [key, callback, ] = l;\n return callback;\n })\n }\n return false;\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done)', 'value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value;\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n if (this.keep) {\n this.logger('(get $done)', this.result)\n return this.result[this.result.length - 1]\n }\n return this.result;\n }\n\n\n}\n","// default\nimport NBEventService from './src/event-service'\n\nexport default NBEventService\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// output\nexport default function(debugOn) {\n let logger = debugOn ? (...args) => {\n args.unshift('[NBS]')\n console.log.apply(null, args)\n }: undefined;\n return new NBEventService({ logger })\n}\n","// main export interface\nimport {\n jsonqlAsync,\n ee as getEventEmitter\n} from './src'\n/**\n * When pass a static contract then it return a static interface\n * otherwise it will become the async interface\n * @param {object} fly the http engine - already init object not the class!\n * @param {object} config configuration\n * @return {object} jsonqlClient\n */\nexport default function jsonqlClient(fly, config) {\n const ee = getEventEmitter(config.debugOn)\n return jsonqlAsync(ee, config, fly)\n}\n","// this one will bring the fly.js in\n// also the built jsonql-client.umd.js together\n// init it @TODO placeholder this Fly import and switch using the NODE_ENV\n// because we are going to create one for wechat and one for node\n\nimport Fly from 'flyio/dist/npm/fly'\nimport jsonqlClient from './index'\n\nexport default function(config = {}) {\n return jsonqlClient(new Fly(), config)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"jsonql-client.umd.js","sources":["../node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"w37CAAA"} \ No newline at end of file diff --git a/packages/http-client/package.json b/packages/http-client/package.json index 4b047b50..4316a7f1 100755 --- a/packages/http-client/package.json +++ b/packages/http-client/package.json @@ -65,7 +65,7 @@ "dependencies": { "flyio": "^0.6.14", "jsonql-constants": "^1.8.13", - "jsonql-errors": "^1.1.8", + "jsonql-errors": "^1.1.10", "jsonql-jwt": "^1.3.6", "jsonql-params-validator": "^1.5.0", "jsonql-utils": "^0.9.2", diff --git a/packages/http-client/src/base/base-cls.js b/packages/http-client/src/base/base-cls.js index e9f975a9..798cc4d4 100644 --- a/packages/http-client/src/base/base-cls.js +++ b/packages/http-client/src/base/base-cls.js @@ -4,7 +4,7 @@ import { CREDENTIAL_STORAGE_KEY } from 'jsonql-constants' // import { JsonqlValidationError } from 'jsonql-errors' // import { timestamp } from 'jsonql-utils/src/timestamp' // import { inArray } from 'jsonql-utils/src/generic' -import { USERDATA_TABLE } from '../utils' +import { USERDATA_TABLE, LOG_ERROR_SWITCH } from '../utils' import AuthCls from './auth-cls' // This class will only focus on the storage system @@ -30,7 +30,9 @@ export default class JsonqlBaseClient extends AuthCls { */ log(...args) { if (this.opts.debugOn === true) { - Reflect.apply(console.info, console, args) + const fns = ['info', 'error'] + const idx = (args[0] === LOG_ERROR_SWITCH) ? 1 : 0 + Reflect.apply(console[fns[idx]], console, args.splice(0, idx)) } } diff --git a/packages/http-client/src/base/contract-cls.js b/packages/http-client/src/base/contract-cls.js index 470b2830..70595062 100644 --- a/packages/http-client/src/base/contract-cls.js +++ b/packages/http-client/src/base/contract-cls.js @@ -46,19 +46,7 @@ export default class ContractClass extends HttpClass { // first need to check if the contract is a contract if (!isContract(contract)) { throw new JsonqlValidationError(`Contract is malformed!`) - //return false; } - /* @TODO need to rethink how to expired the contract - let args = [contract] - if (this.opts.contractExpired) { - let expired = parseFloat(this.opts.contractExpired) - if (!isNaN(expired) && expired > 0) { - args.push(expired) - } - } - // calling the setter - this.jsonqlContract = args; - */ this.lset = {[CLS_CONTRACT_NAME]: contract} // return it this.log('storeContract return result', contract) diff --git a/packages/http-client/src/base/http-cls.js b/packages/http-client/src/base/http-cls.js index 4604534b..a9d4f73f 100644 --- a/packages/http-client/src/base/http-cls.js +++ b/packages/http-client/src/base/http-cls.js @@ -12,7 +12,7 @@ import { JsonqlValidationError, JsonqlServerError, JsonqlError, - // clientErrorsHandler + clientErrorsHandler } from 'jsonql-errors' import { API_REQUEST_METHODS, @@ -20,35 +20,7 @@ import { JSONP_CALLBACK_NAME, SHOW_CONTRACT_DESC_PARAM } from 'jsonql-constants' - -// @DEBUG -import * as errors from 'jsonql-errors' -import { isObjectHasKey } from 'jsonql-utils/src/generic' -/** - * It will ONLY have our own jsonql specific implement check - * @param {object} result the server return result - * @return {object} this will just throw error - */ -function clientErrorsHandler(result) { - if (isObjectHasKey(result, 'error')) { - const { error } = result; - const { className, name } = error; - const errorName = className || name; - // just throw the whole thing back - const msg = error.message || NO_ERROR_MSG; - const detail = error.detail || error; - console.info('--- errorName ---', errorName, errors) - - if (errorName && errors[errorName]) { - throw new errors[className](msg, detail) - } - throw new JsonqlError(msg, detail) - } - // pass through to the next - return result; -} - - +import { LOG_ERROR_SWITCH } from '../utils' // extract the one we need const [ POST, PUT ] = API_REQUEST_METHODS @@ -152,7 +124,7 @@ export default class HttpClass extends StoreClass { // this get call when it's not 200 err => { self.cleanUp() - console.error(err) + this.log(LOG_ERROR_SWITCH, err) throw new JsonqlServerError('Server side error', err) } ) @@ -199,7 +171,7 @@ export default class HttpClass extends StoreClass { return result }) .catch(err => { - console.error('getRemoteContract err', err) + this.log(LOG_ERROR_SWITCH, 'getRemoteContract err', err) throw new JsonqlServerError('getRemoteContract', err) }) } diff --git a/packages/http-client/src/core/methods-generator.js b/packages/http-client/src/core/methods-generator.js index 1fa16aa4..72ac5cc9 100644 --- a/packages/http-client/src/core/methods-generator.js +++ b/packages/http-client/src/core/methods-generator.js @@ -28,7 +28,7 @@ const authMethodGenerator = (jsonqlInstance, name, opts, contract) => { .query .apply(jsonqlInstance, [name, values, header]) ) - .catch(finalCatch) + // .catch(finalCatch) } } @@ -59,7 +59,7 @@ const createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => { .query .apply(jsonqlInstance, [queryFn, _args, header]) ) - .catch(finalCatch) + // .catch(finalCatch) }) } obj.query = query; @@ -91,10 +91,6 @@ const createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => { .mutation .apply(jsonqlInstance, [mutationFn, payload, conditions, header]) ) - .catch(e => { - console.error('--- mutation fn catch ---', e) - return finalCatch(e) - }) }) } obj.mutation = mutation; diff --git a/packages/http-client/src/utils.js b/packages/http-client/src/utils.js index 1cf4d294..34fd9091 100644 --- a/packages/http-client/src/utils.js +++ b/packages/http-client/src/utils.js @@ -29,6 +29,7 @@ const CLS_LOCAL_STORE_NAME = 'localStore' const CLS_SESS_STORE_NAME = 'sessionStore' const CLS_CONTRACT_NAME = 'contract' const CLS_PROFILE_IDX = 'prof_idx' +const LOG_ERROR_SWITCH = '__error__' const ZERO_IDX = 0 // export export { @@ -40,5 +41,6 @@ export { CLS_SESS_STORE_NAME, CLS_CONTRACT_NAME, CLS_PROFILE_IDX, + LOG_ERROR_SWITCH, ZERO_IDX } diff --git a/packages/http-client/static.js b/packages/http-client/static.js index d99694af..ae8b23c5 100644 --- a/packages/http-client/static.js +++ b/packages/http-client/static.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClientStatic=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b="onResult",_="onError",m=Array.isArray,w="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},j="object"==typeof w&&w&&w.Object===Object&&w,S="object"==typeof self&&self&&self.Object===Object&&self,O=j||S||Function("return this")(),k=O.Symbol,A=Object.prototype,E=A.hasOwnProperty,T=A.toString,x=k?k.toStringTag:void 0;var P=Object.prototype.toString;var q="[object Null]",C="[object Undefined]",$=k?k.toStringTag:void 0;function z(t){return null==t?void 0===t?C:q:$&&$ in Object(t)?function(t){var e=E.call(t,x),r=t[x];try{t[x]=void 0;var n=!0}catch(t){}var o=T.call(t);return n&&(e?t[x]=r:delete t[x]),o}(t):function(t){return P.call(t)}(t)}function N(t,e){return function(r){return t(e(r))}}var M=N(Object.getPrototypeOf,Object);function R(t){return null!=t&&"object"==typeof t}var I="[object Object]",F=Function.prototype,J=Object.prototype,U=F.toString,H=J.hasOwnProperty,L=U.call(Object);function D(t){if(!R(t)||z(t)!=I)return!1;var e=M(t);if(null===e)return!0;var r=H.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&U.call(r)==L}function K(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&tt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var gt=function(t){return m(t)?t:[t]},yt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},bt=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},_t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),mt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),xt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),Pt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),qt=Object.freeze({__proto__:null,Jsonql406Error:_t,Jsonql500Error:mt,JsonqlAuthorisationError:wt,JsonqlContractAuthError:jt,JsonqlResolverAppError:St,JsonqlResolverNotFoundError:Ot,JsonqlEnumError:kt,JsonqlTypeError:At,JsonqlCheckerError:Et,JsonqlValidationError:Tt,JsonqlError:xt,JsonqlServerError:Pt}),Ct=xt,$t=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function zt(t){if($t(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&qt[o])throw new qt[r](i,a);throw new Ct(i,a)}return t}function Nt(t){if(Array.isArray(t))throw new Tt("",t);var e=t.message||y,r=t.detail||t;switch(!0){case t instanceof _t:throw new _t(e,r);case t instanceof mt:throw new mt(e,r);case t instanceof wt:throw new wt(e,r);case t instanceof jt:throw new jt(e,r);case t instanceof St:throw new St(e,r);case t instanceof Ot:throw new Ot(e,r);case t instanceof kt:throw new kt(e,r);case t instanceof At:throw new At(e,r);case t instanceof Et:throw new Et(e,r);case t instanceof Tt:throw new Tt(e,r);case t instanceof Pt:throw new Pt(e,r);default:throw new xt(e,r)}}var Mt=function(t){return!!m(t)||null!=t&&""!==vt(t)},Rt="[object Number]";function It(t){return function(t){return"number"==typeof t||R(t)&&z(t)==Rt}(t)&&t!=+t}var Ft="[object String]";function Jt(t){return"string"==typeof t||!m(t)&&R(t)&&z(t)==Ft}var Ut=function(t){return!Jt(t)&&!It(parseFloat(t))},Ht=function(t){return""!==vt(t)&&Jt(t)},Lt=function(t){return null!=t&&"boolean"==typeof t},Dt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==vt(t)&&(!1===e||!0===e&&null!==t)},Kt=s,Bt=f,Vt=l,Gt=p,Wt=h,Yt=d,Qt="continue",Xt=function(t){switch(t){case"number":return Ut;case"string":return Ht;case"boolean":return Lt;default:return Dt}},Zt=function(t,e){return void 0===e&&(e=""),!!m(t)&&(""===e||""===vt(e)||!(t.filter((function(t){return!Xt(e)(t)})).length>0))},te=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ee=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!Xt(e)(t)})).length)})).length:e.length>e.filter((function(t){return!Zt(r,t)})).length};var re,ne=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[re?a:++n];if(!1===e(o[u],u,o))break}return t};var oe="[object Arguments]";function ie(t){return R(t)&&z(t)==oe}var ae=Object.prototype,ue=ae.hasOwnProperty,ce=ae.propertyIsEnumerable,se=ie(function(){return arguments}())?ie:function(t){return R(t)&&ue.call(t,"callee")&&!ce.call(t,"callee")};var fe="object"==typeof exports&&exports&&!exports.nodeType&&exports,le=fe&&"object"==typeof module&&module&&!module.nodeType&&module,pe=le&&le.exports===fe?O.Buffer:void 0,he=(pe?pe.isBuffer:void 0)||function(){return!1},de=9007199254740991,ve=/^(?:0|[1-9]\d*)$/;function ge(t,e){var r=typeof t;return!!(e=null==e?de:e)&&("number"==r||"symbol"!=r&&ve.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=ye}var _e={};_e["[object Float32Array]"]=_e["[object Float64Array]"]=_e["[object Int8Array]"]=_e["[object Int16Array]"]=_e["[object Int32Array]"]=_e["[object Uint8Array]"]=_e["[object Uint8ClampedArray]"]=_e["[object Uint16Array]"]=_e["[object Uint32Array]"]=!0,_e["[object Arguments]"]=_e["[object Array]"]=_e["[object ArrayBuffer]"]=_e["[object Boolean]"]=_e["[object DataView]"]=_e["[object Date]"]=_e["[object Error]"]=_e["[object Function]"]=_e["[object Map]"]=_e["[object Number]"]=_e["[object Object]"]=_e["[object RegExp]"]=_e["[object Set]"]=_e["[object String]"]=_e["[object WeakMap]"]=!1;var me,we="object"==typeof exports&&exports&&!exports.nodeType&&exports,je=we&&"object"==typeof module&&module&&!module.nodeType&&module,Se=je&&je.exports===we&&j.process,Oe=function(){try{var t=je&&je.require&&je.require("util").types;return t||Se&&Se.binding&&Se.binding("util")}catch(t){}}(),ke=Oe&&Oe.isTypedArray,Ae=ke?(me=ke,function(t){return me(t)}):function(t){return R(t)&&be(t.length)&&!!_e[z(t)]},Ee=Object.prototype.hasOwnProperty;function Te(t,e){var r=m(t),n=!r&&se(t),o=!r&&!n&&he(t),i=!r&&!n&&!o&&Ae(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},Ke.prototype.set=function(t,e){var r=this.__data__,n=Le(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var Be,Ve=O["__core-js_shared__"],Ge=(Be=/[^.]+$/.exec(Ve&&Ve.keys&&Ve.keys.IE_PROTO||""))?"Symbol(src)_1."+Be:"";var We=Function.prototype.toString;function Ye(t){if(null!=t){try{return We.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Qe=/^\[object .+?Constructor\]$/,Xe=Function.prototype,Ze=Object.prototype,tr=Xe.toString,er=Ze.hasOwnProperty,rr=RegExp("^"+tr.call(er).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function nr(t){return!(!$e(t)||function(t){return!!Ge&&Ge in t}(t))&&(Ie(t)?rr:Qe).test(Ye(t))}function or(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return nr(r)?r:void 0}var ir=or(O,"Map"),ar=or(Object,"create");var ur="__lodash_hash_undefined__",cr=Object.prototype.hasOwnProperty;var sr=Object.prototype.hasOwnProperty;var fr="__lodash_hash_undefined__";function lr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&mr?new yr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=te(t))?!ee({arg:r},e):!Xt(t)(r))})).length)})).length}return!1},Un=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Jn,null,a);case"array"===t:return!Zt(e.arg);case!1!==(r=te(t)):return!ee(e,r);default:return!Xt(t)(e.arg)}},Hn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Ln=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!Zt(e))throw new xt("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!Zt(t))throw new xt("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Hn(t,a):t,index:r,param:a,optional:i}}));default:throw new xt("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Mt(e)&&!(r.type.length>r.type.filter((function(e){return Un(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Un(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Dn=function(){try{var t=or(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function Kn(t,e,r){"__proto__"==e&&Dn?Dn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function Bn(t,e,r){(void 0===r||He(t[e],r))&&(void 0!==r||e in t)||Kn(t,e,r)}var Vn="object"==typeof exports&&exports&&!exports.nodeType&&exports,Gn=Vn&&"object"==typeof module&&module&&!module.nodeType&&module,Wn=Gn&&Gn.exports===Vn?O.Buffer:void 0,Yn=Wn?Wn.allocUnsafe:void 0;function Qn(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new jr(n).set(new jr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var Xn=Object.create,Zn=function(){function t(){}return function(e){if(!$e(e))return{};if(Xn)return Xn(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function to(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var eo=Object.prototype.hasOwnProperty;function ro(t,e,r){var n=t[e];eo.call(t,e)&&He(n,r)&&(void 0!==r||e in t)||Kn(t,e,r)}var no=Object.prototype.hasOwnProperty;function oo(t){if(!$e(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Pe(t),r=[];for(var n in t)("constructor"!=n||!e&&no.call(t,n))&&r.push(n);return r}function io(t){return Fe(t)?Te(t,!0):oo(t)}function ao(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=po)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(lo);function yo(t,e){return go(function(t,e,r){return e=fo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=fo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=bo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!$e(r))return!1;var n=typeof e;return!!("number"==n?Fe(r)&&ge(e,r.length):"string"==n&&e in r)&&He(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,gt(t))}),Reflect.apply(t,null,r))}};function Lo(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function Do(t,e,r,n){void 0===n&&(n=!1);var o=Lo(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var Ko=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return Fo(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch(Nt)}},Bo=function(t,e,r,n,o){var i={},a=function(t){i=Do(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return Fo(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch(Nt)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},Vo=function(t,e,r,n,o){var i={},a=function(t){i=Do(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return Fo(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch(Nt)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Go=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Ko(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Ko(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var Wo=function(t,e){return function(r){for(var n=[],o=arguments.length-1;o-- >0;)n[o]=arguments[o+1];return new Promise((function(o,i){t.$only(bt(e,r,b),o),t.$only(bt(e,r,_),i),t.$trigger(e,{resolverName:r,args:n})}))}},Yo=function(t,e,r){var n=t.$queues,o=r.debugOn;o&&console.info("(validateRegisteredEvents)","storedEvt",n),n.forEach((function(t){var r=t[0],n=t[1].resolverName;if(o&&console.info("(validateRegisteredEvents)",r,n),!e[r][n])throw new Error(r+"."+n+" not existed in contract!")}))};function Qo(t,e,r,n){var o=function(t,e,r,n){return Ho(Bo,Vo,Go)({},t,e,r,n)}(t,e,r,n);Yo(e,n,r);var i=function(t){e.$only(t,(function(r){var n=r.resolverName,i=r.args;o[t][n]?Reflect.apply(o[t][n],null,i).then((function(r){e.$trigger(bt(t,n,b),r)})).catch((function(r){e.$trigger(bt(t,n,_),r)})):console.error(n+" is not defined in the contract!")}))};for(var a in o)i(a);setTimeout((function(){e.$suspend=!1}),1)}var Xo=function(t,e,r,n){n.$suspend=!0,r.then((function(r){Qo(t,n,e,r)}));var o={query:Wo(n,"query"),mutation:Wo(n,"mutation"),auth:Wo(n,"auth"),getToken:function(){return t.rawAuthToken}};return e.exposeContract&&(o.getContract=function(){return t.get()}),e.enableAuth&&(o.userdata=function(){return t.userdata}),o.version="1.5.1",o};function Zo(t){return!!function(t){return D(t)&&(yt(t,r)||yt(t,n)||yt(t,o))}(t)&&t}function ti(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var ei=function(t,e){return void 0===e&&(e={}),Zo(e)?Promise.resolve(e):t.getContract()},ri="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function ni(t){this.message=t}ni.prototype=new Error,ni.prototype.name="InvalidCharacterError";var oi="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new ni("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=ri.indexOf(n);return a};var ii=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(oi(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return oi(e)}};function ai(t){this.message=t}ai.prototype=new Error,ai.prototype.name="InvalidTokenError";var ui=function(t,e){if("string"!=typeof t)throw new ai("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(ii(t.split(".")[r]))}catch(t){throw new ai("Invalid token specified: "+t.message)}},ci=ai;ui.InvalidTokenError=ci;var si,fi,li,pi,hi,di,vi,gi,yi,bi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function _i(t){if(Ht(t))return function(t){var e=t.iat||bi(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new xt("Token has expired on "+r,t)}return t}(ui(t));throw new xt("Token must be a string!")}Jo("HS256",["string"]),Jo(!1,["boolean","number","string"],((si={})[d]="exp",si[f]=!0,si)),Jo(!1,["boolean","number","string"],((fi={})[d]="nbf",fi[f]=!0,fi)),Jo(!1,["boolean","string"],((li={})[d]="iss",li[f]=!0,li)),Jo(!1,["boolean","string"],((pi={})[d]="sub",pi[f]=!0,pi)),Jo(!1,["boolean","string"],((hi={})[d]="iss",hi[f]=!0,hi)),Jo(!1,["boolean"],((di={})[f]=!0,di)),Jo(!1,["boolean","string"],((vi={})[f]=!0,vi)),Jo(!1,["boolean","string"],((gi={})[f]=!0,gi)),Jo(!1,["boolean"],((yi={})[f]=!0,yi));var mi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},wi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var ji=Object.assign?Object.assign:function(t,e,r,n){for(var o=arguments,i=1;i=0;e--){var r=Di().key(e);t(Ki(r),r)}},remove:function(t){return Di().removeItem(t)},clearAll:function(){return Di().clear()}};function Di(){return Hi.localStorage}function Ki(t){return Di().getItem(t)}var Bi=Ai.trim,Vi={name:"cookieStorage",read:function(t){if(!t||!Qi(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Gi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Gi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Wi,remove:Yi,clearAll:function(){Wi((function(t,e){Yi(e)}))}},Gi=Ai.Global.document;function Wi(t){for(var e=Gi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Bi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Yi(t){t&&Qi(t)&&(Gi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Qi(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Gi.cookie)}var Xi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Zi=Ai.bind,ta=Ai.each,ea=Ai.create,ra=Ai.slice,na=function(){var t=ea(oa,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Zi(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Zi(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),ta(r,(function(e,r){t.fire(r,void 0,e)}))}}};var oa={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Zi(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=ra(arguments,1);ta(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},ia=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),aa=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=ia.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=ia.compress(this._serialize(r));t(e,n)}}};var ua=[Li,Vi],ca=[Xi,na,aa],sa=Fi.createStore(ua,ca),fa=Ai.Global;function la(){return fa.sessionStorage}function pa(t){return la().getItem(t)}var ha=[{name:"sessionStorage",read:pa,write:function(t,e){return la().setItem(t,e)},each:function(t){for(var e=la().length-1;e>=0;e--){var r=la().key(e);t(pa(r),r)}},remove:function(t){return la().removeItem(t)},clearAll:function(){return la().clear()}},Vi],da=[Xi,aa],va=Fi.createStore(ha,da),ga=sa,ya=va,ba=function(t){var e;return(e={}).args=t,e};function _a(t,e){var r;return(r={})[t]=e,r[u]=[mi()],r}var ma=function(t){return yt(t,"data")&&!yt(t,"error")?t.data:t},wa=function(t){this.opts=t,this.instanceKey=ti(this.opts.hostname)+"",this.localStore=ga,this.sessionStore=ya},ja={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};wa.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?_o({},o,e):e,r))},wa.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},wa.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},wa.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},ja.lset.set=function(t){return this.__setMethod("localStore",t)},ja.lget.get=function(){return this.__getMethod("localStore")},wa.prototype.ldel=function(t){return this.__delMethod("localStore",t)},wa.prototype.lclear=function(){return this.__clearMethod("localStore")},ja.sset.set=function(t){return this.__setMethod("sessionStore",t)},ja.sget.get=function(){return this.__getMethod("sessionStore")},wa.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},wa.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(wa.prototype,ja);var Sa=c[0],Oa=c[1],ka=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];!0===this.opts.debugOn&&Reflect.apply(console.info,console,t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=_i)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(Io(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new Tt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&Io(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!Zo(t))throw new Tt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=Zo(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=_o({},{_cb:mi()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=_o({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=_o({},{method:Sa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return ma(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=Ro(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ma(o)}),(function(t){throw e.cleanUp(),console.error(t),new Pt("Server side error",t)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?_o({},e,this.getAuthHeader(),this.extraHeader):_o({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=_o({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(zt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(t){throw console.error("getRemoteContract err",t),new Pt("getRemoteContract",t)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Jt(t)&&m(e)){var n=ba(e);return!0===r?n:_a(t,n)}throw new Tt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(zt)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Jt(t))return _a(t,o);throw new Tt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:Oa}).then(zt)},Object.defineProperties(r.prototype,n),r}(wa)))),Aa={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Ea={hostname:Jo(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:Jo("jsonql",["string"]),loginHandlerName:Jo("login",["string"]),logoutHandlerName:Jo("logout",["string"]),enableJsonp:Jo(!1,["boolean"]),enableAuth:Jo(!1,["boolean"]),useJwt:Jo(!0,["boolean"]),persistToken:Jo(!1,["boolean","number"]),useLocalstorage:Jo(!0,["boolean"]),storageKey:Jo("jsonqlstore",["string"]),authKey:Jo("jsonqlauthkey",["string"]),contractExpired:Jo(0,["number"]),keepContract:Jo(!0,["boolean"]),exposeContract:Jo(!1,["boolean"]),exposeStore:Jo(!1,["boolean"]),showContractDesc:Jo(!1,["boolean"]),contractKey:Jo(!1,["boolean"]),contractKeyName:Jo("X-JSONQL-CV-KEY",["string"]),enableTimeout:Jo(!1,["boolean"]),timeout:Jo(5e3,["number"]),returnInstance:Jo(!1,["boolean"]),allowReturnRawToken:Jo(!1,["boolean"]),debugOn:Jo(!1,["boolean"])};function Ta(t){return Lo(t,v)?t:function(t){return Uo(t,Ea,Aa)}(t)}var xa=new WeakMap,Pa=new WeakMap,qa=function(){this.__suspend__=null,this.queueStore=new Set},Ca={$suspend:{configurable:!0},$queues:{configurable:!0}};Ca.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},qa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ca.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},qa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(qa.prototype,Ca);var $a=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){xa.set(this,t)},r.normalStore.get=function(){return xa.get(this)},r.lazyStore.set=function(t){Pa.set(this,t)},r.lazyStore.get=function(){return Pa.get(this)},e.prototype.hashFnToKey=function(t){return ti(t.toString())+""},Object.defineProperties(e.prototype,r),e}(qa));return function(t,e){void 0===e&&(e={});var r,n=e.contract,o=Ta(e),i=new ka(t,o),a=ei(i,n),u=(r=o.debugOn,new $a({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),c=Xo(i,o,a,u);return c.eventEmitter=u,c}})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClientStatic=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b="onResult",_="onError",m=Array.isArray,w="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},j="object"==typeof w&&w&&w.Object===Object&&w,S="object"==typeof self&&self&&self.Object===Object&&self,O=j||S||Function("return this")(),k=O.Symbol,E=Object.prototype,A=E.hasOwnProperty,T=E.toString,x=k?k.toStringTag:void 0;var P=Object.prototype.toString;var q="[object Null]",C="[object Undefined]",$=k?k.toStringTag:void 0;function z(t){return null==t?void 0===t?C:q:$&&$ in Object(t)?function(t){var e=A.call(t,x),r=t[x];try{t[x]=void 0;var n=!0}catch(t){}var o=T.call(t);return n&&(e?t[x]=r:delete t[x]),o}(t):function(t){return P.call(t)}(t)}function N(t,e){return function(r){return t(e(r))}}var M=N(Object.getPrototypeOf,Object);function R(t){return null!=t&&"object"==typeof t}var F="[object Object]",I=Function.prototype,J=Object.prototype,U=I.toString,H=J.hasOwnProperty,L=U.call(Object);function D(t){if(!R(t)||z(t)!=F)return!1;var e=M(t);if(null===e)return!0;var r=H.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&U.call(r)==L}function K(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&tt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var gt=function(t){return m(t)?t:[t]},yt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},bt=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},_t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),mt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),xt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Pt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),qt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),Ct=Object.freeze({__proto__:null,Jsonql406Error:_t,Jsonql500Error:mt,JsonqlForbiddenError:wt,JsonqlAuthorisationError:jt,JsonqlContractAuthError:St,JsonqlResolverAppError:Ot,JsonqlResolverNotFoundError:kt,JsonqlEnumError:Et,JsonqlTypeError:At,JsonqlCheckerError:Tt,JsonqlValidationError:xt,JsonqlError:Pt,JsonqlServerError:qt}),$t=Pt,zt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function Nt(t){if(zt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&Ct[o])throw new Ct[r](i,a);throw new $t(i,a)}return t}var Mt=function(t){return!!m(t)||null!=t&&""!==vt(t)},Rt="[object Number]";function Ft(t){return function(t){return"number"==typeof t||R(t)&&z(t)==Rt}(t)&&t!=+t}var It="[object String]";function Jt(t){return"string"==typeof t||!m(t)&&R(t)&&z(t)==It}var Ut=function(t){return!Jt(t)&&!Ft(parseFloat(t))},Ht=function(t){return""!==vt(t)&&Jt(t)},Lt=function(t){return null!=t&&"boolean"==typeof t},Dt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==vt(t)&&(!1===e||!0===e&&null!==t)},Kt=s,Bt=f,Vt=l,Gt=p,Wt=h,Yt=d,Qt="continue",Xt=function(t){switch(t){case"number":return Ut;case"string":return Ht;case"boolean":return Lt;default:return Dt}},Zt=function(t,e){return void 0===e&&(e=""),!!m(t)&&(""===e||""===vt(e)||!(t.filter((function(t){return!Xt(e)(t)})).length>0))},te=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ee=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!Xt(e)(t)})).length)})).length:e.length>e.filter((function(t){return!Zt(r,t)})).length};var re,ne=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[re?a:++n];if(!1===e(o[u],u,o))break}return t};var oe="[object Arguments]";function ie(t){return R(t)&&z(t)==oe}var ae=Object.prototype,ue=ae.hasOwnProperty,ce=ae.propertyIsEnumerable,se=ie(function(){return arguments}())?ie:function(t){return R(t)&&ue.call(t,"callee")&&!ce.call(t,"callee")};var fe="object"==typeof exports&&exports&&!exports.nodeType&&exports,le=fe&&"object"==typeof module&&module&&!module.nodeType&&module,pe=le&&le.exports===fe?O.Buffer:void 0,he=(pe?pe.isBuffer:void 0)||function(){return!1},de=9007199254740991,ve=/^(?:0|[1-9]\d*)$/;function ge(t,e){var r=typeof t;return!!(e=null==e?de:e)&&("number"==r||"symbol"!=r&&ve.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=ye}var _e={};_e["[object Float32Array]"]=_e["[object Float64Array]"]=_e["[object Int8Array]"]=_e["[object Int16Array]"]=_e["[object Int32Array]"]=_e["[object Uint8Array]"]=_e["[object Uint8ClampedArray]"]=_e["[object Uint16Array]"]=_e["[object Uint32Array]"]=!0,_e["[object Arguments]"]=_e["[object Array]"]=_e["[object ArrayBuffer]"]=_e["[object Boolean]"]=_e["[object DataView]"]=_e["[object Date]"]=_e["[object Error]"]=_e["[object Function]"]=_e["[object Map]"]=_e["[object Number]"]=_e["[object Object]"]=_e["[object RegExp]"]=_e["[object Set]"]=_e["[object String]"]=_e["[object WeakMap]"]=!1;var me,we="object"==typeof exports&&exports&&!exports.nodeType&&exports,je=we&&"object"==typeof module&&module&&!module.nodeType&&module,Se=je&&je.exports===we&&j.process,Oe=function(){try{var t=je&&je.require&&je.require("util").types;return t||Se&&Se.binding&&Se.binding("util")}catch(t){}}(),ke=Oe&&Oe.isTypedArray,Ee=ke?(me=ke,function(t){return me(t)}):function(t){return R(t)&&be(t.length)&&!!_e[z(t)]},Ae=Object.prototype.hasOwnProperty;function Te(t,e){var r=m(t),n=!r&&se(t),o=!r&&!n&&he(t),i=!r&&!n&&!o&&Ee(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},Ke.prototype.set=function(t,e){var r=this.__data__,n=Le(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var Be,Ve=O["__core-js_shared__"],Ge=(Be=/[^.]+$/.exec(Ve&&Ve.keys&&Ve.keys.IE_PROTO||""))?"Symbol(src)_1."+Be:"";var We=Function.prototype.toString;function Ye(t){if(null!=t){try{return We.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Qe=/^\[object .+?Constructor\]$/,Xe=Function.prototype,Ze=Object.prototype,tr=Xe.toString,er=Ze.hasOwnProperty,rr=RegExp("^"+tr.call(er).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function nr(t){return!(!$e(t)||function(t){return!!Ge&&Ge in t}(t))&&(Fe(t)?rr:Qe).test(Ye(t))}function or(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return nr(r)?r:void 0}var ir=or(O,"Map"),ar=or(Object,"create");var ur="__lodash_hash_undefined__",cr=Object.prototype.hasOwnProperty;var sr=Object.prototype.hasOwnProperty;var fr="__lodash_hash_undefined__";function lr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&mr?new yr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=te(t))?!ee({arg:r},e):!Xt(t)(r))})).length)})).length}return!1},Un=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Jn,null,a);case"array"===t:return!Zt(e.arg);case!1!==(r=te(t)):return!ee(e,r);default:return!Xt(t)(e.arg)}},Hn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Ln=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!Zt(e))throw new Pt("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!Zt(t))throw new Pt("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Hn(t,a):t,index:r,param:a,optional:i}}));default:throw new Pt("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Mt(e)&&!(r.type.length>r.type.filter((function(e){return Un(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Un(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Dn=function(){try{var t=or(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function Kn(t,e,r){"__proto__"==e&&Dn?Dn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function Bn(t,e,r){(void 0===r||He(t[e],r))&&(void 0!==r||e in t)||Kn(t,e,r)}var Vn="object"==typeof exports&&exports&&!exports.nodeType&&exports,Gn=Vn&&"object"==typeof module&&module&&!module.nodeType&&module,Wn=Gn&&Gn.exports===Vn?O.Buffer:void 0,Yn=Wn?Wn.allocUnsafe:void 0;function Qn(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new jr(n).set(new jr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var Xn=Object.create,Zn=function(){function t(){}return function(e){if(!$e(e))return{};if(Xn)return Xn(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function to(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var eo=Object.prototype.hasOwnProperty;function ro(t,e,r){var n=t[e];eo.call(t,e)&&He(n,r)&&(void 0!==r||e in t)||Kn(t,e,r)}var no=Object.prototype.hasOwnProperty;function oo(t){if(!$e(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Pe(t),r=[];for(var n in t)("constructor"!=n||!e&&no.call(t,n))&&r.push(n);return r}function io(t){return Ie(t)?Te(t,!0):oo(t)}function ao(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=po)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(lo);function yo(t,e){return go(function(t,e,r){return e=fo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=fo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=bo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!$e(r))return!1;var n=typeof e;return!!("number"==n?Ie(r)&&ge(e,r.length):"string"==n&&e in r)&&He(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,gt(t))}),Reflect.apply(t,null,r))}};function Lo(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function Do(t,e,r,n){void 0===n&&(n=!1);var o=Lo(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var Ko=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return Io(r,i).then((function(){return t.query.apply(t,[e,a,u])}))}},Bo=function(t,e,r,n,o){var i={},a=function(t){i=Do(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return Io(a,i).then((function(){return e.query.apply(e,[t,a,u])}))}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},Vo=function(t,e,r,n,o){var i={},a=function(t){i=Do(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return Io(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])}))}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Go=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Ko(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Ko(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var Wo=function(t,e){return function(r){for(var n=[],o=arguments.length-1;o-- >0;)n[o]=arguments[o+1];return new Promise((function(o,i){t.$only(bt(e,r,b),o),t.$only(bt(e,r,_),i),t.$trigger(e,{resolverName:r,args:n})}))}},Yo=function(t,e,r){var n=t.$queues,o=r.debugOn;o&&console.info("(validateRegisteredEvents)","storedEvt",n),n.forEach((function(t){var r=t[0],n=t[1].resolverName;if(o&&console.info("(validateRegisteredEvents)",r,n),!e[r][n])throw new Error(r+"."+n+" not existed in contract!")}))};function Qo(t,e,r,n){var o=function(t,e,r,n){return Ho(Bo,Vo,Go)({},t,e,r,n)}(t,e,r,n);Yo(e,n,r);var i=function(t){e.$only(t,(function(r){var n=r.resolverName,i=r.args;o[t][n]?Reflect.apply(o[t][n],null,i).then((function(r){e.$trigger(bt(t,n,b),r)})).catch((function(r){e.$trigger(bt(t,n,_),r)})):console.error(n+" is not defined in the contract!")}))};for(var a in o)i(a);setTimeout((function(){e.$suspend=!1}),1)}var Xo=function(t,e,r,n){n.$suspend=!0,r.then((function(r){Qo(t,n,e,r)}));var o={query:Wo(n,"query"),mutation:Wo(n,"mutation"),auth:Wo(n,"auth"),getToken:function(){return t.rawAuthToken}};return e.exposeContract&&(o.getContract=function(){return t.get()}),e.enableAuth&&(o.userdata=function(){return t.userdata}),o.version="1.5.1",o};function Zo(t){return!!function(t){return D(t)&&(yt(t,r)||yt(t,n)||yt(t,o))}(t)&&t}function ti(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var ei=function(t,e){return void 0===e&&(e={}),Zo(e)?Promise.resolve(e):t.getContract()},ri="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function ni(t){this.message=t}ni.prototype=new Error,ni.prototype.name="InvalidCharacterError";var oi="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new ni("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=ri.indexOf(n);return a};var ii=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(oi(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return oi(e)}};function ai(t){this.message=t}ai.prototype=new Error,ai.prototype.name="InvalidTokenError";var ui=function(t,e){if("string"!=typeof t)throw new ai("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(ii(t.split(".")[r]))}catch(t){throw new ai("Invalid token specified: "+t.message)}},ci=ai;ui.InvalidTokenError=ci;var si,fi,li,pi,hi,di,vi,gi,yi,bi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function _i(t){if(Ht(t))return function(t){var e=t.iat||bi(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Pt("Token has expired on "+r,t)}return t}(ui(t));throw new Pt("Token must be a string!")}Jo("HS256",["string"]),Jo(!1,["boolean","number","string"],((si={})[d]="exp",si[f]=!0,si)),Jo(!1,["boolean","number","string"],((fi={})[d]="nbf",fi[f]=!0,fi)),Jo(!1,["boolean","string"],((li={})[d]="iss",li[f]=!0,li)),Jo(!1,["boolean","string"],((pi={})[d]="sub",pi[f]=!0,pi)),Jo(!1,["boolean","string"],((hi={})[d]="iss",hi[f]=!0,hi)),Jo(!1,["boolean"],((di={})[f]=!0,di)),Jo(!1,["boolean","string"],((vi={})[f]=!0,vi)),Jo(!1,["boolean","string"],((gi={})[f]=!0,gi)),Jo(!1,["boolean"],((yi={})[f]=!0,yi));var mi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},wi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var ji=Object.assign?Object.assign:function(t,e,r,n){for(var o=arguments,i=1;i=0;e--){var r=Di().key(e);t(Ki(r),r)}},remove:function(t){return Di().removeItem(t)},clearAll:function(){return Di().clear()}};function Di(){return Hi.localStorage}function Ki(t){return Di().getItem(t)}var Bi=Ei.trim,Vi={name:"cookieStorage",read:function(t){if(!t||!Qi(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Gi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Gi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Wi,remove:Yi,clearAll:function(){Wi((function(t,e){Yi(e)}))}},Gi=Ei.Global.document;function Wi(t){for(var e=Gi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Bi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Yi(t){t&&Qi(t)&&(Gi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Qi(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Gi.cookie)}var Xi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Zi=Ei.bind,ta=Ei.each,ea=Ei.create,ra=Ei.slice,na=function(){var t=ea(oa,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Zi(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Zi(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),ta(r,(function(e,r){t.fire(r,void 0,e)}))}}};var oa={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Zi(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=ra(arguments,1);ta(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},ia=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),aa=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=ia.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=ia.compress(this._serialize(r));t(e,n)}}};var ua=[Li,Vi],ca=[Xi,na,aa],sa=Ii.createStore(ua,ca),fa=Ei.Global;function la(){return fa.sessionStorage}function pa(t){return la().getItem(t)}var ha=[{name:"sessionStorage",read:pa,write:function(t,e){return la().setItem(t,e)},each:function(t){for(var e=la().length-1;e>=0;e--){var r=la().key(e);t(pa(r),r)}},remove:function(t){return la().removeItem(t)},clearAll:function(){return la().clear()}},Vi],da=[Xi,aa],va=Ii.createStore(ha,da),ga=sa,ya=va,ba=function(t){var e;return(e={}).args=t,e};function _a(t,e){var r;return(r={})[t]=e,r[u]=[mi()],r}var ma=function(t){return yt(t,"data")&&!yt(t,"error")?t.data:t},wa=function(t){this.opts=t,this.instanceKey=ti(this.opts.hostname)+"",this.localStore=ga,this.sessionStore=ya},ja={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};wa.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?_o({},o,e):e,r))},wa.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},wa.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},wa.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},ja.lset.set=function(t){return this.__setMethod("localStore",t)},ja.lget.get=function(){return this.__getMethod("localStore")},wa.prototype.ldel=function(t){return this.__delMethod("localStore",t)},wa.prototype.lclear=function(){return this.__clearMethod("localStore")},ja.sset.set=function(t){return this.__setMethod("sessionStore",t)},ja.sget.get=function(){return this.__getMethod("sessionStore")},wa.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},wa.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(wa.prototype,ja);var Sa=c[0],Oa=c[1],ka=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=_i)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(Fo(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new xt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&Fo(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!Zo(t))throw new xt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=Zo(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=_o({},{_cb:mi()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=_o({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=_o({},{method:Sa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return ma(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=Ro(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ma(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new qt("Server side error",r)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?_o({},e,this.getAuthHeader(),this.extraHeader):_o({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=_o({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(Nt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new qt("getRemoteContract",e)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Jt(t)&&m(e)){var n=ba(e);return!0===r?n:_a(t,n)}throw new xt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(Nt)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Jt(t))return _a(t,o);throw new xt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:Oa}).then(Nt)},Object.defineProperties(r.prototype,n),r}(wa)))),Ea={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Aa={hostname:Jo(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:Jo("jsonql",["string"]),loginHandlerName:Jo("login",["string"]),logoutHandlerName:Jo("logout",["string"]),enableJsonp:Jo(!1,["boolean"]),enableAuth:Jo(!1,["boolean"]),useJwt:Jo(!0,["boolean"]),persistToken:Jo(!1,["boolean","number"]),useLocalstorage:Jo(!0,["boolean"]),storageKey:Jo("jsonqlstore",["string"]),authKey:Jo("jsonqlauthkey",["string"]),contractExpired:Jo(0,["number"]),keepContract:Jo(!0,["boolean"]),exposeContract:Jo(!1,["boolean"]),exposeStore:Jo(!1,["boolean"]),showContractDesc:Jo(!1,["boolean"]),contractKey:Jo(!1,["boolean"]),contractKeyName:Jo("X-JSONQL-CV-KEY",["string"]),enableTimeout:Jo(!1,["boolean"]),timeout:Jo(5e3,["number"]),returnInstance:Jo(!1,["boolean"]),allowReturnRawToken:Jo(!1,["boolean"]),debugOn:Jo(!1,["boolean"])};function Ta(t){return Lo(t,v)?t:function(t){return Uo(t,Aa,Ea)}(t)}var xa=new WeakMap,Pa=new WeakMap,qa=function(){this.__suspend__=null,this.queueStore=new Set},Ca={$suspend:{configurable:!0},$queues:{configurable:!0}};Ca.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},qa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ca.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},qa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(qa.prototype,Ca);var $a=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){xa.set(this,t)},r.normalStore.get=function(){return xa.get(this)},r.lazyStore.set=function(t){Pa.set(this,t)},r.lazyStore.get=function(){return Pa.get(this)},e.prototype.hashFnToKey=function(t){return ti(t.toString())+""},Object.defineProperties(e.prototype,r),e}(qa));return function(t,e){void 0===e&&(e={});var r,n=e.contract,o=Ta(e),i=new ka(t,o),a=ei(i,n),u=(r=o.debugOn,new $a({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),c=Xo(i,o,a,u);return c.eventEmitter=u,c}})); //# sourceMappingURL=static.js.map diff --git a/packages/http-client/static.js.map b/packages/http-client/static.js.map index 802af841..3a9264e1 100644 --- a/packages/http-client/static.js.map +++ b/packages/http-client/static.js.map @@ -1 +1 @@ -{"version":3,"file":"static.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"6g2CAAA"} \ No newline at end of file +{"version":3,"file":"static.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"u81CAAA"} \ No newline at end of file -- Gitee From 6c172e6487be55319bbfa2d3b947464c201a4715 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 19:08:15 +0800 Subject: [PATCH 6/7] the error now matching the server side --- .../http-client/dist/jsonql-client.static.js | 9574 ++++++++++++++++- .../dist/jsonql-client.static.js.map | 2 +- .../http-client/dist/jsonql-client.umd.js | 9559 +++++++++++++++- .../http-client/dist/jsonql-client.umd.js.map | 2 +- packages/http-client/package.json | 2 +- .../http-client/src/core/methods-generator.js | 5 +- .../tests/qunit/tests/base-test.js | 2 +- 7 files changed, 19138 insertions(+), 8 deletions(-) diff --git a/packages/http-client/dist/jsonql-client.static.js b/packages/http-client/dist/jsonql-client.static.js index 961f72db..9aa41f4a 100644 --- a/packages/http-client/dist/jsonql-client.static.js +++ b/packages/http-client/dist/jsonql-client.static.js @@ -1,2 +1,9574 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClientStatic=e()}(this,(function(){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r,n=e((function(t,e){var r;r=function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=2)}([function(t,e,r){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};t.exports={type:function(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()},isObject:function(t,e){return e?"object"===this.type(t):t&&"object"===(void 0===t?"undefined":n(t))},isFormData:function(t){return"undefined"!=typeof FormData&&t instanceof FormData},trim:function(t){return t.replace(/(^\s*)|(\s*$)/g,"")},encode:function(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")},formatParams:function(t){var e="",r=!0,n=this;return this.isObject(t)?(function t(o,i){var a=n.encode,u=n.type(o);if("array"==u)o.forEach((function(e,r){n.isObject(e)||(r=""),t(e,i+"%5B"+r+"%5D")}));else if("object"==u)for(var c in o)t(o[c],i?i+"%5B"+a(c)+"%5D":a(c));else r||(e+="&"),r=!1,e+=i+"="+a(o)}(t,""),e):t},merge:function(t,e){for(var r in e)t.hasOwnProperty(r)?this.isObject(e[r],1)&&this.isObject(t[r],1)&&this.merge(t[r],e[r]):t[r]=e[r];return t}}},,function(t,e,r){var n=function(){function t(t,e){for(var r=0;r0&&(t+=(-1===t.indexOf("?")?"?":"&")+w.join("&")),a.open(r.method,t);try{a.withCredentials=!!r.withCredentials,a.timeout=r.timeout||0,"stream"!==y&&(a.responseType=y)}catch(t){}var j=r.headers[u]||r.headers[c],O="application/x-www-form-urlencoded";for(var S in o.trim((j||"").toLowerCase())===O?e=o.formatParams(e):o.isFormData(e)||-1===["object","array"].indexOf(o.type(e))||(O="application/json;charset=utf-8",e=JSON.stringify(e)),j||b||(r.headers[u]=O),r.headers)if(S===u&&o.isFormData(e))delete r.headers[S];else try{a.setRequestHeader(S,r.headers[S])}catch(t){}function k(t,e,n){v(l.p,(function(){if(t){n&&(e.request=r);var o=t.call(l,e,Promise);e=void 0===o?e:o}d(e)||(e=Promise[0===n?"resolve":"reject"](e)),e.then((function(t){s(t)})).catch((function(t){h(t)}))}))}function E(t){t.engine=a,k(l.onerror,t,-1)}function A(t,e){this.message=t,this.status=e}a.onload=function(){try{var t=a.response||a.responseText;t&&r.parseJson&&-1!==(a.getResponseHeader(u)||"").indexOf("json")&&!o.isObject(t)&&(t=JSON.parse(t));var e=a.responseHeaders;if(!e){e={};var n=(a.getAllResponseHeaders()||"").split("\r\n");n.pop(),n.forEach((function(t){if(t){var r=t.split(":")[0];e[r]=a.getResponseHeader(r)}}))}var i=a.status,c=a.statusText,s={data:t,headers:e,status:i,statusText:c};if(o.merge(s,a._response),i>=200&&i<300||304===i)s.engine=a,s.request=r,k(l.handler,s,0);else{var f=new A(c,i);f.response=s,E(f)}}catch(f){E(new A(f.msg,a.status))}},a.onerror=function(t){E(new A(t.msg||"Network Error",0))},a.ontimeout=function(){E(new A("timeout [ "+a.timeout+"ms ]",1))},a._options=r,setTimeout((function(){a.send(b?null:e)}),0)}(n):s(n)}),(function(t){h(t)}))}))}));return h.engine=a,h}},{key:"all",value:function(t){return Promise.all(t)}},{key:"spread",value:function(t){return function(e){return t.apply(null,e)}}}]),t}();a.default=a,["get","post","put","patch","head","delete"].forEach((function(t){a.prototype[t]=function(e,r,n){return this.request(e,r,o.merge({method:t},n))}})),["lock","unlock","clear"].forEach((function(t){a.prototype[t]=function(){this.interceptors.request[t]()}})),t.exports=a}])},t.exports=r()})),o=(r=n)&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r,i="application/vnd.api+json",a={Accept:i,"Content-Type":[i,"charset=utf-8"].join(";")},u="query",c="mutation",s="socket",f="payload",l="condition",p="TS",h=["POST","PUT"],d="type",v="optional",g="enumv",y="args",b="checker",m="alias",_="__checked__",w={desc:"y"},j="No message",O="onResult",S="onError",k=Array.isArray,E="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},A="object"==typeof E&&E&&E.Object===Object&&E,T="object"==typeof self&&self&&self.Object===Object&&self,x=A||T||Function("return this")(),P=x.Symbol,q=Object.prototype,C=q.hasOwnProperty,$=q.toString,z=P?P.toStringTag:void 0;var N=Object.prototype.toString;var R="[object Null]",M="[object Undefined]",F=P?P.toStringTag:void 0;function J(t){return null==t?void 0===t?M:R:F&&F in Object(t)?function(t){var e=C.call(t,z),r=t[z];try{t[z]=void 0;var n=!0}catch(t){}var o=$.call(t);return n&&(e?t[z]=r:delete t[z]),o}(t):function(t){return N.call(t)}(t)}function I(t,e){return function(r){return t(e(r))}}var U=I(Object.getPrototypeOf,Object);function D(t){return null!=t&&"object"==typeof t}var H="[object Object]",L=Function.prototype,B=Object.prototype,K=L.toString,G=B.hasOwnProperty,V=K.call(Object);function W(t){if(!D(t)||J(t)!=H)return!1;var e=U(t);if(null===e)return!0;var r=G.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&K.call(r)==V}function Y(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&it(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var wt=function(t){return k(t)?t:[t]},jt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},Ot=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),xt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),Pt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),qt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),Ct=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),$t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),zt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Nt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),Rt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),Mt=Object.freeze({__proto__:null,Jsonql406Error:St,Jsonql500Error:kt,JsonqlForbiddenError:Et,JsonqlAuthorisationError:At,JsonqlContractAuthError:Tt,JsonqlResolverAppError:xt,JsonqlResolverNotFoundError:Pt,JsonqlEnumError:qt,JsonqlTypeError:Ct,JsonqlCheckerError:$t,JsonqlValidationError:zt,JsonqlError:Nt,JsonqlServerError:Rt}),Ft=Nt,Jt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function It(t){if(Jt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||j,a=e.detail||e;if(o&&Mt[o])throw new Mt[r](i,a);throw new Ft(i,a)}return t}var Ut=function(t){return!!k(t)||null!=t&&""!==_t(t)},Dt="[object Number]";function Ht(t){return function(t){return"number"==typeof t||D(t)&&J(t)==Dt}(t)&&t!=+t}var Lt="[object String]";function Bt(t){return"string"==typeof t||!k(t)&&D(t)&&J(t)==Lt}var Kt=function(t){return!Bt(t)&&!Ht(parseFloat(t))},Gt=function(t){return""!==_t(t)&&Bt(t)},Vt=function(t){return null!=t&&"boolean"==typeof t},Wt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==_t(t)&&(!1===e||!0===e&&null!==t)},Yt=d,Qt=v,Xt=g,Zt=y,te=b,ee=m,re="continue",ne=function(t){switch(t){case"number":return Kt;case"string":return Gt;case"boolean":return Vt;default:return Wt}},oe=function(t,e){return void 0===e&&(e=""),!!k(t)&&(""===e||""===_t(e)||!(t.filter((function(t){return!ne(e)(t)})).length>0))},ie=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ae=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ne(e)(t)})).length)})).length:e.length>e.filter((function(t){return!oe(r,t)})).length};var ue,ce=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[ue?a:++n];if(!1===e(o[u],u,o))break}return t};var se="[object Arguments]";function fe(t){return D(t)&&J(t)==se}var le=Object.prototype,pe=le.hasOwnProperty,he=le.propertyIsEnumerable,de=fe(function(){return arguments}())?fe:function(t){return D(t)&&pe.call(t,"callee")&&!he.call(t,"callee")};var ve="object"==typeof exports&&exports&&!exports.nodeType&&exports,ge=ve&&"object"==typeof module&&module&&!module.nodeType&&module,ye=ge&&ge.exports===ve?x.Buffer:void 0,be=(ye?ye.isBuffer:void 0)||function(){return!1},me=9007199254740991,_e=/^(?:0|[1-9]\d*)$/;function we(t,e){var r=typeof t;return!!(e=null==e?me:e)&&("number"==r||"symbol"!=r&&_e.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=je}var Se={};Se["[object Float32Array]"]=Se["[object Float64Array]"]=Se["[object Int8Array]"]=Se["[object Int16Array]"]=Se["[object Int32Array]"]=Se["[object Uint8Array]"]=Se["[object Uint8ClampedArray]"]=Se["[object Uint16Array]"]=Se["[object Uint32Array]"]=!0,Se["[object Arguments]"]=Se["[object Array]"]=Se["[object ArrayBuffer]"]=Se["[object Boolean]"]=Se["[object DataView]"]=Se["[object Date]"]=Se["[object Error]"]=Se["[object Function]"]=Se["[object Map]"]=Se["[object Number]"]=Se["[object Object]"]=Se["[object RegExp]"]=Se["[object Set]"]=Se["[object String]"]=Se["[object WeakMap]"]=!1;var ke,Ee="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ae=Ee&&"object"==typeof module&&module&&!module.nodeType&&module,Te=Ae&&Ae.exports===Ee&&A.process,xe=function(){try{var t=Ae&&Ae.require&&Ae.require("util").types;return t||Te&&Te.binding&&Te.binding("util")}catch(t){}}(),Pe=xe&&xe.isTypedArray,qe=Pe?(ke=Pe,function(t){return ke(t)}):function(t){return D(t)&&Oe(t.length)&&!!Se[J(t)]},Ce=Object.prototype.hasOwnProperty;function $e(t,e){var r=k(t),n=!r&&de(t),o=!r&&!n&&be(t),i=!r&&!n&&!o&&qe(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},Ye.prototype.set=function(t,e){var r=this.__data__,n=Ve(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var Qe,Xe=x["__core-js_shared__"],Ze=(Qe=/[^.]+$/.exec(Xe&&Xe.keys&&Xe.keys.IE_PROTO||""))?"Symbol(src)_1."+Qe:"";var tr=Function.prototype.toString;function er(t){if(null!=t){try{return tr.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var rr=/^\[object .+?Constructor\]$/,nr=Function.prototype,or=Object.prototype,ir=nr.toString,ar=or.hasOwnProperty,ur=RegExp("^"+ir.call(ar).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function cr(t){return!(!Fe(t)||function(t){return!!Ze&&Ze in t}(t))&&(He(t)?ur:rr).test(er(t))}function sr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return cr(r)?r:void 0}var fr=sr(x,"Map"),lr=sr(Object,"create");var pr="__lodash_hash_undefined__",hr=Object.prototype.hasOwnProperty;var dr=Object.prototype.hasOwnProperty;var vr="__lodash_hash_undefined__";function gr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&kr?new jr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=ie(t))?!ae({arg:r},e):!ne(t)(r))})).length)})).length}return!1},Kn=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Bn,null,a);case"array"===t:return!oe(e.arg);case!1!==(r=ie(t)):return!ae(e,r);default:return!ne(t)(e.arg)}},Gn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Vn=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!oe(e))throw new Nt("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!oe(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==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Gn(t,a):t,index:r,param:a,optional:i}}));default:throw new Nt("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Ut(e)&&!(r.type.length>r.type.filter((function(e){return Kn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Kn(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Wn=function(){try{var t=sr(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function Yn(t,e,r){"__proto__"==e&&Wn?Wn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function Qn(t,e,r){(void 0===r||Ge(t[e],r))&&(void 0!==r||e in t)||Yn(t,e,r)}var Xn="object"==typeof exports&&exports&&!exports.nodeType&&exports,Zn=Xn&&"object"==typeof module&&module&&!module.nodeType&&module,to=Zn&&Zn.exports===Xn?x.Buffer:void 0,eo=to?to.allocUnsafe:void 0;function ro(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new Ar(n).set(new Ar(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var no=Object.create,oo=function(){function t(){}return function(e){if(!Fe(e))return{};if(no)return no(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function io(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ao=Object.prototype.hasOwnProperty;function uo(t,e,r){var n=t[e];ao.call(t,e)&&Ge(n,r)&&(void 0!==r||e in t)||Yn(t,e,r)}var co=Object.prototype.hasOwnProperty;function so(t){if(!Fe(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Ne(t),r=[];for(var n in t)("constructor"!=n||!e&&co.call(t,n))&&r.push(n);return r}function fo(t){return Le(t)?$e(t,!0):so(t)}function lo(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=bo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(yo);function jo(t,e){return wo(function(t,e,r){return e=go(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=go(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Oo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!Fe(r))return!1;var n=typeof e;return!!("number"==n?Le(r)&&we(e,r.length):"string"==n&&e in r)&&Ge(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,wt(t))}),Reflect.apply(t,null,r))}};function Vo(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function Wo(t,e,r,n){void 0===n&&(n=!1);var o=Vo(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var Yo=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return Lo(r,i).then((function(){return t.query.apply(t,[e,a,u])}))}},Qo=function(t,e,r,n,o){var i={},a=function(t){i=Wo(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return Lo(a,i).then((function(){return e.query.apply(e,[t,a,u])}))}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},Xo=function(t,e,r,n,o){var i={},a=function(t){i=Wo(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return Lo(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])}))}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Zo=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Yo(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Yo(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var ti=function(t,e){return function(r){for(var n=[],o=arguments.length-1;o-- >0;)n[o]=arguments[o+1];return new Promise((function(o,i){t.$only(Ot(e,r,O),o),t.$only(Ot(e,r,S),i),t.$trigger(e,{resolverName:r,args:n})}))}},ei=function(t,e,r){var n=t.$queues,o=r.debugOn;o&&console.info("(validateRegisteredEvents)","storedEvt",n),n.forEach((function(t){var r=t[0],n=t[1].resolverName;if(o&&console.info("(validateRegisteredEvents)",r,n),!e[r][n])throw new Error(r+"."+n+" not existed in contract!")}))};function ri(t,e,r,n){var o=function(t,e,r,n){return Go(Qo,Xo,Zo)({},t,e,r,n)}(t,e,r,n);ei(e,n,r);var i=function(t){e.$only(t,(function(r){var n=r.resolverName,i=r.args;o[t][n]?Reflect.apply(o[t][n],null,i).then((function(r){e.$trigger(Ot(t,n,O),r)})).catch((function(r){e.$trigger(Ot(t,n,S),r)})):console.error(n+" is not defined in the contract!")}))};for(var a in o)i(a);setTimeout((function(){e.$suspend=!1}),1)}var ni=function(t,e,r,n){n.$suspend=!0,r.then((function(r){ri(t,n,e,r)}));var o={query:ti(n,"query"),mutation:ti(n,"mutation"),auth:ti(n,"auth"),getToken:function(){return t.rawAuthToken}};return e.exposeContract&&(o.getContract=function(){return t.get()}),e.enableAuth&&(o.userdata=function(){return t.userdata}),o.version="1.5.1",o};function oi(t){return!!function(t){return W(t)&&(jt(t,u)||jt(t,c)||jt(t,s))}(t)&&t}function ii(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var ai=function(t,e){return void 0===e&&(e={}),oi(e)?Promise.resolve(e):t.getContract()},ui="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function ci(t){this.message=t}ci.prototype=new Error,ci.prototype.name="InvalidCharacterError";var si="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new ci("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=ui.indexOf(n);return a};var fi=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(si(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return si(e)}};function li(t){this.message=t}li.prototype=new Error,li.prototype.name="InvalidTokenError";var pi=function(t,e){if("string"!=typeof t)throw new li("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(fi(t.split(".")[r]))}catch(t){throw new li("Invalid token specified: "+t.message)}},hi=li;pi.InvalidTokenError=hi;var di,vi,gi,yi,bi,mi,_i,wi,ji,Oi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Si(t){if(Gt(t))return function(t){var e=t.iat||Oi(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Nt("Token has expired on "+r,t)}return t}(pi(t));throw new Nt("Token must be a string!")}Bo("HS256",["string"]),Bo(!1,["boolean","number","string"],((di={})[m]="exp",di[v]=!0,di)),Bo(!1,["boolean","number","string"],((vi={})[m]="nbf",vi[v]=!0,vi)),Bo(!1,["boolean","string"],((gi={})[m]="iss",gi[v]=!0,gi)),Bo(!1,["boolean","string"],((yi={})[m]="sub",yi[v]=!0,yi)),Bo(!1,["boolean","string"],((bi={})[m]="iss",bi[v]=!0,bi)),Bo(!1,["boolean"],((mi={})[v]=!0,mi)),Bo(!1,["boolean","string"],((_i={})[v]=!0,_i)),Bo(!1,["boolean","string"],((wi={})[v]=!0,wi)),Bo(!1,["boolean"],((ji={})[v]=!0,ji));var ki=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},Ei=Object.assign?Object.assign:function(t,e,r,n){for(var o=arguments,i=1;i=0;e--){var r=Vi().key(e);t(Wi(r),r)}},remove:function(t){return Vi().removeItem(t)},clearAll:function(){return Vi().clear()}};function Vi(){return Ki.localStorage}function Wi(t){return Vi().getItem(t)}var Yi=Pi.trim,Qi={name:"cookieStorage",read:function(t){if(!t||!ea(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Xi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Xi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Zi,remove:ta,clearAll:function(){Zi((function(t,e){ta(e)}))}},Xi=Pi.Global.document;function Zi(t){for(var e=Xi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Yi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function ta(t){t&&ea(t)&&(Xi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function ea(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Xi.cookie)}var ra=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var na=Pi.bind,oa=Pi.each,ia=Pi.create,aa=Pi.slice,ua=function(){var t=ia(ca,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,na(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,na(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),oa(r,(function(e,r){t.fire(r,void 0,e)}))}}};var ca={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,na(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=aa(arguments,1);oa(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},sa=e((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),fa=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=sa.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=sa.compress(this._serialize(r));t(e,n)}}};var la=[Gi,Qi],pa=[ra,ua,fa],ha=Hi.createStore(la,pa),da=Pi.Global;function va(){return da.sessionStorage}function ga(t){return va().getItem(t)}var ya=[{name:"sessionStorage",read:ga,write:function(t,e){return va().setItem(t,e)},each:function(t){for(var e=va().length-1;e>=0;e--){var r=va().key(e);t(ga(r),r)}},remove:function(t){return va().removeItem(t)},clearAll:function(){return va().clear()}},Qi],ba=[ra,fa],ma=Hi.createStore(ya,ba),_a=ha,wa=ma,ja=function(t){var e;return(e={}).args=t,e};function Oa(t,e){var r;return(r={})[t]=e,r[p]=[ki()],r}var Sa=function(t){return jt(t,"data")&&!jt(t,"error")?t.data:t},ka=function(t){this.opts=t,this.instanceKey=ii(this.opts.hostname)+"",this.localStore=_a,this.sessionStore=wa},Ea={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};ka.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?So({},o,e):e,r))},ka.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},ka.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},ka.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},Ea.lset.set=function(t){return this.__setMethod("localStore",t)},Ea.lget.get=function(){return this.__getMethod("localStore")},ka.prototype.ldel=function(t){return this.__delMethod("localStore",t)},ka.prototype.lclear=function(){return this.__clearMethod("localStore")},Ea.sset.set=function(t){return this.__setMethod("sessionStore",t)},Ea.sget.get=function(){return this.__getMethod("sessionStore")},ka.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},ka.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(ka.prototype,Ea);var Aa=h[0],Ta=h[1],xa=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Si)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(Ho(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new zt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&Ho(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!oi(t))throw new zt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=oi(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={headers:{configurable:!0}};return r.headers.set=function(t){this.extraHeader=t},e.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=So({},{_cb:ki()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=So({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=So({},{method:Aa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},e.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},e.prototype.processJsonp=function(t){return Sa(t)},e.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=Do(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):Sa(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new Rt("Server side error",r)}))},e.prototype.getHeaders=function(){return this.opts.enableAuth?So({},a,this.getAuthHeader(),this.extraHeader):So({},a,this.extraHeader)},e.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},e.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=So({},this.extraParams,w)),this.request({},{method:"GET"},this.contractHeader).then(It).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new Rt("getRemoteContract",e)}))},e.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Bt(t)&&k(e)){var n=ja(e);return!0===r?n:Oa(t,n)}throw new zt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(It)},e.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[f]=e,o[l]=r,!0===n)return o;if(Bt(t))return Oa(t,o);throw new zt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:Ta}).then(It)},Object.defineProperties(e.prototype,r),e}(ka)))),Pa={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:i,BEARER:"Bearer",AUTH_HEADER:"Authorization"},qa={hostname:Bo(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:Bo("jsonql",["string"]),loginHandlerName:Bo("login",["string"]),logoutHandlerName:Bo("logout",["string"]),enableJsonp:Bo(!1,["boolean"]),enableAuth:Bo(!1,["boolean"]),useJwt:Bo(!0,["boolean"]),persistToken:Bo(!1,["boolean","number"]),useLocalstorage:Bo(!0,["boolean"]),storageKey:Bo("jsonqlstore",["string"]),authKey:Bo("jsonqlauthkey",["string"]),contractExpired:Bo(0,["number"]),keepContract:Bo(!0,["boolean"]),exposeContract:Bo(!1,["boolean"]),exposeStore:Bo(!1,["boolean"]),showContractDesc:Bo(!1,["boolean"]),contractKey:Bo(!1,["boolean"]),contractKeyName:Bo("X-JSONQL-CV-KEY",["string"]),enableTimeout:Bo(!1,["boolean"]),timeout:Bo(5e3,["number"]),returnInstance:Bo(!1,["boolean"]),allowReturnRawToken:Bo(!1,["boolean"]),debugOn:Bo(!1,["boolean"])};function Ca(t){return Vo(t,_)?t:function(t){return Ko(t,qa,Pa)}(t)}var $a=new WeakMap,za=new WeakMap,Na=function(){this.__suspend__=null,this.queueStore=new Set},Ra={$suspend:{configurable:!0},$queues:{configurable:!0}};Ra.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Na.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ra.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Na.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Na.prototype,Ra);var Ma=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){$a.set(this,t)},r.normalStore.get=function(){return $a.get(this)},r.lazyStore.set=function(t){za.set(this,t)},r.lazyStore.get=function(){return za.get(this)},e.prototype.hashFnToKey=function(t){return ii(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Na));function Fa(t,e){void 0===e&&(e={});var r,n=e.contract,o=Ca(e),i=new xa(t,o),a=ai(i,n),u=(r=o.debugOn,new Ma({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),c=ni(i,o,a,u);return c.eventEmitter=u,c}return function(t){return void 0===t&&(t={}),Fa(new o,t)}})); +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.jsonqlClientStatic = factory()); +}(this, (function () { 'use strict'; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var fly = createCommonjsModule(function (module, exports) { + (function webpackUniversalModuleDefinition(root, factory) { + { module.exports = factory(); } + })(commonjsGlobal, function() { + return /******/ (function(modules) { // webpackBootstrap + /******/ // The module cache + /******/ var installedModules = {}; + /******/ + /******/ // The require function + /******/ function __webpack_require__(moduleId) { + /******/ + /******/ // Check if module is in cache + /******/ if(installedModules[moduleId]) { + /******/ return installedModules[moduleId].exports; + /******/ } + /******/ // Create a new module (and put it into the cache) + /******/ var module = installedModules[moduleId] = { + /******/ i: moduleId, + /******/ l: false, + /******/ exports: {} + /******/ }; + /******/ + /******/ // Execute the module function + /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + /******/ + /******/ // Flag the module as loaded + /******/ module.l = true; + /******/ + /******/ // Return the exports of the module + /******/ return module.exports; + /******/ } + /******/ + /******/ + /******/ // expose the modules object (__webpack_modules__) + /******/ __webpack_require__.m = modules; + /******/ + /******/ // expose the module cache + /******/ __webpack_require__.c = installedModules; + /******/ + /******/ // identity function for calling harmony imports with the correct context + /******/ __webpack_require__.i = function(value) { return value; }; + /******/ + /******/ // define getter function for harmony exports + /******/ __webpack_require__.d = function(exports, name, getter) { + /******/ if(!__webpack_require__.o(exports, name)) { + /******/ Object.defineProperty(exports, name, { + /******/ configurable: false, + /******/ enumerable: true, + /******/ get: getter + /******/ }); + /******/ } + /******/ }; + /******/ + /******/ // getDefaultExport function for compatibility with non-harmony modules + /******/ __webpack_require__.n = function(module) { + /******/ var getter = module && module.__esModule ? + /******/ function getDefault() { return module['default']; } : + /******/ function getModuleExports() { return module; }; + /******/ __webpack_require__.d(getter, 'a', getter); + /******/ return getter; + /******/ }; + /******/ + /******/ // Object.prototype.hasOwnProperty.call + /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; + /******/ + /******/ // __webpack_public_path__ + /******/ __webpack_require__.p = ""; + /******/ + /******/ // Load entry module and return exports + /******/ return __webpack_require__(__webpack_require__.s = 2); + /******/ }) + /************************************************************************/ + /******/ ([ + /* 0 */ + /***/ (function(module, exports, __webpack_require__) { + + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + module.exports = { + type: function type(ob) { + return Object.prototype.toString.call(ob).slice(8, -1).toLowerCase(); + }, + isObject: function isObject(ob, real) { + if (real) { + return this.type(ob) === "object"; + } else { + return ob && (typeof ob === 'undefined' ? 'undefined' : _typeof(ob)) === 'object'; + } + }, + isFormData: function isFormData(val) { + return typeof FormData !== 'undefined' && val instanceof FormData; + }, + trim: function trim(str) { + return str.replace(/(^\s*)|(\s*$)/g, ''); + }, + encode: function encode(val) { + return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); + }, + formatParams: function formatParams(data) { + var str = ""; + var first = true; + var that = this; + if (!this.isObject(data)) { + return data; + } + + function _encode(sub, path) { + var encode = that.encode; + var type = that.type(sub); + if (type == "array") { + sub.forEach(function (e, i) { + if (!that.isObject(e)) { i = ""; } + _encode(e, path + ('%5B' + i + '%5D')); + }); + } else if (type == "object") { + for (var key in sub) { + if (path) { + _encode(sub[key], path + "%5B" + encode(key) + "%5D"); + } else { + _encode(sub[key], encode(key)); + } + } + } else { + if (!first) { + str += "&"; + } + first = false; + str += path + "=" + encode(sub); + } + } + + _encode(data, ""); + return str; + }, + + // Do not overwrite existing attributes + merge: function merge(a, b) { + for (var key in b) { + if (!a.hasOwnProperty(key)) { + a[key] = b[key]; + } else if (this.isObject(b[key], 1) && this.isObject(a[key], 1)) { + this.merge(a[key], b[key]); + } + } + return a; + } + }; + + /***/ }), + /* 1 */, + /* 2 */ + /***/ (function(module, exports, __webpack_require__) { + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var utils = __webpack_require__(0); + var isBrowser = typeof document !== "undefined"; + + var Fly = function () { + function Fly(engine) { + _classCallCheck(this, Fly); + + this.engine = engine || XMLHttpRequest; + + this.default = this; //For typeScript + + /** + * Add lock/unlock API for interceptor. + * + * Once an request/response interceptor is locked, the incoming request/response + * will be added to a queue before they enter the interceptor, they will not be + * continued until the interceptor is unlocked. + * + * @param [interceptor] either is interceptors.request or interceptors.response + */ + function wrap(interceptor) { + var resolve = void 0; + var reject = void 0; + + function _clear() { + interceptor.p = resolve = reject = null; + } + + utils.merge(interceptor, { + lock: function lock() { + if (!resolve) { + interceptor.p = new Promise(function (_resolve, _reject) { + resolve = _resolve; + reject = _reject; + }); + } + }, + unlock: function unlock() { + if (resolve) { + resolve(); + _clear(); + } + }, + clear: function clear() { + if (reject) { + reject("cancel"); + _clear(); + } + } + }); + } + + var interceptors = this.interceptors = { + response: { + use: function use(handler, onerror) { + this.handler = handler; + this.onerror = onerror; + } + }, + request: { + use: function use(handler) { + this.handler = handler; + } + } + }; + + var irq = interceptors.request; + var irp = interceptors.response; + wrap(irp); + wrap(irq); + + this.config = { + method: "GET", + baseURL: "", + headers: {}, + timeout: 0, + params: {}, // Default Url params + parseJson: true, // Convert response data to JSON object automatically. + withCredentials: false + }; + } + + _createClass(Fly, [{ + key: "request", + value: function request(url, data, options) { + var _this = this; + + var engine = new this.engine(); + var contentType = "Content-Type"; + var contentTypeLowerCase = contentType.toLowerCase(); + var interceptors = this.interceptors; + var requestInterceptor = interceptors.request; + var responseInterceptor = interceptors.response; + var requestInterceptorHandler = requestInterceptor.handler; + var promise = new Promise(function (resolve, reject) { + if (utils.isObject(url)) { + options = url; + url = options.url; + } + options = options || {}; + options.headers = options.headers || {}; + + function isPromise(p) { + // some polyfill implementation of Promise may be not standard, + // so, we test by duck-typing + return p && p.then && p.catch; + } + + /** + * If the request/response interceptor has been locked, + * the new request/response will enter a queue. otherwise, it will be performed directly. + * @param [promise] if the promise exist, means the interceptor is locked. + * @param [callback] + */ + function enqueueIfLocked(promise, callback) { + if (promise) { + promise.then(function () { + callback(); + }); + } else { + callback(); + } + } + + // make the http request + function makeRequest(options) { + data = options.body; + // Normalize the request url + url = utils.trim(options.url); + var baseUrl = utils.trim(options.baseURL || ""); + if (!url && isBrowser && !baseUrl) { url = location.href; } + if (url.indexOf("http") !== 0) { + var isAbsolute = url[0] === "/"; + if (!baseUrl && isBrowser) { + var arr = location.pathname.split("/"); + arr.pop(); + baseUrl = location.protocol + "//" + location.host + (isAbsolute ? "" : arr.join("/")); + } + if (baseUrl[baseUrl.length - 1] !== "/") { + baseUrl += "/"; + } + url = baseUrl + (isAbsolute ? url.substr(1) : url); + if (isBrowser) { + + // Normalize the url which contains the ".." or ".", such as + // "http://xx.com/aa/bb/../../xx" to "http://xx.com/xx" . + var t = document.createElement("a"); + t.href = url; + url = t.href; + } + } + + var responseType = utils.trim(options.responseType || ""); + var needQuery = ["GET", "HEAD", "DELETE", "OPTION"].indexOf(options.method) !== -1; + var dataType = utils.type(data); + var params = options.params || {}; + + // merge url params when the method is "GET" (data is object) + if (needQuery && dataType === "object") { + params = utils.merge(data, params); + } + // encode params to String + params = utils.formatParams(params); + + // save url params + var _params = []; + if (params) { + _params.push(params); + } + // Add data to url params when the method is "GET" (data is String) + if (needQuery && data && dataType === "string") { + _params.push(data); + } + + // make the final url + if (_params.length > 0) { + url += (url.indexOf("?") === -1 ? "?" : "&") + _params.join("&"); + } + + engine.open(options.method, url); + + // try catch for ie >=9 + try { + engine.withCredentials = !!options.withCredentials; + engine.timeout = options.timeout || 0; + if (responseType !== "stream") { + engine.responseType = responseType; + } + } catch (e) {} + + var customContentType = options.headers[contentType] || options.headers[contentTypeLowerCase]; + + // default content type + var _contentType = "application/x-www-form-urlencoded"; + // If the request data is json object, transforming it to json string, + // and set request content-type to "json". In browser, the data will + // be sent as RequestBody instead of FormData + if (utils.trim((customContentType || "").toLowerCase()) === _contentType) { + data = utils.formatParams(data); + } else if (!utils.isFormData(data) && ["object", "array"].indexOf(utils.type(data)) !== -1) { + _contentType = 'application/json;charset=utf-8'; + data = JSON.stringify(data); + } + //If user doesn't set content-type, set default. + if (!(customContentType || needQuery)) { + options.headers[contentType] = _contentType; + } + + for (var k in options.headers) { + if (k === contentType && utils.isFormData(data)) { + // Delete the content-type, Let the browser set it + delete options.headers[k]; + } else { + try { + // In browser environment, some header fields are readonly, + // write will cause the exception . + engine.setRequestHeader(k, options.headers[k]); + } catch (e) {} + } + } + + function onresult(handler, data, type) { + enqueueIfLocked(responseInterceptor.p, function () { + if (handler) { + //如果失败,添加请求信息 + if (type) { + data.request = options; + } + var ret = handler.call(responseInterceptor, data, Promise); + data = ret === undefined ? data : ret; + } + if (!isPromise(data)) { + data = Promise[type === 0 ? "resolve" : "reject"](data); + } + data.then(function (d) { + resolve(d); + }).catch(function (e) { + reject(e); + }); + }); + } + + function onerror(e) { + e.engine = engine; + onresult(responseInterceptor.onerror, e, -1); + } + + function Err(msg, status) { + this.message = msg; + this.status = status; + } + + engine.onload = function () { + try { + // The xhr of IE9 has not response field + var response = engine.response || engine.responseText; + if (response && options.parseJson && (engine.getResponseHeader(contentType) || "").indexOf("json") !== -1 + // Some third engine implementation may transform the response text to json object automatically, + // so we should test the type of response before transforming it + && !utils.isObject(response)) { + response = JSON.parse(response); + } + + var headers = engine.responseHeaders; + // In browser + if (!headers) { + headers = {}; + var items = (engine.getAllResponseHeaders() || "").split("\r\n"); + items.pop(); + items.forEach(function (e) { + if (!e) { return; } + var key = e.split(":")[0]; + headers[key] = engine.getResponseHeader(key); + }); + } + var status = engine.status; + var statusText = engine.statusText; + var _data = { data: response, headers: headers, status: status, statusText: statusText }; + // The _response filed of engine is set in adapter which be called in engine-wrapper.js + utils.merge(_data, engine._response); + if (status >= 200 && status < 300 || status === 304) { + _data.engine = engine; + _data.request = options; + onresult(responseInterceptor.handler, _data, 0); + } else { + var e = new Err(statusText, status); + e.response = _data; + onerror(e); + } + } catch (e) { + onerror(new Err(e.msg, engine.status)); + } + }; + + engine.onerror = function (e) { + onerror(new Err(e.msg || "Network Error", 0)); + }; + + engine.ontimeout = function () { + onerror(new Err("timeout [ " + engine.timeout + "ms ]", 1)); + }; + engine._options = options; + setTimeout(function () { + engine.send(needQuery ? null : data); + }, 0); + } + + enqueueIfLocked(requestInterceptor.p, function () { + utils.merge(options, JSON.parse(JSON.stringify(_this.config))); + var headers = options.headers; + headers[contentType] = headers[contentType] || headers[contentTypeLowerCase] || ""; + delete headers[contentTypeLowerCase]; + options.body = data || options.body; + url = utils.trim(url || ""); + options.method = options.method.toUpperCase(); + options.url = url; + var ret = options; + if (requestInterceptorHandler) { + ret = requestInterceptorHandler.call(requestInterceptor, options, Promise) || options; + } + if (!isPromise(ret)) { + ret = Promise.resolve(ret); + } + ret.then(function (d) { + //if options continue + if (d === options) { + makeRequest(d); + } else { + resolve(d); + } + }, function (err) { + reject(err); + }); + }); + }); + promise.engine = engine; + return promise; + } + }, { + key: "all", + value: function all(promises) { + return Promise.all(promises); + } + }, { + key: "spread", + value: function spread(callback) { + return function (arr) { + return callback.apply(null, arr); + }; + } + }]); + + return Fly; + }(); + + //For typeScript + + + Fly.default = Fly; + + ["get", "post", "put", "patch", "head", "delete"].forEach(function (e) { + Fly.prototype[e] = function (url, data, option) { + return this.request(url, data, utils.merge({ method: e }, option)); + }; + }); + ["lock", "unlock", "clear"].forEach(function (e) { + Fly.prototype[e] = function () { + this.interceptors.request[e](); + }; + }); + module.exports = Fly; + + /***/ }) + /******/ ]); + }); + }); + + var Fly = unwrapExports(fly); + + // the core stuff to id if it's calling with jsonql + var DATA_KEY = 'data'; + var ERROR_KEY = 'error'; + + var JSONQL_PATH = 'jsonql'; + // according to the json query spec + var CONTENT_TYPE = 'application/vnd.api+json'; + var CHARSET = 'charset=utf-8'; + var DEFAULT_HEADER = { + 'Accept': CONTENT_TYPE, + 'Content-Type': [ CONTENT_TYPE, CHARSET ].join(';') + }; + + // export const INDEX = 'index'; use INDEX_KEY instead + var DEFAULT_TYPE = 'any'; + + // @TODO remove this is not in use + // export const CLIENT_CONFIG_FILE = '.clients.json'; + // export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js'; + // type of resolvers + var QUERY_NAME = 'query'; + var MUTATION_NAME = 'mutation'; + var SOCKET_NAME = 'socket'; + // for calling the mutation + var PAYLOAD_PARAM_NAME = 'payload'; // @TODO shortern them + var CONDITION_PARAM_NAME = 'condition'; + var QUERY_ARG_NAME = 'args'; + var TIMESTAMP_PARAM_NAME = 'TS'; + // new jsonp + var JSONP_CALLBACK_NAME = 'jsonqlJsonpCallback'; + + // methods allow + var API_REQUEST_METHODS = ['POST', 'PUT']; + // for contract-cli + var KEY_WORD = 'continue'; + + var TYPE_KEY = 'type'; + var OPTIONAL_KEY = 'optional'; + var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word + var ARGS_KEY = 'args'; + var CHECKER_KEY = 'checker'; + var ALIAS_KEY = 'alias'; + var CHECKED_KEY = '__checked__'; + var LOGIN_NAME = 'login'; + var ISSUER_NAME = LOGIN_NAME; // legacy issue need to replace them later + var LOGOUT_NAME = 'logout'; + + var AUTH_HEADER = 'Authorization'; + var BEARER = 'Bearer'; + + // for client use @TODO need to clean this up some of them are not in use + var CREDENTIAL_STORAGE_KEY = 'jsonqlcredential'; + var CLIENT_STORAGE_KEY = 'jsonqlstore'; + var CLIENT_AUTH_KEY = 'jsonqlauthkey'; + // contract key + var CONTRACT_KEY_NAME = 'X-JSONQL-CV-KEY'; + var SHOW_CONTRACT_DESC_PARAM = {desc: 'y'}; + + var OR_SEPERATOR = '|'; + + var STRING_TYPE = 'string'; + var BOOLEAN_TYPE = 'boolean'; + var ARRAY_TYPE = 'array'; + var OBJECT_TYPE = 'object'; + + var NUMBER_TYPE = 'number'; + var ARRAY_TYPE_LFT = 'array.<'; + var ARRAY_TYPE_RGT = '>'; + + var NO_ERROR_MSG = 'No message'; + var NO_STATUS_CODE = -1; + var ON_RESULT_PROP_NAME = 'onResult'; + var ON_ERROR_PROP_NAME = 'onError'; + var HSA_ALGO = 'HS256'; + + /** + * 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; + + 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$1 = root.Symbol; + + /** 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$1 ? Symbol$1.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$1 ? Symbol$1.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); + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** Built-in value references. */ + var getPrototype = overArg(Object.getPrototypeOf, Object); + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @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 objectTag = '[object Object]'; + + /** Used for built-in method references. */ + var funcProto = Function.prototype, + objectProto$2 = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty$1 = objectProto$2.hasOwnProperty; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty$1.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * 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; + } + + /** `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$1 ? Symbol$1.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(''); + } + + // bunch of generic helpers + + /** + * DIY in Array + * @param {array} arr to check from + * @param {*} value to check against + * @return {boolean} true on found + */ + var inArray = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; + + // quick and dirty to turn non array to array + var toArray = function (arg) { return isArray(arg) ? arg : [arg]; }; + + /** + * @param {object} obj for search + * @param {string} key target + * @return {boolean} true on success + */ + var isObjectHasKey = function(obj, key) { + try { + var keys = Object.keys(obj); + return inArray(keys, key) + } catch(e) { + // @BUG when the obj is not an OBJECT we got some weird output + return false; + /* + console.info('obj', obj) + console.error(e) + throw new Error(e) + */ + } + }; + + /** + * create a event name + * @param {string[]} args + * @return {string} event name for use + */ + var createEvt = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return args.join('_'); + }; + + /** + * This is a custom error to throw when server throw a 406 + * 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 Jsonql406Error = /*@__PURE__*/(function (Error) { + function Jsonql406Error() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + this.message = args[0]; + this.detail = args[1]; + // We can't access the static name from an instance + // but we can do it like this + this.className = Jsonql406Error.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Jsonql406Error); + } + } + + if ( Error ) Jsonql406Error.__proto__ = Error; + Jsonql406Error.prototype = Object.create( Error && Error.prototype ); + Jsonql406Error.prototype.constructor = Jsonql406Error; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 406; + }; + + staticAccessors.name.get = function () { + return 'Jsonql406Error'; + }; + + Object.defineProperties( Jsonql406Error, staticAccessors ); + + return Jsonql406Error; + }(Error)); + + /** + * This is a custom error to throw when server throw a 500 + * 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 Jsonql500Error = /*@__PURE__*/(function (Error) { + function Jsonql500Error() { + 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 = Jsonql500Error.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Jsonql500Error); + } + } + + if ( Error ) Jsonql500Error.__proto__ = Error; + Jsonql500Error.prototype = Object.create( Error && Error.prototype ); + Jsonql500Error.prototype.constructor = Jsonql500Error; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 500; + }; + + staticAccessors.name.get = function () { + return 'Jsonql500Error'; + }; + + Object.defineProperties( Jsonql500Error, staticAccessors ); + + return Jsonql500Error; + }(Error)); + + /** + * this is the 403 Forbidden error + * that means this user is not login + * use the 401 for try to login and failed + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ + var JsonqlForbiddenError = /*@__PURE__*/(function (Error) { + function JsonqlForbiddenError() { + 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 = JsonqlForbiddenError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlForbiddenError); + } + } + + if ( Error ) JsonqlForbiddenError.__proto__ = Error; + JsonqlForbiddenError.prototype = Object.create( Error && Error.prototype ); + JsonqlForbiddenError.prototype.constructor = JsonqlForbiddenError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 403; + }; + + staticAccessors.name.get = function () { + return 'JsonqlForbiddenError'; + }; + + Object.defineProperties( JsonqlForbiddenError, staticAccessors ); + + return JsonqlForbiddenError; + }(Error)); + + /** + * This is a custom error to throw when pass credential but fail + * 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 JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { + function JsonqlAuthorisationError() { + 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 = JsonqlAuthorisationError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlAuthorisationError); + } + } + + if ( Error ) JsonqlAuthorisationError.__proto__ = Error; + JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); + JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 401; + }; + + staticAccessors.name.get = function () { + return 'JsonqlAuthorisationError'; + }; + + Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); + + return JsonqlAuthorisationError; + }(Error)); + + /** + * This is a custom error when not supply the credential and try to get contract + * 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 JsonqlContractAuthError = /*@__PURE__*/(function (Error) { + function JsonqlContractAuthError() { + 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 = JsonqlContractAuthError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlContractAuthError); + } + } + + if ( Error ) JsonqlContractAuthError.__proto__ = Error; + JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); + JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 401; + }; + + staticAccessors.name.get = function () { + return 'JsonqlContractAuthError'; + }; + + Object.defineProperties( JsonqlContractAuthError, staticAccessors ); + + return JsonqlContractAuthError; + }(Error)); + + /** + * This is a custom error to throw when the resolver throw error and capture inside the middleware + * 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 JsonqlResolverAppError = /*@__PURE__*/(function (Error) { + function JsonqlResolverAppError() { + 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 = JsonqlResolverAppError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlResolverAppError); + } + } + + if ( Error ) JsonqlResolverAppError.__proto__ = Error; + JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); + JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 500; + }; + + staticAccessors.name.get = function () { + return 'JsonqlResolverAppError'; + }; + + Object.defineProperties( JsonqlResolverAppError, staticAccessors ); + + return JsonqlResolverAppError; + }(Error)); + + /** + * This is a custom error to throw when could not find the resolver + * 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 JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { + function JsonqlResolverNotFoundError() { + 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 = JsonqlResolverNotFoundError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlResolverNotFoundError); + } + } + + if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; + JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); + JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 404; + }; + + staticAccessors.name.get = function () { + return 'JsonqlResolverNotFoundError'; + }; + + Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); + + return JsonqlResolverNotFoundError; + }(Error)); + + // this get throw from within the checkOptions when run through the enum failed + var JsonqlEnumError = /*@__PURE__*/(function (Error) { + function JsonqlEnumError() { + 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 = JsonqlEnumError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlEnumError); + } + } + + if ( Error ) JsonqlEnumError.__proto__ = Error; + JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); + JsonqlEnumError.prototype.constructor = JsonqlEnumError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlEnumError'; + }; + + Object.defineProperties( JsonqlEnumError, staticAccessors ); + + return JsonqlEnumError; + }(Error)); + + // this will throw from inside the checkOptions + var JsonqlTypeError = /*@__PURE__*/(function (Error) { + function JsonqlTypeError() { + 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 = JsonqlTypeError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlTypeError); + } + } + + if ( Error ) JsonqlTypeError.__proto__ = Error; + JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); + JsonqlTypeError.prototype.constructor = JsonqlTypeError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlTypeError'; + }; + + Object.defineProperties( JsonqlTypeError, staticAccessors ); + + return JsonqlTypeError; + }(Error)); + + // allow supply a custom checker function + // if that failed then we throw this error + var JsonqlCheckerError = /*@__PURE__*/(function (Error) { + function JsonqlCheckerError() { + 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 = JsonqlCheckerError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlCheckerError); + } + } + + if ( Error ) JsonqlCheckerError.__proto__ = Error; + JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); + JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlCheckerError'; + }; + + Object.defineProperties( JsonqlCheckerError, staticAccessors ); + + return JsonqlCheckerError; + }(Error)); + + // custom validation error class + // when validaton failed + var JsonqlValidationError = /*@__PURE__*/(function (Error) { + function JsonqlValidationError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlValidationError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlValidationError); + } + } + + if ( Error ) JsonqlValidationError.__proto__ = Error; + JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); + JsonqlValidationError.prototype.constructor = JsonqlValidationError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlValidationError'; + }; + + Object.defineProperties( JsonqlValidationError, staticAccessors ); + + return JsonqlValidationError; + }(Error)); + + /** + * This is a custom error to throw whenever a error happen inside the jsonql + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ + var JsonqlError = /*@__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)); + + // this is from an example from Koa team to use for internal middleware ctx.throw + // but after the test the res.body part is unable to extract the required data + // I keep this one here for future reference + + var JsonqlServerError = /*@__PURE__*/(function (Error) { + function JsonqlServerError(statusCode, message) { + Error.call(this, message); + this.statusCode = statusCode; + this.className = JsonqlServerError.name; + } + + if ( Error ) JsonqlServerError.__proto__ = Error; + JsonqlServerError.prototype = Object.create( Error && Error.prototype ); + JsonqlServerError.prototype.constructor = JsonqlServerError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlServerError'; + }; + + Object.defineProperties( JsonqlServerError, staticAccessors ); + + return JsonqlServerError; + }(Error)); + + // server side + + var errors = /*#__PURE__*/Object.freeze({ + __proto__: null, + Jsonql406Error: Jsonql406Error, + Jsonql500Error: Jsonql500Error, + JsonqlForbiddenError: JsonqlForbiddenError, + JsonqlAuthorisationError: JsonqlAuthorisationError, + JsonqlContractAuthError: JsonqlContractAuthError, + JsonqlResolverAppError: JsonqlResolverAppError, + JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, + JsonqlEnumError: JsonqlEnumError, + JsonqlTypeError: JsonqlTypeError, + JsonqlCheckerError: JsonqlCheckerError, + JsonqlValidationError: JsonqlValidationError, + JsonqlError: JsonqlError, + JsonqlServerError: JsonqlServerError + }); + + // this will add directly to the then call in each http call + var JsonqlError$1 = JsonqlError; + + /** + * We can not just check something like result.data what if the result if false? + * @param {object} obj the result object + * @param {string} key we want to check if its exist or not + * @return {boolean} true on found + */ + var isObjectHasKey$1 = function (obj, key) { + var keys = Object.keys(obj); + return !!keys.filter(function (k) { return key === k; }).length; + }; + + /** + * It will ONLY have our own jsonql specific implement check + * @param {object} result the server return result + * @return {object} this will just throw error + */ + function clientErrorsHandler(result) { + if (isObjectHasKey$1(result, 'error')) { + var error = result.error; + var className = error.className; + var name = error.name; + var errorName = className || name; + // just throw the whole thing back + var msg = error.message || NO_ERROR_MSG; + var detail = error.detail || error; + if (errorName && errors[errorName]) { + throw new errors[className](msg, detail) + } + throw new JsonqlError$1(msg, detail) + } + // pass through to the next + return result; + } + + /** + * this will put into generator call at the very end and catch + * the error throw from inside then throw again + * this is necessary because we split calls inside and the throw + * will not reach the actual client unless we do it this way + * @param {object} e Error + * @return {void} just throw + */ + function finalCatch(e) { + // this is a hack to get around the validateAsync not actually throw error + // instead it just rejected it with the array of failed parameters + if (Array.isArray(e)) { + // if we want the message then I will have to create yet another function + // to wrap this function to provide the name prop + throw new JsonqlValidationError('', e) + } + var msg = e.message || NO_ERROR_MSG; + var detail = e.detail || e; + // @BUG the instance of not always work for some reason! + // need to figure out a better way to find out the type of the error + switch (true) { + case e instanceof Jsonql406Error: + throw new Jsonql406Error(msg, detail) + case e instanceof Jsonql500Error: + throw new Jsonql500Error(msg, detail) + case e instanceof JsonqlForbiddenError: + throw new JsonqlForbiddenError(msg, detail) + case e instanceof JsonqlAuthorisationError: + throw new JsonqlAuthorisationError(msg, detail) + case e instanceof JsonqlContractAuthError: + throw new JsonqlContractAuthError(msg, detail) + case e instanceof JsonqlResolverAppError: + throw new JsonqlResolverAppError(msg, detail) + case e instanceof JsonqlResolverNotFoundError: + throw new JsonqlResolverNotFoundError(msg, detail) + case e instanceof JsonqlEnumError: + throw new JsonqlEnumError(msg, detail) + case e instanceof JsonqlTypeError: + throw new JsonqlTypeError(msg, detail) + case e instanceof JsonqlCheckerError: + throw new JsonqlCheckerError(msg, detail) + case e instanceof JsonqlValidationError: + throw new JsonqlValidationError(msg, detail) + case e instanceof JsonqlServerError: + throw new JsonqlServerError(msg, detail) + default: + throw new JsonqlError(msg, detail) + } + } + + /** + * Check several parameter that there is something in the param + * @param {*} param input + * @return {boolean} + */ + var isNotEmpty = function (a) { + if (isArray(a)) { + return true; + } + return a !== undefined && a !== null && trim(a) !== ''; + }; + + /** `Object#toString` result references. */ + var numberTag = '[object Number]'; + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** `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); + } + + // validator numbers + /** + * @2015-05-04 found a problem if the value is a number like string + * it will pass, so add a chck if it's string before we pass to next + * @param {number} value expected value + * @return {boolean} true if OK + */ + var checkIsNumber = function(value) { + return isString(value) ? false : !isNaN( parseFloat(value) ) + }; + + // validate string type + /** + * @param {string} value expected value + * @return {boolean} true if OK + */ + var checkIsString = function(value) { + return (trim(value) !== '') ? isString(value) : false; + }; + + // check for boolean + + /** + * @param {boolean} value expected + * @return {boolean} true if OK + */ + var checkIsBoolean = function(value) { + return value !== null && value !== undefined && typeof value === 'boolean' + }; + + // validate any thing only check if there is something + + /** + * @param {*} value the value + * @param {boolean} [checkNull=true] strict check if there is null value + * @return {boolean} true is OK + */ + var checkIsAny = function(value, checkNull) { + if ( checkNull === void 0 ) checkNull = true; + + if (value !== undefined && value !== '' && trim(value) !== '') { + if (checkNull === false || (checkNull === true && value !== null)) { + return true; + } + } + return false; + }; + + // Good practice rule - No magic number + + var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; + var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; + var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; + // @TODO the jsdoc return array. and we should also allow array syntax + var DEFAULT_TYPE$1 = DEFAULT_TYPE; + var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; + var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; + + var TYPE_KEY$1 = TYPE_KEY; + var OPTIONAL_KEY$1 = OPTIONAL_KEY; + var ENUM_KEY$1 = ENUM_KEY; + var ARGS_KEY$1 = ARGS_KEY; + var CHECKER_KEY$1 = CHECKER_KEY; + var ALIAS_KEY$1 = ALIAS_KEY; + + var ARRAY_TYPE$1 = ARRAY_TYPE; + var OBJECT_TYPE$1 = OBJECT_TYPE; + var STRING_TYPE$1 = STRING_TYPE; + var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; + var NUMBER_TYPE$1 = NUMBER_TYPE; + var KEY_WORD$1 = KEY_WORD; + var OR_SEPERATOR$1 = OR_SEPERATOR; + + // not actually in use + // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; + + // primitive types + + /** + * this is a wrapper method to call different one based on their type + * @param {string} type to check + * @return {function} a function to handle the type + */ + var combineFn = function(type) { + switch (type) { + case NUMBER_TYPE$1: + return checkIsNumber; + case STRING_TYPE$1: + return checkIsString; + case BOOLEAN_TYPE$1: + return checkIsBoolean; + default: + return checkIsAny; + } + }; + + // validate array type + + /** + * @param {array} value expected + * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well + * @return {boolean} true if OK + */ + var checkIsArray = function(value, type) { + if ( type === void 0 ) type=''; + + if (isArray(value)) { + if (type === '' || trim(type)==='') { + return true; + } + // we test it in reverse + // @TODO if the type is an array (OR) then what? + // we need to take into account this could be an array + var c = value.filter(function (v) { return !combineFn(type)(v); }); + return !(c.length > 0) + } + return false; + }; + + /** + * check if it matches the array. pattern + * @param {string} type + * @return {boolean|array} false means NO, always return array + */ + var isArrayLike = function(type) { + // @TODO could that have something like array<> instead of array.<>? missing the dot? + // because type script is Array without the dot + if (type.indexOf(ARRAY_TYPE_LFT$1) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { + var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); + if (_type.indexOf(OR_SEPERATOR$1)) { + return _type.split(OR_SEPERATOR$1) + } + return [_type] + } + return false; + }; + + /** + * we might encounter something like array. then we need to take it apart + * @param {object} p the prepared object for processing + * @param {string|array} type the type came from + * @return {boolean} for the filter to operate on + */ + var arrayTypeHandler = function(p, type) { + var arg = p.arg; + // need a special case to handle the OR type + // we need to test the args instead of the type(s) + if (type.length > 1) { + return !arg.filter(function (v) { return ( + !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) + ); }).length; + } + // type is array so this will be or! + return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length; + }; + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]'; + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** Used for built-in method references. */ + var objectProto$3 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$2 = objectProto$3.hasOwnProperty; + + /** Built-in value references. */ + var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + function stubFalse() { + return false; + } + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Built-in value references. */ + var Buffer = moduleExports ? root.Buffer : undefined; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER = 9007199254740991; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER$1 = 9007199254740991; + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; + } + + /** `Object#toString` result references. */ + var argsTag$1 = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag$1 = '[object Number]', + objectTag$1 = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag$1 = '[object String]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag$1] = + typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag$1] = + typedArrayTags[weakMapTag] = false; + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** Detect free variable `exports`. */ + var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports$1 && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** Used for built-in method references. */ + var objectProto$4 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$3 = objectProto$4.hasOwnProperty; + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$3.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** Used for built-in method references. */ + var objectProto$5 = Object.prototype; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; + + return value === proto; + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeKeys = overArg(Object.keys, Object); + + /** Used for built-in method references. */ + var objectProto$6 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$4 = objectProto$6.hasOwnProperty; + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$4.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** `Object#toString` result references. */ + var asyncTag = '[object AsyncFunction]', + funcTag$1 = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike$1(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** Used for built-in method references. */ + var arrayProto = Array.prototype; + + /** Built-in value references. */ + var splice = arrayProto.splice; + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** Used to detect overreaching core-js shims. */ + var coreJsData = root['__core-js_shared__']; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** Used for built-in method references. */ + var funcProto$1 = Function.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString$1 = funcProto$1.toString; + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString$1.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used for built-in method references. */ + var funcProto$2 = Function.prototype, + objectProto$7 = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString$2 = funcProto$2.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty$5 = objectProto$7.hasOwnProperty; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString$2.call(hasOwnProperty$5).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /* Built-in method references that are verified to be native. */ + var Map$1 = getNative(root, 'Map'); + + /* Built-in method references that are verified to be native. */ + var nativeCreate = getNative(Object, 'create'); + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used for built-in method references. */ + var objectProto$8 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$6 = objectProto$8.hasOwnProperty; + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty$6.call(data, key) ? data[key] : undefined; + } + + /** Used for built-in method references. */ + var objectProto$9 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$7 = objectProto$9.hasOwnProperty; + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key); + } + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; + return this; + } + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map$1 || ListCache), + 'string': new Hash + }; + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED$2); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** Built-in value references. */ + var Uint8Array$1 = root.Uint8Array; + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$1 = 1, + COMPARE_UNORDERED_FLAG$1 = 2; + + /** `Object#toString` result references. */ + var boolTag$1 = '[object Boolean]', + dateTag$1 = '[object Date]', + errorTag$1 = '[object Error]', + mapTag$1 = '[object Map]', + numberTag$2 = '[object Number]', + regexpTag$1 = '[object RegExp]', + setTag$1 = '[object Set]', + stringTag$2 = '[object String]', + symbolTag$1 = '[object Symbol]'; + + var arrayBufferTag$1 = '[object ArrayBuffer]', + dataViewTag$1 = '[object DataView]'; + + /** Used to convert symbols to primitives and strings. */ + var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined, + symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag$1: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag$1: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array$1(object), new Uint8Array$1(other))) { + return false; + } + return true; + + case boolTag$1: + case dateTag$1: + case numberTag$2: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag$1: + return object.name == other.name && object.message == other.message; + + case regexpTag$1: + case stringTag$2: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag$1: + var convert = mapToArray; + + case setTag$1: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG$1; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag$1: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + function stubArray() { + return []; + } + + /** Used for built-in method references. */ + var objectProto$a = Object.prototype; + + /** Built-in value references. */ + var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols = Object.getOwnPropertySymbols; + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable$1.call(object, symbol); + }); + }; + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$2 = 1; + + /** Used for built-in method references. */ + var objectProto$b = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$8 = objectProto$b.hasOwnProperty; + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(root, 'DataView'); + + /* Built-in method references that are verified to be native. */ + var Promise$1 = getNative(root, 'Promise'); + + /* Built-in method references that are verified to be native. */ + var Set$1 = getNative(root, 'Set'); + + /* Built-in method references that are verified to be native. */ + var WeakMap$1 = getNative(root, 'WeakMap'); + + /** `Object#toString` result references. */ + var mapTag$2 = '[object Map]', + objectTag$2 = '[object Object]', + promiseTag = '[object Promise]', + setTag$2 = '[object Set]', + weakMapTag$1 = '[object WeakMap]'; + + var dataViewTag$2 = '[object DataView]'; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map$1), + promiseCtorString = toSource(Promise$1), + setCtorString = toSource(Set$1), + weakMapCtorString = toSource(WeakMap$1); + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$2) || + (Map$1 && getTag(new Map$1) != mapTag$2) || + (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || + (Set$1 && getTag(new Set$1) != setTag$2) || + (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag$2 ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag$2; + case mapCtorString: return mapTag$2; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag$2; + case weakMapCtorString: return weakMapTag$1; + } + } + return result; + }; + } + + var getTag$1 = getTag; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$3 = 1; + + /** `Object#toString` result references. */ + var argsTag$2 = '[object Arguments]', + arrayTag$1 = '[object Array]', + objectTag$3 = '[object Object]'; + + /** Used for built-in method references. */ + var objectProto$c = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$9 = objectProto$c.hasOwnProperty; + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag$1 : getTag$1(object), + othTag = othIsArr ? arrayTag$1 : getTag$1(other); + + objTag = objTag == argsTag$2 ? objectTag$3 : objTag; + othTag = othTag == argsTag$2 ? objectTag$3 : othTag; + + var objIsObj = objTag == objectTag$3, + othIsObj = othTag == objectTag$3, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { + var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$4 = 1, + COMPARE_UNORDERED_FLAG$2 = 2; + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** Error message constants. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** Used to match property names within property paths. */ + var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** Used as references for various `Number` constants. */ + var INFINITY$1 = 1 / 0; + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$5 = 1, + COMPARE_UNORDERED_FLAG$3 = 2; + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); + }; + } + + /** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + function identity(value) { + return value; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ + function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + // validate object type + /** + * @TODO if provide with the keys then we need to check if the key:value type as well + * @param {object} value expected + * @param {array} [keys=null] if it has the keys array to compare as well + * @return {boolean} true if OK + */ + var checkIsObject = function(value, keys) { + if ( keys === void 0 ) keys=null; + + if (isPlainObject(value)) { + if (!keys) { + return true; + } + if (checkIsArray(keys)) { + // please note we DON'T care if some is optional + // plese refer to the contract.json for the keys + return !keys.filter(function (key) { + var _value = value[key.name]; + return !(key.type.length > key.type.filter(function (type) { + var tmp; + if (_value !== undefined) { + if ((tmp = isArrayLike(type)) !== false) { + return !arrayTypeHandler({arg: _value}, tmp) + // return tmp.filter(t => !checkIsArray(_value, t)).length; + // @TODO there might be an object within an object with keys as well :S + } + return !combineFn(type)(_value) + } + return true; + }).length) + }).length; + } + } + return false; + }; + + /** + * fold this into it's own function to handler different object type + * @param {object} p the prepared object for process + * @return {boolean} + */ + var objectTypeHandler = function(p) { + var arg = p.arg; + var param = p.param; + var _args = [arg]; + if (Array.isArray(param.keys) && param.keys.length) { + _args.push(param.keys); + } + // just simple check + return Reflect.apply(checkIsObject, null, _args) + }; + + // move the index.js code here that make more sense to find where things are + // import debug from 'debug' + // const debugFn = debug('jsonql-params-validator:validator') + // also export this for use in other places + + /** + * We need to handle those optional parameter without a default value + * @param {object} params from contract.json + * @return {boolean} for filter operation false is actually OK + */ + var optionalHandler = function( params ) { + var arg = params.arg; + var param = params.param; + if (isNotEmpty(arg)) { + // debug('call optional handler', arg, params); + // loop through the type in param + return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } + ).length) + } + return false; + }; + + /** + * actually picking the validator + * @param {*} type for checking + * @param {*} value for checking + * @return {boolean} true on OK + */ + var validateHandler = function(type, value) { + var tmp; + switch (true) { + case type === OBJECT_TYPE$1: + // debugFn('call OBJECT_TYPE') + return !objectTypeHandler(value) + case type === ARRAY_TYPE$1: + // debugFn('call ARRAY_TYPE') + return !checkIsArray(value.arg) + // @TODO when the type is not present, it always fall through here + // so we need to find a way to actually pre-check the type first + // AKA check the contract.json map before running here + case (tmp = isArrayLike(type)) !== false: + // debugFn('call ARRAY_LIKE: %O', value) + return !arrayTypeHandler(value, tmp) + default: + return !combineFn(type)(value.arg) + } + }; + + /** + * it get too longer to fit in one line so break it out from the fn below + * @param {*} arg value + * @param {object} param config + * @return {*} value or apply default value + */ + var getOptionalValue = function(arg, param) { + if (arg !== undefined) { + return arg; + } + return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null) + }; + + /** + * padding the arguments with defaultValue if the arguments did not provide the value + * this will be the name export + * @param {array} args normalized arguments + * @param {array} params from contract.json + * @return {array} merge the two together + */ + var normalizeArgs = function(args, params) { + // first we should check if this call require a validation at all + // there will be situation where the function doesn't need args and params + if (!checkIsArray(params)) { + // debugFn('params value', params) + throw new JsonqlError(PARAMS_NOT_ARRAY_ERR) + } + if (params.length === 0) { + return []; + } + if (!checkIsArray(args)) { + throw new JsonqlError(ARGS_NOT_ARRAY_ERR) + } + // debugFn(args, params); + // fall through switch + switch(true) { + case args.length == params.length: // standard + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, + param: params[i] + } + ); }) + case params[0].variable === true: // using spread syntax + var type = params[0].type; + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, // keep the index for reference + param: params[i] || { type: type, name: '_' } + } + ); }) + // with optional defaultValue parameters + case args.length < params.length: + return params.map(function (param, i) { return ( + { + param: param, + index: i, + arg: getOptionalValue(args[i], param), + optional: param.optional || false + } + ); }) + // this one pass more than it should have anything after the args.length will be cast as any type + case args.length > params.length: + var ctn = params.length; + // this happens when we have those array. type + var _type = [ DEFAULT_TYPE$1 ]; + // we only looking at the first one, this might be a @BUG + /* + if ((tmp = isArrayLike(params[0].type[0])) !== false) { + _type = tmp; + } */ + // if we use the params as guide then the rest will get throw out + // which is not what we want, instead, anything without the param + // will get a any type and optional flag + return args.map(function (arg, i) { + var optional = i >= ctn ? true : !!params[i].optional; + var param = params[i] || { type: _type, name: ("_" + i) }; + return { + arg: optional ? getOptionalValue(arg, param) : arg, + index: i, + param: param, + optional: optional + } + }) + // @TODO find out if there is more cases not cover + default: // this should never happen + // debugFn('args', args) + // debugFn('params', params) + // this is unknown therefore we just throw it! + throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) + } + }; + + // what we want is after the validaton we also get the normalized result + // which is with the optional property if the argument didn't provide it + /** + * process the array of params back to their arguments + * @param {array} result the params result + * @return {array} arguments + */ + var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; + + /** + * validator main interface + * @param {array} args the arguments pass to the method call + * @param {array} params from the contract for that method + * @param {boolean} [withResul=false] if true then this will return the normalize result as well + * @return {array} empty array on success, or failed parameter and reasons + */ + var validateSync = function(args, params, withResult) { + var obj; + + if ( withResult === void 0 ) withResult = false; + var cleanArgs = normalizeArgs(args, params); + var checkResult = cleanArgs.filter(function (p) { + // v1.4.4 this fixed the problem, the root level optional is from the last fn + if (p.optional === true || p.param.optional === true) { + return optionalHandler(p) + } + // because array of types means OR so if one pass means pass + return !(p.param.type.length > p.param.type.filter( + function (type) { return validateHandler(type, p); } + ).length) + }); + // using the same convention we been using all this time + return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) + }; + + /** + * A wrapper method that return promise + * @param {array} args arguments + * @param {array} params from contract.json + * @param {boolean} [withResul=false] if true then this will return the normalize result as well + * @return {object} promise.then or catch + */ + var validateAsync = function(args, params, withResult) { + if ( withResult === void 0 ) withResult = false; + + return new Promise(function (resolver, rejecter) { + var result = validateSync(args, params, withResult); + if (withResult) { + return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) + : resolver(result[DATA_KEY]) + } + // the different is just in the then or catch phrase + return result.length ? rejecter(result) : resolver([]) + }) + }; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** Detect free variable `exports`. */ + var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; + + /** Built-in value references. */ + var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, + allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** Built-in value references. */ + var objectCreate = Object.create; + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike$1(value); + } + + /** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; + } + + /** Used for built-in method references. */ + var objectProto$d = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$a = objectProto$d.hasOwnProperty; + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty$a.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** Used for built-in method references. */ + var objectProto$e = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$b = objectProto$e.hasOwnProperty; + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty$b.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike$1(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeMax = Math.max; + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ + function constant(value) { + return function() { + return value; + }; + } + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeNow = Date.now; + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike$1(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** Error message constants. */ + var FUNC_ERROR_TEXT$1 = 'Expected a function'; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$1); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols$1 = Object.getOwnPropertySymbols; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = baseIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(baseIteratee(predicate))); + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate), baseForOwn); + } + + /** + * @param {array} arr Array for check + * @param {*} value target + * @return {boolean} true on successs + */ + var isInArray = function(arr, value) { + return !!arr.filter(function (a) { return a === value; }).length; + }; + + var isObjectHasKey$2 = function(obj, key) { + var keys = Object.keys(obj); + return isInArray(keys, key) + }; + + // just not to make my head hurt + var isEmpty = function (value) { return !isNotEmpty(value); }; + + /** + * Map the alias to their key then grab their value over + * @param {object} config the user supplied config + * @param {object} appProps the default option map + * @return {object} the config keys replaced with the appProps key by the ALIAS + */ + function mapAliasConfigKeys(config, appProps) { + // need to do two steps + // 1. take key with alias key + var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$1]; } ); + if (isEqual(aliasMap, {})) { + return config; + } + return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) + } + + /** + * We only want to run the valdiation against the config (user supplied) value + * but keep the defaultOptions untouch + * @param {object} config configuraton supplied by user + * @param {object} appProps the default options map + * @return {object} the pristine values that will add back to the final output + */ + function preservePristineValues(config, appProps) { + // @BUG this will filter out those that is alias key + // we need to first map the alias keys back to their full key + var _config = mapAliasConfigKeys(config, appProps); + // take the default value out + var pristineValues = mapValues( + omitBy(appProps, function (value, key) { return isObjectHasKey$2(_config, key); }), + function (value) { return value.args; } + ); + // for testing the value + var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !isObjectHasKey$2(_config, key); }); + // output + return { + pristineValues: pristineValues, + checkAgainstAppProps: checkAgainstAppProps, + config: _config // passing this correct values back + } + } + + /** + * This will take the value that is ONLY need to check + * @param {object} config that one + * @param {object} props map for creating checking + * @return {object} put that arg into the args + */ + function processConfigAction(config, props) { + // debugFn('processConfigAction', props) + // v.1.2.0 add checking if its mark optional and the value is empty then pass + return mapValues(props, function (value, key) { + var obj, obj$1; + + return ( + config[key] === undefined || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) + ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) + : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) + ); + } + ) + } + + /** + * Quick transform + * @TODO we should only validate those that is pass from the config + * and pass through those values that is from the defaultOptions + * @param {object} opts that one + * @param {object} appProps mutation configuration options + * @return {object} put that arg into the args + */ + function prepareArgsForValidation(opts, appProps) { + var ref = preservePristineValues(opts, appProps); + var config = ref.config; + var pristineValues = ref.pristineValues; + var checkAgainstAppProps = ref.checkAgainstAppProps; + // output + return [ + processConfigAction(config, checkAgainstAppProps), + pristineValues + ] + } + + // breaking the whole thing up to see what cause the multiple calls issue + + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:options:validation') + + /** + * just make sure it returns an array to use + * @param {*} arg input + * @return {array} output + */ + var toArray$1 = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; + + /** + * DIY in array + * @param {array} arr to check against + * @param {*} value to check + * @return {boolean} true on OK + */ + var inArray$1 = function (arr, value) { return ( + !!arr.filter(function (v) { return v === value; }).length + ); }; + + /** + * break out to make the code easier to read + * @param {object} value to process + * @param {function} cb the validateSync + * @return {array} empty on success + */ + function validateHandler$1(value, cb) { + var obj; + + // cb is the validateSync methods + var args = [ + [ value[ARGS_KEY$1] ], + [( obj = {}, obj[TYPE_KEY$1] = toArray$1(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] + ]; + // debugFn('validateHandler', args) + return Reflect.apply(cb, null, args) + } + + /** + * Check against the enum value if it's provided + * @param {*} value to check + * @param {*} enumv to check against if it's not false + * @return {boolean} true on OK + */ + var enumHandler = function (value, enumv) { + if (checkIsArray(enumv)) { + return inArray$1(enumv, value) + } + return true; + }; + + /** + * Allow passing a function to check the value + * There might be a problem here if the function is incorrect + * and that will makes it hard to debug what is going on inside + * @TODO there could be a few feature add to this one under different circumstance + * @param {*} value to check + * @param {function} checker for checking + */ + var checkerHandler = function (value, checker) { + try { + return isFunction(checker) ? checker.apply(null, [value]) : false; + } catch (e) { + return false; + } + }; + + /** + * Taken out from the runValidaton this only validate the required values + * @param {array} args from the config2argsAction + * @param {function} cb validateSync + * @return {array} of configuration values + */ + function runValidationAction(cb) { + return function (value, key) { + // debugFn('runValidationAction', key, value) + if (value[KEY_WORD$1]) { + return value[ARGS_KEY$1] + } + var check = validateHandler$1(value, cb); + if (check.length) { + // log('runValidationAction', key, value) + throw new JsonqlTypeError(key, check) + } + if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { + // log(ENUM_KEY, value[ENUM_KEY]) + throw new JsonqlEnumError(key) + } + if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { + // log(CHECKER_KEY, value[CHECKER_KEY]) + throw new JsonqlCheckerError(key) + } + return value[ARGS_KEY$1] + } + } + + /** + * @param {object} args from the config2argsAction + * @param {function} cb validateSync + * @return {object} of configuration values + */ + function runValidation(args, cb) { + var argsForValidate = args[0]; + var pristineValues = args[1]; + // turn the thing into an array and see what happen here + // debugFn('_args', argsForValidate) + var result = mapValues(argsForValidate, runValidationAction(cb)); + return merge(result, pristineValues) + } + + // this is port back from the client to share across all projects + + /** + * @param {object} config user provide configuration option + * @param {object} appProps mutation configuration options + * @param {object} constProps the immutable configuration options + * @param {function} cb the validateSync method + * @return {object} Promise resolve merge config object + */ + function checkOptionsSync(config, appProps, constProps, cb) { + if ( config === void 0 ) config = {}; + + return merge( + runValidation( + prepareArgsForValidation(config, appProps), + cb + ), + constProps + ) + } + + // create function to construct the config entry so we don't need to keep building object + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:construct-config'); + /** + * @param {*} args value + * @param {string} type for value + * @param {boolean} [optional=false] + * @param {boolean|array} [enumv=false] + * @param {boolean|function} [checker=false] + * @return {object} config entry + */ + function constructConfig(args, type, optional, enumv, checker, alias) { + if ( optional === void 0 ) optional=false; + if ( enumv === void 0 ) enumv=false; + if ( checker === void 0 ) checker=false; + if ( alias === void 0 ) alias=false; + + var base = {}; + base[ARGS_KEY] = args; + base[TYPE_KEY] = type; + if (optional === true) { + base[OPTIONAL_KEY] = true; + } + if (checkIsArray(enumv)) { + base[ENUM_KEY] = enumv; + } + if (isFunction(checker)) { + base[CHECKER_KEY] = checker; + } + if (isString(alias)) { + base[ALIAS_KEY] = alias; + } + return base; + } + + // export also create wrapper methods + + /** + * This has a different interface + * @param {*} value to supply + * @param {string|array} type for checking + * @param {object} params to map against the config check + * @param {array} params.enumv NOT enum + * @param {boolean} params.optional false then nothing + * @param {function} params.checker need more work on this one later + * @param {string} params.alias mostly for cmd + */ + var createConfig = function (value, type, params) { + if ( params === void 0 ) params = {}; + + // Note the enumv not ENUM + // const { enumv, optional, checker, alias } = params; + // let args = [value, type, optional, enumv, checker, alias]; + var o = params[OPTIONAL_KEY]; + var e = params[ENUM_KEY]; + var c = params[CHECKER_KEY]; + var a = params[ALIAS_KEY]; + return constructConfig.apply(null, [value, type, o, e, c, a]) + }; + + // copy of above but it's sync + var checkConfig = function(validateSync) { + return function(config, appProps, constantProps) { + if ( constantProps === void 0 ) constantProps = {}; + + return checkOptionsSync(config, appProps, constantProps, validateSync) + } + }; + + // export + var isString$1 = checkIsString; + var isNumber$1 = checkIsNumber; + var validateAsync$1 = validateAsync; + + var createConfig$1 = createConfig; + var checkConfig$1 = checkConfig(validateSync); + + /** + * using just the map reduce to chain multiple functions together + * @param {function} mainFn the init function + * @param {array} moreFns as many as you want to take the last value and return a new one + * @return {function} accept value for the mainFn + */ + var chainFns = function (mainFn) { + var moreFns = [], len = arguments.length - 1; + while ( len-- > 0 ) moreFns[ len ] = arguments[ len + 1 ]; + + return ( + function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return ( + moreFns.reduce(function (value, nextFn) { return ( + // change here to check if the return value is array then we spread it + Reflect.apply(nextFn, null, toArray(value)) + ); }, Reflect.apply(mainFn, null, args)) + ); + } + ); + }; + + /** + * check if the object has name property + * @param {object} obj the object to check + * @param {string} name the prop name + * @return {*} the value or undefined + */ + function objHasProp(obj, name) { + var prop = Object.getOwnPropertyDescriptor(obj, name); + return prop !== undefined && prop.value ? prop.value : prop; + } + + /** + * 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 {string} name the name of the object to get inject also for checking + * @param {object} data to inject into the function static interface + * @param {boolean} [overwrite=false] if we want to overwrite the existing data + * @return {function} added property resolver + */ + function injectToFn(resolver, name, data, overwrite) { + if ( overwrite === void 0 ) overwrite = false; + + var check = objHasProp(resolver, name); + if (overwrite === false && check !== undefined) { + // console.info(`NOT INJECTED`) + return resolver; + } + /* this will throw error! + if (overwrite === true && check !== undefined) { + delete resolver[name] // delete this property + } + */ + // console.info(`INJECTED`) + Object.defineProperty(resolver, name, { + value: data, + writable: overwrite // if its set to true then we should able to overwrite it + }); + + return resolver; + } + + // breaking out the inner methods generator in here + + /** + * generate authorisation specific methods + * @param {object} jsonqlInstance instance of this + * @param {string} name of method + * @param {object} opts configuration + * @param {object} contract to match + * @return {function} for use + */ + var authMethodGenerator = function (jsonqlInstance, name, opts, contract) { + return function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var params = contract.auth[name].params; + var values = params.map(function (p, i) { return args[i]; }); + var header = args[params.length] || {}; + return validateAsync$1(args, params) + .then(function () { return jsonqlInstance + .query + .apply(jsonqlInstance, [name, values, header]); } + ) + .catch(finalCatch) + } + }; + + /** + * Break up the different type each - create query methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createQueryMethods = function (obj, jsonqlInstance, ee, config, contract) { + var query = {}; + var loop = function ( queryFn ) { + // to keep it clean we use a param to id the auth method + // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; + // generate the query method + query = injectToFn(query, queryFn, function queryFnHandler() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var params = contract.query[queryFn].params; + var _args = params.map(function (param, i) { return args[i]; }); + // debug('query', queryFn, _params); + // @TODO this need to change to a different way to add an extra header + var header = {}; + // @TODO validate against the type + return validateAsync$1(_args, params) + .then(function () { return jsonqlInstance + .query + .apply(jsonqlInstance, [queryFn, _args, header]); } + ) + .catch(finalCatch) + }); + }; + + for (var queryFn in contract.query) loop( queryFn ); + obj.query = query; + // create an alias to the helloWorld method + obj.helloWorld = query.helloWorld; + return [ obj, jsonqlInstance, ee, config, contract ] + }; + + /** + * create mutation methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createMutationMethods = function (obj, jsonqlInstance, ee, config, contract) { + var mutation = {}; + // process the mutation, the reason the mutation has a fixed number of parameters + // there is only the payload, and conditions parameters + // plus a header at the end + var loop = function ( mutationFn ) { + mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header) { + if ( header === void 0 ) header = {}; + + var args = [payload, conditions]; + var params = contract.mutation[mutationFn].params; + return validateAsync$1(args, params) + .then(function () { return jsonqlInstance + .mutation + .apply(jsonqlInstance, [mutationFn, payload, conditions, header]); } + ) + .catch(finalCatch) + }); + }; + + for (var mutationFn in contract.mutation) loop( mutationFn ); + obj.mutation = mutation; + return [ obj, jsonqlInstance, ee, config, contract ] + }; + + /** + * create auth methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createAuthMethods = function (obj, jsonqlInstance, ee, config, contract) { + if (config.enableAuth && contract.auth) { + var auth = {}; // v1.3.1 add back the auth prop name in contract + var loginHandlerName = config.loginHandlerName; + var logoutHandlerName = config.logoutHandlerName; + if (contract.auth[loginHandlerName]) { + // changing to the name the config specify + auth[loginHandlerName] = function loginHandlerFn() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract); + return fn.apply(null, args) + .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance)) + .then(function (token) { + ee.$trigger(LOGIN_NAME, token); + return token; + }) + }; + } + // @TODO allow to logout one particular profile or all of them + if (contract.auth[logoutHandlerName]) { + auth[logoutHandlerName] = function logoutHandlerFn() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract); + return fn.apply(null, args) + .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance)) + .then(function (r) { + ee.$trigger(LOGOUT_NAME, r); + return r; + }) + }; + } else { + auth[logoutHandlerName] = function logoutHandlerFn() { + jsonqlInstance.postLogoutAction(KEY_WORD); + ee.$trigger(LOGOUT_NAME, KEY_WORD); + }; + } + obj.auth = auth; + } + + return obj; + }; + + /** + * Here just generate the methods calls + * @param {object} jsonqlInstance what it said + * @param {object} ee event emitter + * @param {object} config configuration + * @param {object} contract the map + * @return {object} with mapped methods + */ + function methodsGenerator(jsonqlInstance, ee, config, contract) { + var obj = {}; + var executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods); + return executor(obj, jsonqlInstance, ee, config, contract) + } + + // This generator will use the old style + + /** + * Group all the same methods together + * @param {object} ee event emitters + * @param {string} type query, mutation or auth + * @param {string} resolverName use as the guide + * @param {array} args from the call + * @return {function} the handler itself + */ + var handler = function (ee, type) { + // we don't run validate here because we want until the contract is ready + return function (resolverName) { + var args = [], len = arguments.length - 1; + while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; + + return ( + new Promise(function (resolver, rejecter) { + // this are the callbacks + ee.$only(createEvt(type, resolverName, ON_RESULT_PROP_NAME), resolver); + ee.$only(createEvt(type, resolverName, ON_ERROR_PROP_NAME), rejecter); + // this is the main call + ee.$trigger(type, { resolverName: resolverName, args: args }); + }) + ); + } + }; + + /** + * @param {object} ee eventEmitter + * @param {object} contract the map + * @param {object} config configuration + */ + var validateRegisteredEvents = function (ee, contract, config) { + var storedEvt = ee.$queues; + var debug = config.debugOn; + if (debug) { + console.info('(validateRegisteredEvents)', 'storedEvt', storedEvt); + } + storedEvt.forEach(function (args) { + var type = args[0]; + var payload = args[1]; + var resolverName = payload.resolverName; + if (debug) { + console.info('(validateRegisteredEvents)', type, resolverName); + } + if (!contract[type][resolverName]) { + throw new Error((type + "." + resolverName + " not existed in contract!")) + } + }); + }; + + /** + * set up all the event handlers once the contract is ready + * @param {object} jsonqlInstance what the name said + * @param {object} ee event emitter + * @param {object} config the configuration + * @param {object} contract the map + * @return {void} nothing + */ + function setupEventHandlers(jsonqlInstance, ee, config, contract) { + var methods = methodsGenerator(jsonqlInstance, ee, config, contract); + validateRegisteredEvents(ee, contract, config); + // create handler + var loop = function ( type ) { + // setup event listeners - only one listener per type + ee.$only(type, function(ref) { + var resolverName = ref.resolverName; + var args = ref.args; + + if (methods[type][resolverName]) { + Reflect.apply(methods[type][resolverName], null, args) + .then(function (result) { + ee.$trigger(createEvt(type, resolverName, ON_RESULT_PROP_NAME), result); + }) + .catch(function (err) { + ee.$trigger(createEvt(type, resolverName, ON_ERROR_PROP_NAME), err); + }); + } else { + console.error((resolverName + " is not defined in the contract!")); + } + }); + }; + + for (var type in methods) loop( type ); + // all done now release the queue if any + setTimeout(function () { + ee.$suspend = false; + }, 1); + } + + /** + * @param {object} jsonqlInstance jsonql class instance + * @param {object} config options + * @param {object} contractPromise an unresolve promise + * @param {object} ee eventEmitter + * @return {object} constructed functions call + */ + var generator = function (jsonqlInstance, config, contractPromise, ee) { + ee.$suspend = true; // hold all the calls + // wait for the promise to resolve + contractPromise.then(function (contract) { + setupEventHandlers(jsonqlInstance, ee, config, contract); + }); + // construct the api + var obj = { + query: handler(ee, 'query'), + mutation: handler(ee, 'mutation'), + auth: handler(ee, 'auth') + }; + // allow getting the token for valdiate agains the socket + obj.getToken = function () { return jsonqlInstance.rawAuthToken; }; + // this will pass to the ws-client if needed + // obj.eventEmitter = ee; + // this will require a param + if (config.exposeContract) { + obj.getContract = function () { return jsonqlInstance.get(); }; + } + if (config.enableAuth) { + obj.userdata = function () { return jsonqlInstance.userdata; }; + } + obj.version = '1.5.1'; + // output + return obj; + }; + + // split the contract into the node side and the generic side + /** + * Check if the json is a contract file or not + * @param {object} contract json object + * @return {boolean} true + */ + function checkIsContract(contract) { + return isPlainObject(contract) + && ( + isObjectHasKey(contract, QUERY_NAME) + || isObjectHasKey(contract, MUTATION_NAME) + || isObjectHasKey(contract, SOCKET_NAME) + ) + } + + /** + * Wrapper method that check if it's contract then return the contract or false + * @param {object} contract the object to check + * @return {boolean | object} false when it's not + */ + function isContract(contract) { + return checkIsContract(contract) ? contract : false; + } + + /** + * generate a 32bit hash based on the function.toString() + * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery + * @param {string} s the converted to string function + * @return {string} the hashed function string + */ + function hashCode(s) { + return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) + } + + // take only the module part which is what we use here + /** + * @param {object} jsonqlInstance the init instance of jsonql client + * @param {object} contract the static contract + * @return {object} contract may be from server + */ + var getContractFromConfig = function(jsonqlInstance, contract) { + if ( contract === void 0 ) contract = {}; + + if (isContract(contract)) { + return Promise.resolve(contract) + } + return jsonqlInstance.getContract() + }; + // wrapper method to make sure it's a string + var hashCode$1 = function (str) { return hashCode(str) + ''; }; + var USERDATA_TABLE = 'userdata'; + var CLS_LOCAL_STORE_NAME = 'localStore'; + var CLS_SESS_STORE_NAME = 'sessionStore'; + var CLS_CONTRACT_NAME = 'contract'; + var CLS_PROFILE_IDX = 'prof_idx'; + var LOG_ERROR_SWITCH = '__error__'; + var ZERO_IDX = 0; + + /** + * The code was extracted from: + * https://github.com/davidchambers/Base64.js + */ + + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + + function InvalidCharacterError(message) { + this.message = message; + } + + InvalidCharacterError.prototype = new Error(); + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + + function polyfill (input) { + var str = String(input).replace(/=+$/, ''); + if (str.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); + } + for ( + // initialize result and counters + var bc = 0, bs, buffer, idx = 0, output = ''; + // get next character + buffer = str.charAt(idx++); + // character found in table? initialize bit storage and add its ascii value; + ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, + // and if not first of each 4 characters, + // convert the first 8 bits to one ascii character + bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 + ) { + // try to find character in table (0-63, not found => -1) + buffer = chars.indexOf(buffer); + } + return output; + } + + + var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; + + function b64DecodeUnicode(str) { + return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { + var code = p.charCodeAt(0).toString(16).toUpperCase(); + if (code.length < 2) { + code = '0' + code; + } + return '%' + code; + })); + } + + var base64_url_decode = function(str) { + var output = str.replace(/-/g, "+").replace(/_/g, "/"); + switch (output.length % 4) { + case 0: + break; + case 2: + output += "=="; + break; + case 3: + output += "="; + break; + default: + throw "Illegal base64url string!"; + } + + try{ + return b64DecodeUnicode(output); + } catch (err) { + return atob(output); + } + }; + + function InvalidTokenError(message) { + this.message = message; + } + + InvalidTokenError.prototype = new Error(); + InvalidTokenError.prototype.name = 'InvalidTokenError'; + + var lib = function (token,options) { + if (typeof token !== 'string') { + throw new InvalidTokenError('Invalid token specified'); + } + + options = options || {}; + var pos = options.header === true ? 0 : 1; + try { + return JSON.parse(base64_url_decode(token.split('.')[pos])); + } catch (e) { + throw new InvalidTokenError('Invalid token specified: ' + e.message); + } + }; + + var InvalidTokenError_1 = InvalidTokenError; + lib.InvalidTokenError = InvalidTokenError_1; + + // when the user is login with the jwt + + 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 = lib(token); + return validate(t) + } + throw new JsonqlError('Token must be a string!') + } + + var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; + + var appProps = { + algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), + expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), + notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), + audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), + subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), + issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), + noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), + header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), + keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), + mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) + }; + + /** + * @param {boolean} sec return in second or not + * @return {number} timestamp + */ + var timestamp$1 = function (sec) { + if ( sec === void 0 ) sec = false; + + var time = Date.now(); + return sec ? Math.floor( time / 1000 ) : time; + }; + + var assign = make_assign(); + var create = make_create(); + var trim$1 = make_trim(); + var Global = (typeof window !== 'undefined' ? window : commonjsGlobal); + + var util = { + assign: assign, + create: create, + trim: trim$1, + bind: bind, + slice: slice, + each: each, + map: map, + pluck: pluck, + isList: isList, + isFunction: isFunction$1, + isObject: isObject$1, + Global: Global + }; + + function make_assign() { + if (Object.assign) { + return Object.assign + } else { + return function shimAssign(obj, props1, props2, etc) { + var arguments$1 = arguments; + + for (var i = 1; i < arguments.length; i++) { + each(Object(arguments$1[i]), function(val, key) { + obj[key] = val; + }); + } + return obj + } + } + } + + function make_create() { + if (Object.create) { + return function create(obj, assignProps1, assignProps2, etc) { + var assignArgsList = slice(arguments, 1); + return assign.apply(this, [Object.create(obj)].concat(assignArgsList)) + } + } else { + function F() {} // eslint-disable-line no-inner-declarations + return function create(obj, assignProps1, assignProps2, etc) { + var assignArgsList = slice(arguments, 1); + F.prototype = obj; + return assign.apply(this, [new F()].concat(assignArgsList)) + } + } + } + + function make_trim() { + if (String.prototype.trim) { + return function trim(str) { + return String.prototype.trim.call(str) + } + } else { + return function trim(str) { + return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '') + } + } + } + + function bind(obj, fn) { + return function() { + return fn.apply(obj, Array.prototype.slice.call(arguments, 0)) + } + } + + function slice(arr, index) { + return Array.prototype.slice.call(arr, index || 0) + } + + function each(obj, fn) { + pluck(obj, function(val, key) { + fn(val, key); + return false + }); + } + + function map(obj, fn) { + var res = (isList(obj) ? [] : {}); + pluck(obj, function(v, k) { + res[k] = fn(v, k); + return false + }); + return res + } + + function pluck(obj, fn) { + if (isList(obj)) { + for (var i=0; i= 0; i--) { + var key = localStorage().key(i); + fn(read(key), key); + } + } + + function remove(key) { + return localStorage().removeItem(key) + } + + function clearAll() { + return localStorage().clear() + } + + // cookieStorage is useful Safari private browser mode, where localStorage + // doesn't work but cookies do. This implementation is adopted from + // https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage + + + var Global$2 = util.Global; + var trim$2 = util.trim; + + var cookieStorage = { + name: 'cookieStorage', + read: read$1, + write: write$1, + each: each$3, + remove: remove$1, + clearAll: clearAll$1, + }; + + var doc = Global$2.document; + + function read$1(key) { + if (!key || !_has(key)) { return null } + var regexpStr = "(?:^|.*;\\s*)" + + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"; + return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")) + } + + function each$3(callback) { + var cookies = doc.cookie.split(/; ?/g); + for (var i = cookies.length - 1; i >= 0; i--) { + if (!trim$2(cookies[i])) { + continue + } + var kvp = cookies[i].split('='); + var key = unescape(kvp[0]); + var val = unescape(kvp[1]); + callback(val, key); + } + } + + function write$1(key, data) { + if(!key) { return } + doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; + } + + function remove$1(key) { + if (!key || !_has(key)) { + return + } + doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; + } + + function clearAll$1() { + each$3(function(_, key) { + remove$1(key); + }); + } + + function _has(key) { + return (new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie) + } + + var defaults = defaultsPlugin; + + function defaultsPlugin() { + var defaultValues = {}; + + return { + defaults: defaults, + get: get + } + + function defaults(_, values) { + defaultValues = values; + } + + function get(super_fn, key) { + var val = super_fn(); + return (val !== undefined ? val : defaultValues[key]) + } + } + + var bind$2 = util.bind; + var each$4 = util.each; + var create$2 = util.create; + var slice$2 = util.slice; + + var events = eventsPlugin; + + function eventsPlugin() { + var pubsub = _newPubSub(); + + return { + watch: watch, + unwatch: unwatch, + once: once, + + set: set, + remove: remove, + clearAll: clearAll + } + + // new pubsub functions + function watch(_, key, listener) { + return pubsub.on(key, bind$2(this, listener)) + } + function unwatch(_, subId) { + pubsub.off(subId); + } + function once(_, key, listener) { + pubsub.once(key, bind$2(this, listener)); + } + + // overwrite function to fire when appropriate + function set(super_fn, key, val) { + var oldVal = this.get(key); + super_fn(); + pubsub.fire(key, val, oldVal); + } + function remove(super_fn, key) { + var oldVal = this.get(key); + super_fn(); + pubsub.fire(key, undefined, oldVal); + } + function clearAll(super_fn) { + var oldVals = {}; + this.each(function(val, key) { + oldVals[key] = val; + }); + super_fn(); + each$4(oldVals, function(oldVal, key) { + pubsub.fire(key, undefined, oldVal); + }); + } + } + + + function _newPubSub() { + return create$2(_pubSubBase, { + _id: 0, + _subSignals: {}, + _subCallbacks: {} + }) + } + + var _pubSubBase = { + _id: null, + _subCallbacks: null, + _subSignals: null, + on: function(signal, callback) { + if (!this._subCallbacks[signal]) { + this._subCallbacks[signal] = {}; + } + this._id += 1; + this._subCallbacks[signal][this._id] = callback; + this._subSignals[this._id] = signal; + return this._id + }, + off: function(subId) { + var signal = this._subSignals[subId]; + delete this._subCallbacks[signal][subId]; + delete this._subSignals[subId]; + }, + once: function(signal, callback) { + var subId = this.on(signal, bind$2(this, function() { + callback.apply(this, arguments); + this.off(subId); + })); + }, + fire: function(signal) { + var args = slice$2(arguments, 1); + each$4(this._subCallbacks[signal], function(callback) { + callback.apply(this, args); + }); + } + }; + + var lzString = createCommonjsModule(function (module) { + /* eslint-disable */ + // Copyright (c) 2013 Pieroxy + // This work is free. You can redistribute it and/or modify it + // under the terms of the WTFPL, Version 2 + // For more information see LICENSE.txt or http://www.wtfpl.net/ + // + // For more information, the home page: + // http://pieroxy.net/blog/pages/lz-string/testing.html + // + // LZ-based compression algorithm, version 1.4.4 + var LZString = (function() { + + // private property + var f = String.fromCharCode; + var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; + var baseReverseDic = {}; + + function getBaseValue(alphabet, character) { + if (!baseReverseDic[alphabet]) { + baseReverseDic[alphabet] = {}; + for (var i=0 ; i>> 8; + buf[i*2+1] = current_value % 256; + } + return buf; + }, + + //decompress from uint8array (UCS-2 big endian format) + decompressFromUint8Array:function (compressed) { + if (compressed===null || compressed===undefined){ + return LZString.decompress(compressed); + } else { + var buf=new Array(compressed.length/2); // 2 bytes per character + for (var i=0, TotalLen=buf.length; i> 1; + } + } else { + value = 1; + for (i=0 ; i> 1; + } + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + delete context_dictionaryToCreate[context_w]; + } else { + value = context_dictionary[context_w]; + for (i=0 ; i> 1; + } + + + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + // Add wc to the dictionary. + context_dictionary[context_wc] = context_dictSize++; + context_w = String(context_c); + } + } + + // Output the code for w. + if (context_w !== "") { + if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) { + if (context_w.charCodeAt(0)<256) { + for (i=0 ; i> 1; + } + } else { + value = 1; + for (i=0 ; i> 1; + } + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + delete context_dictionaryToCreate[context_w]; + } else { + value = context_dictionary[context_w]; + for (i=0 ; i> 1; + } + + + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + } + + // Mark the end of the stream + value = 2; + for (i=0 ; i> 1; + } + + // Flush the last char + while (true) { + context_data_val = (context_data_val << 1); + if (context_data_position == bitsPerChar-1) { + context_data.push(getCharFromInt(context_data_val)); + break; + } + else { context_data_position++; } + } + return context_data.join(''); + }, + + decompress: function (compressed) { + if (compressed == null) { return ""; } + if (compressed == "") { return null; } + return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); }); + }, + + _decompress: function (length, resetValue, getNextValue) { + var dictionary = [], + next, + enlargeIn = 4, + dictSize = 4, + numBits = 3, + entry = "", + result = [], + i, + w, + bits, resb, maxpower, power, + c, + data = {val:getNextValue(0), position:resetValue, index:1}; + + for (i = 0; i < 3; i += 1) { + dictionary[i] = i; + } + + bits = 0; + maxpower = Math.pow(2,2); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + switch (next = bits) { + case 0: + bits = 0; + maxpower = Math.pow(2,8); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + c = f(bits); + break; + case 1: + bits = 0; + maxpower = Math.pow(2,16); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + c = f(bits); + break; + case 2: + return ""; + } + dictionary[3] = c; + w = c; + result.push(c); + while (true) { + if (data.index > length) { + return ""; + } + + bits = 0; + maxpower = Math.pow(2,numBits); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + switch (c = bits) { + case 0: + bits = 0; + maxpower = Math.pow(2,8); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + dictionary[dictSize++] = f(bits); + c = dictSize-1; + enlargeIn--; + break; + case 1: + bits = 0; + maxpower = Math.pow(2,16); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + dictionary[dictSize++] = f(bits); + c = dictSize-1; + enlargeIn--; + break; + case 2: + return result.join(''); + } + + if (enlargeIn == 0) { + enlargeIn = Math.pow(2, numBits); + numBits++; + } + + if (dictionary[c]) { + entry = dictionary[c]; + } else { + if (c === dictSize) { + entry = w + w.charAt(0); + } else { + return null; + } + } + result.push(entry); + + // Add w+entry[0] to the dictionary. + dictionary[dictSize++] = w + entry.charAt(0); + enlargeIn--; + + w = entry; + + if (enlargeIn == 0) { + enlargeIn = Math.pow(2, numBits); + numBits++; + } + + } + } + }; + return LZString; + })(); + + if( module != null ) { + module.exports = LZString; + } + }); + + var compression = compressionPlugin; + + function compressionPlugin() { + return { + get: get, + set: set, + } + + function get(super_fn, key) { + var val = super_fn(key); + if (!val) { return val } + var decompressed = lzString.decompress(val); + // fallback to existing values that are not compressed + return (decompressed == null) ? val : this._deserialize(decompressed) + } + + function set(super_fn, key, val) { + var compressed = lzString.compress(this._serialize(val)); + super_fn(key, compressed); + } + } + + // sort of persist on the user side + + var storages = [localStorage_1, cookieStorage]; + var plugins = [defaults, events, compression]; + + var localStore = storeEngine.createStore(storages, plugins); + + var Global$3 = util.Global; + + var sessionStorage_1 = { + name: 'sessionStorage', + read: read$2, + write: write$2, + each: each$5, + remove: remove$2, + clearAll: clearAll$2 + }; + + function sessionStorage() { + return Global$3.sessionStorage + } + + function read$2(key) { + return sessionStorage().getItem(key) + } + + function write$2(key, data) { + return sessionStorage().setItem(key, data) + } + + function each$5(fn) { + for (var i = sessionStorage().length - 1; i >= 0; i--) { + var key = sessionStorage().key(i); + fn(read$2(key), key); + } + } + + function remove$2(key) { + return sessionStorage().removeItem(key) + } + + function clearAll$2() { + return sessionStorage().clear() + } + + // session store with watch + // @1.5.0 stop using the expired plugin and deal it ourself + // import expiredPlugin from 'store/plugins/expire' + + var storages$1 = [sessionStorage_1, cookieStorage]; + var plugins$1 = [defaults, compression]; + + var sessionStore = storeEngine.createStore(storages$1, plugins$1); + + // export store interface + + // export back the raw version for development purposes + var localStore$1 = localStore; + var sessionStore$1 = sessionStore; + + // ported from jsonql-params-validator + + /** + * @param {*} args arguments to send + *@return {object} formatted payload + */ + var formatPayload = function (args) { + var obj; + + return ( + ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) + ); + }; + + /** + * Get name from the payload (ported back from jsonql-koa) + * @param {*} payload to extract from + * @return {string} name + */ + function getNameFromPayload(payload) { + return Object.keys(payload)[0] + } + + /** + * wrapper method to add the timestamp as well + * @param {string} resolverName + * @param {*} payload + * @return {object} delierable + */ + function createDeliverable(resolverName, payload) { + var obj; + + return ( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME] = [ timestamp$1() ], obj ) + } + + /** + * @param {string} resolverName name of function + * @param {array} [args=[]] from the ...args + * @param {boolean} [jsonp = false] add v1.3.0 to koa + * @return {object} formatted argument + */ + function createQuery(resolverName, args, jsonp) { + if ( args === void 0 ) args = []; + if ( jsonp === void 0 ) jsonp = false; + + if (isString(resolverName) && isArray(args)) { + var payload = formatPayload(args); + if (jsonp === true) { + return payload; + } + return createDeliverable(resolverName, payload) + } + throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) + } + + /** + * @param {string} resolverName name of function + * @param {*} payload to send + * @param {object} [condition={}] for what + * @param {boolean} [jsonp = false] add v1.3.0 to koa + * @return {object} formatted argument + */ + function createMutation(resolverName, payload, condition, jsonp) { + if ( condition === void 0 ) condition = {}; + if ( jsonp === void 0 ) jsonp = false; + + var _payload = {}; + _payload[PAYLOAD_PARAM_NAME] = payload; + _payload[CONDITION_PARAM_NAME] = condition; + if (jsonp === true) { + return _payload; + } + if (isString(resolverName)) { + return createDeliverable(resolverName, _payload) + } + throw new JsonqlValidationError("[createMutation] expect resolverName to be string!", { resolverName: resolverName, payload: payload, condition: condition }) + } + + /** + * @return {object} _cb as key with timestamp + */ + var cacheBurst = function () { return ({ _cb: timestamp$1() }); }; + + // break up from node-middleware + + // ported from http-client + + /** + * handle the return data + * @TODO how to handle the return timestamp and calculate the diff? + * @param {object} result return from server + * @return {object} strip the data part out, or if the error is presented + */ + var resultHandler = function (result) { return ( + (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result + ); }; + + // new 1.5.0 + + // this becomes the base class instead of the HttpCls + var StoreClass = function StoreClass(opts) { + this.opts = opts; + // make it a string + this.instanceKey = hashCode$1(this.opts.hostname); + // pass this store for use later + this.localStore = localStore$1; + this.sessionStore = sessionStore$1; + /* + if (this.opts.debugOn) { // reuse this to clear out the data + this.log('clear all stores') + localStore.clearAll() + sessionStore.clearAll() + + localStore.set('TEST', Date.now()) + sessionStore.set('TEST', Date.now()) + } + */ + }; + + var prototypeAccessors = { lset: { configurable: true },lget: { configurable: true },sset: { configurable: true },sget: { configurable: true } }; + // store in local storage id by the instanceKey + // values should be an object so with key so we just merge + // into the existing store without going through the keys + StoreClass.prototype.__setMethod = function __setMethod (storeType, values) { + var obj; + + var store = this[storeType]; + var data = this.__getMethod(storeType); + var skey = this.opts.storageKey; + var ikey = this.instanceKey; + store.set(skey, ( obj = {}, obj[ikey] = data ? merge({}, data, values) : values, obj )); + }; + // return the data id by the instaceKey + StoreClass.prototype.__getMethod = function __getMethod (storeType) { + var store = this[storeType]; + var data = store.get(this.opts.storageKey); + return data ? data[this.instanceKey] : false + }; + // remove from local store id by instanceKey + StoreClass.prototype.__delMethod = function __delMethod (storeType, key) { + var data = this.__getMethod(storeType); + if (data) { + var store = {}; + for (var k in data) { + if (k !== key) { + store[k] = data[k]; + } + } + this.__setMethod(storeType, store); + } + }; + // clear everything by this instanceKey + StoreClass.prototype.__clearMethod = function __clearMethod (storeKey) { + var skey = this.opts.storageKey; + var store = this[storeKey]; + var data = store.get(skey); + if (data) { + var _store = {}; + for (var k in data) { + if (k !== this.instanceKey) { + _store[k] = data[k]; + } + } + store.set(skey, _store); + } + }; + // Alias for different store + prototypeAccessors.lset.set = function (values) { + return this.__setMethod(CLS_LOCAL_STORE_NAME, values) + }; + + prototypeAccessors.lget.get = function () { + return this.__getMethod(CLS_LOCAL_STORE_NAME) + }; + + StoreClass.prototype.ldel = function ldel (key) { + return this.__delMethod(CLS_LOCAL_STORE_NAME, key) + }; + + StoreClass.prototype.lclear = function lclear () { + return this.__clearMethod(CLS_LOCAL_STORE_NAME) + }; + + // store in session store id by the instanceKey + prototypeAccessors.sset.set = function (values) { + // this.log('--- sset ---', values) + return this.__setMethod(CLS_SESS_STORE_NAME, values) + }; + + prototypeAccessors.sget.get = function () { + return this.__getMethod(CLS_SESS_STORE_NAME) + }; + + StoreClass.prototype.sdel = function sdel (key) { + return this.__delMethod(CLS_SESS_STORE_NAME, key) + }; + + StoreClass.prototype.sclear = function sclear () { + return this.__clearMethod(CLS_SESS_STORE_NAME) + }; + + Object.defineProperties( StoreClass.prototype, prototypeAccessors ); + + // base HttpClass + + // extract the one we need + var POST = API_REQUEST_METHODS[0]; + var PUT = API_REQUEST_METHODS[1]; + + var HttpClass = /*@__PURE__*/(function (StoreClass) { + function HttpClass(opts) { + StoreClass.call(this, opts); + // change the way how we init Fly + // flyio now become external depedencies and it makes it easier to switch + // @BUG should we run test to check if we have the windows object? + // this.log(opts) + // this.fly = opts.Fly ? new opts.Fly() : new Fly() + // to a different environment like WeChat mini app + + this.extraHeader = {}; + // @1.2.1 for adding query to the call on the fly + this.extraParams = {}; + // this.log('start up opts', opts); + this.reqInterceptor(); + this.resInterceptor(); + } + + if ( StoreClass ) HttpClass.__proto__ = StoreClass; + HttpClass.prototype = Object.create( StoreClass && StoreClass.prototype ); + HttpClass.prototype.constructor = HttpClass; + + var prototypeAccessors = { headers: { configurable: true } }; + + // set headers for that one call + prototypeAccessors.headers.set = function (header) { + this.extraHeader = header; + }; + + /** + * Create the reusage request method + * @param {object} payload jsonql payload + * @param {object} options extra options add the request + * @param {object} headers extra headers add to the call + * @return {object} the fly request instance + */ + HttpClass.prototype.request = function request (payload, options, headers) { + var obj; + + if ( options === void 0 ) options = {}; + if ( headers === void 0 ) headers = {}; + this.headers = headers; + var params = merge({}, cacheBurst(), this.extraParams); + // @TODO need to add a jsonp url and payload + if (this.opts.enableJsonp) { + var resolverName = getNameFromPayload(payload); + params = merge({}, params, ( obj = {}, obj[JSONP_CALLBACK_NAME] = resolverName, obj )); + payload = payload[resolverName]; + } + // double up the url param and see what happen @TODO remove later + var reqParams = merge({}, { method: POST, params: params }, options); + this.log('request params', reqParams, this.jsonqlEndpoint); + + return this.fly.request(this.jsonqlEndpoint, payload, reqParams) + }; + + /** + * This will replace the create baseRequest method + * + */ + HttpClass.prototype.reqInterceptor = function reqInterceptor () { + var this$1 = this; + + this.fly.interceptors.request.use( + function (req) { + var headers = this$1.getHeaders(); + this$1.log('request interceptor call', headers); + + for (var key in headers) { + req.headers[key] = headers[key]; + } + return req; + } + ); + }; + + // @TODO + HttpClass.prototype.processJsonp = function processJsonp (result) { + return resultHandler(result) + }; + + /** + * This will be replacement of the first then call + * + */ + HttpClass.prototype.resInterceptor = function resInterceptor () { + var this$1 = this; + + var self = this; + var jsonp = self.opts.enableJsonp; + this.fly.interceptors.response.use( + function (res) { + this$1.log('response interceptor call', res); + self.cleanUp(); + // now more processing here + // there is a problem if we throw the result.error here + // the original data is lost, so we need to do what we did before + // deal with that error in the first then instead + var result = isString$1(res.data) ? JSON.parse(res.data) : res.data; + if (jsonp) { + return self.processJsonp(result) + } + return resultHandler(result) + }, + // this get call when it's not 200 + function (err) { + self.cleanUp(); + this$1.log(LOG_ERROR_SWITCH, err); + throw new JsonqlServerError('Server side error', err) + } + ); + }; + + /** + * Get the headers inject into the call + * @return {object} headers + */ + HttpClass.prototype.getHeaders = function getHeaders () { + if (this.opts.enableAuth) { + return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader) + } + return merge({}, DEFAULT_HEADER, this.extraHeader) + }; + + /** + * Post http call operation to clean up things we need + */ + HttpClass.prototype.cleanUp = function cleanUp () { + this.extraHeader = {}; + this.extraParams = {}; + }; + + /** + * GET for contract only + * @return {promise} resolve the contract + */ + HttpClass.prototype.getRemoteContract = function getRemoteContract () { + var this$1 = this; + + if (this.opts.showContractDesc) { + this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM); + } + return this.request({}, {method: 'GET'}, this.contractHeader) + .then(clientErrorsHandler) + .then(function (result) { + this$1.log('get contract result', result); + // when refresh the window the result is different! + // @TODO need to check the Koa side about why is that + // also it should set a flag if we want the description or not + if (result.cache && result.contract) { + return result.contract; + } + // just the normal result + return result + }) + .catch(function (err) { + this$1.log(LOG_ERROR_SWITCH, 'getRemoteContract err', err); + throw new JsonqlServerError('getRemoteContract', err) + }) + }; + + /** + * POST to server - query + * @param {object} name of the resolver + * @param {array} args arguments + * @return {object} promise resolve to the resolver return + */ + HttpClass.prototype.query = function query (name, args) { + if ( args === void 0 ) args = []; + + return this.request(createQuery(name, args)) + .then(clientErrorsHandler) + }; + + /** + * PUT to server - mutation + * @param {string} name of resolver + * @param {object} payload what it said + * @param {object} conditions what it said + * @return {object} promise resolve to the resolver return + */ + HttpClass.prototype.mutation = function mutation (name, payload, conditions) { + if ( payload === void 0 ) payload = {}; + if ( conditions === void 0 ) conditions = {}; + + return this.request(createMutation(name, payload, conditions), {method: PUT}) + .then(clientErrorsHandler) + }; + + Object.defineProperties( HttpClass.prototype, prototypeAccessors ); + + return HttpClass; + }(StoreClass)); + + // all the contract related methods will be here + + // export + var ContractClass = /*@__PURE__*/(function (HttpClass) { + function ContractClass(opts) { + HttpClass.call(this, opts); + } + + if ( HttpClass ) ContractClass.__proto__ = HttpClass; + ContractClass.prototype = Object.create( HttpClass && HttpClass.prototype ); + ContractClass.prototype.constructor = ContractClass; + + var prototypeAccessors = { contractHeader: { configurable: true } }; + + /** + * return the contract public api + * @return {object} contract + */ + ContractClass.prototype.getContract = function getContract () { + var contract = this.readContract(); + this.log('getContract first call', contract); + return contract ? Promise.resolve(contract) + : this.getRemoteContract().then(this.storeContract.bind(this)) + }; + + /** + * We are changing the way how to auth to get the contract.json + * Instead of in the url, we will be putting that key value in the header + * @return {object} header + */ + prototypeAccessors.contractHeader.get = function () { + var base = {}; + if (this.opts.contractKey !== false) { + base[this.opts.contractKeyName] = this.opts.contractKey; + } + return base; + }; + + /** + * Save the contract to local store + * @param {object} contract to save + * @return {object|boolean} false when its not a contract or contract on OK + */ + ContractClass.prototype.storeContract = function storeContract (contract) { + var obj; + + // first need to check if the contract is a contract + if (!isContract(contract)) { + throw new JsonqlValidationError("Contract is malformed!") + } + this.lset = ( obj = {}, obj[CLS_CONTRACT_NAME] = contract, obj ); + // return it + this.log('storeContract return result', contract); + return contract; + }; + + /** + * return the contract from options or localStore + * @return {object|boolean} false on not found + */ + ContractClass.prototype.readContract = function readContract () { + var contract = isContract(this.opts.contract); + if (contract !== false) { + return contract; + } + var data = this.lget; + if (data) { + return data[CLS_CONTRACT_NAME] + } + return false; + }; + + Object.defineProperties( ContractClass.prototype, prototypeAccessors ); + + return ContractClass; + }(HttpClass)); + + // this is the new auth class that integrate with the jsonql-jwt + // export + var AuthClass = /*@__PURE__*/(function (ContractClass) { + function AuthClass(opts) { + ContractClass.call(this, opts); + if (opts.enableAuth) { + this.setDecoder = jwtDecode; + } + } + + if ( ContractClass ) AuthClass.__proto__ = ContractClass; + AuthClass.prototype = Object.create( ContractClass && ContractClass.prototype ); + AuthClass.prototype.constructor = AuthClass; + + var prototypeAccessors = { profileIndex: { configurable: true },setDecoder: { configurable: true },saveProfile: { configurable: true },readProfile: { configurable: true },jsonqlToken: { configurable: true },jsonqlUserdata: { configurable: true } }; + + /** + * for overwrite + * @param {string} token stored token + * @return {string} token + */ + AuthClass.prototype.decoder = function decoder (token) { + return token; + }; + + /** + * set the profile index + * @param {number} idx + */ + prototypeAccessors.profileIndex.set = function (idx) { + var obj; + + var key = CLS_PROFILE_IDX; + if (isNumber$1(idx)) { + this[key] = idx; + if (this.opts.persistToken) { + this.lset = ( obj = {}, obj[key] = idx, obj ); + } + return; + } + throw new JsonqlValidationError('profileIndex', ("Expect idx to be number but got " + (typeof idx))) + }; + + /** + * get the profile index + * @return {number} idx + */ + prototypeAccessors.profileIndex.get = function () { + var key = CLS_PROFILE_IDX; + if (this.opts.persistToken) { + var data = this.lget; + if (data[key]) { + return data[key] + } + } + return this[key] ? this[key] : ZERO_IDX + }; + + /** + * Return the token from session store + * @param {number} [idx=false] profile index + * @return {string} token + */ + AuthClass.prototype.rawAuthToken = function rawAuthToken (idx) { + if ( idx === void 0 ) idx = false; + + if (idx !== false) { + this.profileIndex = idx; + } + // this should return from the base + return this.jsonqlToken; // see base-cls + }; + + /** + * Setter to add a decoder when retrieve user token + * @param {function} d a decoder + */ + prototypeAccessors.setDecoder.set = function (d) { + if (typeof d === 'function') { + this.decoder = d; + } + }; + + /** + * getter to return the session or local store set method + * @param {*} data to save + * @return {object} set method + */ + prototypeAccessors.saveProfile.set = function (data) { + if (this.opts.persistToken) { + // this.log('--- saveProfile lset ---', data) + this.lset = data; + } else { + // this.log('--- saveProfile sset ---', data) + this.sset = data; + } + }; + + /** + * getter to return the session or local store get method + * @return {object} get method + */ + prototypeAccessors.readProfile.get = function () { + return this.opts.persistToken ? this.lget : this.sget + }; + + // these were in the base class before but it should be here + /** + * save token + * @param {string} token to store + * @return {string|boolean} false on failed + */ + prototypeAccessors.jsonqlToken.set = function (token) { + var obj; + + var data = this.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + // @TODO also have to make sure the token is not already existed! + var tokens = (data && data[key]) ? data[key] : []; + tokens.push(token); + this.saveProfile = ( obj = {}, obj[key] = tokens, obj ); + // store the userdata + this.jsonqlUserdata = this.decoder(token); + }; + + /** + * Jsonql token getter + * 1.5.1 each token associate with the same profileIndex + * @return {string|boolean} false when failed + */ + prototypeAccessors.jsonqlToken.get = function () { + var data = this.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + if (data && data[key]) { + this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex]); + return data[key][this.profileIndex] + } + return false + }; + + /** + * this one will use the sessionStore + * basically we hook this onto the token store and decode it to store here + * we only store one decoded user data at a time, but the token can be multiple + */ + prototypeAccessors.jsonqlUserdata.set = function (userdata) { + var obj; + + this.sset = ( obj = {}, obj[USERDATA_TABLE] = userdata, obj ); + }; + + /** + * this one store in the session store + * get login userdata decoded jwt + * 1.5.1 each userdata associate with the same profileIndex + * @return {object|null} + */ + prototypeAccessors.jsonqlUserdata.get = function () { + var data = this.sget; + return data ? data[USERDATA_TABLE] : false + }; + + /** + * Construct the auth header + * @return {object} header + */ + AuthClass.prototype.getAuthHeader = function getAuthHeader () { + var obj; + + var token = this.jsonqlToken; // only call the getter to get the default one + return token ? ( obj = {}, obj[this.opts.AUTH_HEADER] = (BEARER + " " + token), obj ) : {}; + }; + + /** + * return all the stored token and decode it + * @param {number} [idx=false] profile index + * @return {array|boolean|string} false not found or array + */ + AuthClass.prototype.getProfiles = function getProfiles (idx) { + if ( idx === void 0 ) idx = false; + + var self = this; // just in case the scope problem + var data = self.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + if (data && data[key]) { + if (idx !== false && isNumber$1(idx)) { + return data[key][idx] || false + } + return data[key].map(self.decoder.bind(self)) + } + return false + }; + + /** + * call after the login + * @param {string} token return from server + * @return {object} decoded token to userdata object + */ + AuthClass.prototype.postLoginAction = function postLoginAction (token) { + this.jsonqlToken = token; + return token + }; + + /** + * call after the logout @TODO + */ + AuthClass.prototype.postLogoutAction = function postLogoutAction () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + console.info("postLogoutAction", args); + }; + + Object.defineProperties( AuthClass.prototype, prototypeAccessors ); + + return AuthClass; + }(ContractClass)); + + // this the core of the internal storage management + + // This class will only focus on the storage system + var JsonqlBaseClient = /*@__PURE__*/(function (AuthCls) { + function JsonqlBaseClient(fly, opts) { + // change at 1.4.10 pass it directly without init it + this.fly = fly; + AuthCls.call(this, opts); + } + + if ( AuthCls ) JsonqlBaseClient.__proto__ = AuthCls; + JsonqlBaseClient.prototype = Object.create( AuthCls && AuthCls.prototype ); + JsonqlBaseClient.prototype.constructor = JsonqlBaseClient; + + var prototypeAccessors = { jsonqlEndpoint: { configurable: true } }; + + /** + * construct the end point + * @return {string} the end point to call + */ + prototypeAccessors.jsonqlEndpoint.get = function () { + var baseUrl = this.opts.hostname || ''; + return [baseUrl, this.opts.jsonqlPath].join('/') + }; + + /** + * simple log + */ + JsonqlBaseClient.prototype.log = function log () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (this.opts.debugOn === true) { + var fns = ['info', 'error']; + var idx = (args[0] === LOG_ERROR_SWITCH) ? 1 : 0; + Reflect.apply(console[fns[idx]], console, args.splice(0, idx)); + } + }; + + Object.defineProperties( JsonqlBaseClient.prototype, prototypeAccessors ); + + return JsonqlBaseClient; + }(AuthClass)); + + // export interface + + // all the client configuration options here + var constProps = { + contract: false, + MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong? + CONTENT_TYPE: CONTENT_TYPE, + BEARER: BEARER, + AUTH_HEADER: AUTH_HEADER + }; + + // grab the localhost name and put into the hostname as default + var getHostName = function () { + try { + return [window.location.protocol, window.location.host].join('//') + } catch(e) { + return null + } + }; + + var appProps$1 = { + + hostname: createConfig$1(getHostName(), [STRING_TYPE]), // required the hostname + jsonqlPath: createConfig$1(JSONQL_PATH, [STRING_TYPE]), // The path on the server + + loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), + logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), + // add to koa v1.3.0 - this might remove in the future + enableJsonp: createConfig$1(false, [BOOLEAN_TYPE]), + enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), + // enable useJwt by default @TODO replace with something else and remove them later + useJwt: createConfig$1(true, [BOOLEAN_TYPE]), + // when true then store infinity or pass a time in seconds then we check against + // the token date of creation + persistToken: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE]), + // the header + // v1.2.0 we are using this option during the dev + // so it won't save anything to the localstorage and fetch a new contract + // whenever the browser reload + useLocalstorage: createConfig$1(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage + storageKey: createConfig$1(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage + authKey: createConfig$1(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage + contractExpired: createConfig$1(0, [NUMBER_TYPE]),// -1 always fetch contract, + // 0 never expired, + // > 0 then compare the timestamp with the current one to see if we need to get contract again + // useful during development + keepContract: createConfig$1(true, [BOOLEAN_TYPE]), + exposeContract: createConfig$1(false, [BOOLEAN_TYPE]), + exposeStore: createConfig$1(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn + // @1.2.1 new option for the contract-console to fetch the contract with description + showContractDesc: createConfig$1(false, [BOOLEAN_TYPE]), + contractKey: createConfig$1(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this + contractKeyName: createConfig$1(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs + enableTimeout: createConfig$1(false, [BOOLEAN_TYPE]), // @TODO + timeout: createConfig$1(5000, [NUMBER_TYPE]), // 5 seconds + returnInstance: createConfig$1(false, [BOOLEAN_TYPE]), + allowReturnRawToken: createConfig$1(false, [BOOLEAN_TYPE]), + debugOn: createConfig$1(false, [BOOLEAN_TYPE]) + }; + + // This is for the sync version therefore we don't need to care about the contract options + + function checkOptions(config) { + return checkConfig$1(config, appProps$1, constProps) + } + + // export interface + + // sync version without needing the promise + function checkOptions$1(config) { + return objHasProp(config, CHECKED_KEY) ? config : checkOptions(config) + } + + var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); + var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); + + // making all the functionality on it's own + // import { WatchClass } from './watch' + + var SuspendClass = function SuspendClass() { + // suspend, release and queue + this.__suspend__ = null; + this.queueStore = new Set(); + /* + this.watch('suspend', function(value, prop, oldValue) { + this.logger(`${prop} set from ${oldValue} to ${value}`) + // it means it set the suspend = true then release it + if (oldValue === true && value === false) { + // we want this happen after the return happens + setTimeout(() => { + this.release() + }, 1) + } + return value; // we need to return the value to store it + }) + */ + }; + + var prototypeAccessors$1 = { $suspend: { configurable: true },$queues: { configurable: true } }; + + /** + * setter to set the suspend and check if it's boolean value + * @param {boolean} value to trigger + */ + prototypeAccessors$1.$suspend.set = function (value) { + var this$1 = this; + + if (typeof value === 'boolean') { + var lastValue = this.__suspend__; + this.__suspend__ = value; + this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); + if (lastValue === true && value === false) { + setTimeout(function () { + this$1.release(); + }, 1); + } + } else { + throw new Error("$suspend only accept Boolean value!") + } + }; + + /** + * queuing call up when it's in suspend mode + * @param {any} value + * @return {Boolean} true when added or false when it's not + */ + SuspendClass.prototype.$queue = function $queue () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (this.__suspend__ === true) { + this.logger('($queue)', 'added to $queue', args); + // there shouldn't be any duplicate ... + this.queueStore.add(args); + } + return this.__suspend__; + }; + + /** + * a getter to get all the store queue + * @return {array} Set turn into Array before return + */ + prototypeAccessors$1.$queues.get = function () { + var size = this.queueStore.size; + this.logger('($queues)', ("size: " + size)); + if (size > 0) { + return Array.from(this.queueStore) + } + return [] + }; + + /** + * Release the queue + * @return {int} size if any + */ + SuspendClass.prototype.release = function release () { + var this$1 = this; + + var size = this.queueStore.size; + this.logger('(release)', ("Release was called " + size)); + if (size > 0) { + var queue = Array.from(this.queueStore); + this.queueStore.clear(); + this.logger('queue', queue); + queue.forEach(function (args) { + this$1.logger(args); + Reflect.apply(this$1.$trigger, this$1, args); + }); + this.logger(("Release size " + (this.queueStore.size))); + } + }; + + Object.defineProperties( SuspendClass.prototype, prototypeAccessors$1 ); + + // break up the main file because its getting way too long + + var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { + function NbEventServiceBase(config) { + if ( config === void 0 ) config = {}; + + SuspendClass.call(this); + if (config.logger && typeof config.logger === 'function') { + this.logger = config.logger; + } + this.keep = config.keep; + // for the $done setter + this.result = config.keep ? [] : null; + // we need to init the store first otherwise it could be a lot of checking later + this.normalStore = new Map(); + this.lazyStore = new Map(); + } + + if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; + NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); + NbEventServiceBase.prototype.constructor = NbEventServiceBase; + + var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; + + /** + * validate the event name(s) + * @param {string[]} evt event name + * @return {boolean} true when OK + */ + NbEventServiceBase.prototype.validateEvt = function validateEvt () { + var this$1 = this; + var evt = [], len = arguments.length; + while ( len-- ) evt[ len ] = arguments[ len ]; + + evt.forEach(function (e) { + if (typeof e !== 'string') { + this$1.logger('(validateEvt)', e); + throw new Error("event name must be string type!") + } + }); + return true; + }; + + /** + * Simple quick check on the two main parameters + * @param {string} evt event name + * @param {function} callback function to call + * @return {boolean} true when OK + */ + NbEventServiceBase.prototype.validate = function validate (evt, callback) { + if (this.validateEvt(evt)) { + if (typeof callback === 'function') { + return true; + } + } + throw new Error("callback required to be function type!") + }; + + /** + * Check if this type is correct or not added in V1.5.0 + * @param {string} type for checking + * @return {boolean} true on OK + */ + NbEventServiceBase.prototype.validateType = function validateType (type) { + var types = ['on', 'only', 'once', 'onlyOnce']; + return !!types.filter(function (t) { return type === t; }).length; + }; + + /** + * Run the callback + * @param {function} callback function to execute + * @param {array} payload for callback + * @param {object} ctx context or null + * @return {void} the result store in $done + */ + NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { + this.logger('(run)', callback, payload, ctx); + this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); + }; + + /** + * Take the content out and remove it from store id by the name + * @param {string} evt event name + * @param {string} [storeName = lazyStore] name of store + * @return {object|boolean} content or false on not found + */ + NbEventServiceBase.prototype.takeFromStore = function takeFromStore (evt, storeName) { + if ( storeName === void 0 ) storeName = 'lazyStore'; + + var store = this[storeName]; // it could be empty at this point + if (store) { + this.logger('(takeFromStore)', storeName, store); + if (store.has(evt)) { + var content = store.get(evt); + this.logger('(takeFromStore)', ("has " + evt), content); + store.delete(evt); + return content; + } + return false; + } + throw new Error((storeName + " is not supported!")) + }; + + /** + * The add to store step is similar so make it generic for resuse + * @param {object} store which store to use + * @param {string} evt event name + * @param {spread} args because the lazy store and normal store store different things + * @return {array} store and the size of the store + */ + NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { + var args = [], len = arguments.length - 2; + while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; + + var fnSet; + if (store.has(evt)) { + this.logger('(addToStore)', (evt + " existed")); + fnSet = store.get(evt); + } else { + this.logger('(addToStore)', ("create new Set for " + evt)); + // this is new + fnSet = new Set(); + } + // lazy only store 2 items - this is not the case in V1.6.0 anymore + // we need to check the first parameter is string or not + if (args.length > 2) { + if (Array.isArray(args[0])) { // lazy store + // check if this type of this event already register in the lazy store + var t = args[2]; + if (!this.checkTypeInLazyStore(evt, t)) { + fnSet.add(args); + } + } else { + if (!this.checkContentExist(args, fnSet)) { + this.logger('(addToStore)', "insert new", args); + fnSet.add(args); + } + } + } else { // add straight to lazy store + fnSet.add(args); + } + store.set(evt, fnSet); + return [store, fnSet.size] + }; + + /** + * @param {array} args for compare + * @param {object} fnSet A Set to search from + * @return {boolean} true on exist + */ + NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { + var list = Array.from(fnSet); + return !!list.filter(function (l) { + var hash = l[0]; + if (hash === args[0]) { + return true; + } + return false; + }).length; + }; + + /** + * get the existing type to make sure no mix type add to the same store + * @param {string} evtName event name + * @param {string} type the type to check + * @return {boolean} true you can add, false then you can't add this type + */ + NbEventServiceBase.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { + this.validateEvt(evtName, type); + var all = this.$get(evtName, true); + if (all === false) { + // pristine it means you can add + return true; + } + // it should only have ONE type in ONE event store + return !all.filter(function (list) { + var t = list[3]; + return type !== t; + }).length; + }; + + /** + * This is checking just the lazy store because the structure is different + * therefore we need to use a new method to check it + */ + NbEventServiceBase.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { + this.validateEvt(evtName, type); + var store = this.lazyStore.get(evtName); + this.logger('(checkTypeInLazyStore)', store); + if (store) { + return !!Array + .from(store) + .filter(function (l) { + var t = l[2]; + return t !== type; + }).length + } + return false; + }; + + /** + * wrapper to re-use the addToStore, + * V1.3.0 add extra check to see if this type can add to this evt + * @param {string} evt event name + * @param {string} type on or once + * @param {function} callback function + * @param {object} context the context the function execute in or null + * @return {number} size of the store + */ + NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { + if ( context === void 0 ) context = null; + + this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); + // @TODO we need to check the existing store for the type first! + if (this.checkTypeInStore(evt, type)) { + this.logger('(addToNormalStore)', (type + " can add to " + evt + " normal store")); + var key = this.hashFnToKey(callback); + var args = [this.normalStore, evt, key, callback, context, type]; + var ref = Reflect.apply(this.addToStore, this, args); + var _store = ref[0]; + var size = ref[1]; + this.normalStore = _store; + return size; + } + return false; + }; + + /** + * Add to lazy store this get calls when the callback is not register yet + * so we only get a payload object or even nothing + * @param {string} evt event name + * @param {array} payload of arguments or empty if there is none + * @param {object} [context=null] the context the callback execute in + * @param {string} [type=false] register a type so no other type can add to this evt + * @return {number} size of the store + */ + NbEventServiceBase.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { + if ( payload === void 0 ) payload = []; + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = false; + + // this is add in V1.6.0 + // when there is type then we will need to check if this already added in lazy store + // and no other type can add to this lazy store + var args = [this.lazyStore, evt, this.toArray(payload), context]; + if (type) { + args.push(type); + } + var ref = Reflect.apply(this.addToStore, this, args); + var _store = ref[0]; + var size = ref[1]; + this.lazyStore = _store; + return size; + }; + + /** + * make sure we store the argument correctly + * @param {*} arg could be array + * @return {array} make sured + */ + NbEventServiceBase.prototype.toArray = function toArray (arg) { + return Array.isArray(arg) ? arg : [arg]; + }; + + /** + * setter to store the Set in private + * @param {object} obj a Set + */ + prototypeAccessors.normalStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); + }; + + /** + * @return {object} Set object + */ + prototypeAccessors.normalStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) + }; + + /** + * setter to store the Set in lazy store + * @param {object} obj a Set + */ + prototypeAccessors.lazyStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); + }; + + /** + * @return {object} the lazy store Set + */ + prototypeAccessors.lazyStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) + }; + + /** + * generate a hashKey to identify the function call + * The build-in store some how could store the same values! + * @param {function} fn the converted to string function + * @return {string} hashKey + */ + NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { + return hashCode(fn.toString()) + ''; + }; + + Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); + + return NbEventServiceBase; + }(SuspendClass)); + + // The top level + // export + var EventService = /*@__PURE__*/(function (NbStoreService) { + function EventService(config) { + if ( config === void 0 ) config = {}; + + NbStoreService.call(this, config); + } + + if ( NbStoreService ) EventService.__proto__ = NbStoreService; + EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); + EventService.prototype.constructor = EventService; + + var prototypeAccessors = { $done: { configurable: true } }; + + /** + * logger function for overwrite + */ + EventService.prototype.logger = function logger () {}; + + ////////////////////////// + // PUBLIC METHODS // + ////////////////////////// + + /** + * Register your evt handler, note we don't check the type here, + * we expect you to be sensible and know what you are doing. + * @param {string} evt name of event + * @param {function} callback bind method --> if it's array or not + * @param {object} [context=null] to execute this call in + * @return {number} the size of the store + */ + EventService.prototype.$on = function $on (evt , callback , context) { + var this$1 = this; + if ( context === void 0 ) context = null; + + var type = 'on'; + this.validate(evt, callback); + // first need to check if this evt is in lazy store + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register first then call later + if (lazyStoreContent === false) { + this.logger('($on)', (evt + " callback is not in lazy store")); + // @TODO we need to check if there was other listener to this + // event and are they the same type then we could solve that + // register the different type to the same event name + + return this.addToNormalStore(evt, type, callback, context) + } + this.logger('($on)', (evt + " found in lazy store")); + // this is when they call $trigger before register this callback + var size = 0; + lazyStoreContent.forEach(function (content) { + var payload = content[0]; + var ctx = content[1]; + var t = content[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this$1.logger("($on)", ("call run on " + evt)); + this$1.run(callback, payload, context || ctx); + size += this$1.addToNormalStore(evt, type, callback, context || ctx); + }); + return size; + }; + + /** + * once only registered it once, there is no overwrite option here + * @NOTE change in v1.3.0 $once can add multiple listeners + * but once the event fired, it will remove this event (see $only) + * @param {string} evt name + * @param {function} callback to execute + * @param {object} [context=null] the handler execute in + * @return {boolean} result + */ + EventService.prototype.$once = function $once (evt , callback , context) { + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'once'; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (lazyStoreContent === false) { + this.logger('($once)', (evt + " not in the lazy store")); + // v1.3.0 $once now allow to add multiple listeners + return this.addToNormalStore(evt, type, callback, context) + } else { + // now this is the tricky bit + // there is a potential bug here that cause by the developer + // if they call $trigger first, the lazy won't know it's a once call + // so if in the middle they register any call with the same evt name + // then this $once call will be fucked - add this to the documentation + this.logger('($once)', lazyStoreContent); + var list = Array.from(lazyStoreContent); + // should never have more than 1 + var ref = list[0]; + var payload = ref[0]; + var ctx = ref[1]; + var t = ref[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this.logger('($once)', ("call run for " + evt)); + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); + } + }; + + /** + * This one event can only bind one callbackback + * @param {string} evt event name + * @param {function} callback event handler + * @param {object} [context=null] the context the event handler execute in + * @return {boolean} true bind for first time, false already existed + */ + EventService.prototype.$only = function $only (evt, callback, context) { + var this$1 = this; + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'only'; + var added = false; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (!nStore.has(evt)) { + this.logger("($only)", (evt + " add to store")); + added = this.addToNormalStore(evt, type, callback, context); + } + if (lazyStoreContent !== false) { + // there are data store in lazy store + this.logger('($only)', (evt + " found data in lazy store to execute")); + var list = Array.from(lazyStoreContent); + // $only allow to trigger this multiple time on the single handler + list.forEach( function (l) { + var payload = l[0]; + var ctx = l[1]; + var t = l[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this$1.logger("($only)", ("call run for " + evt)); + this$1.run(callback, payload, context || ctx); + }); + } + return added; + }; + + /** + * $only + $once this is because I found a very subtile bug when we pass a + * resolver, rejecter - and it never fire because that's OLD added in v1.4.0 + * @param {string} evt event name + * @param {function} callback to call later + * @param {object} [context=null] exeucte context + * @return {void} + */ + EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'onlyOnce'; + var added = false; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (!nStore.has(evt)) { + this.logger("($onlyOnce)", (evt + " add to store")); + added = this.addToNormalStore(evt, type, callback, context); + } + if (lazyStoreContent !== false) { + // there are data store in lazy store + this.logger('($onlyOnce)', lazyStoreContent); + var list = Array.from(lazyStoreContent); + // should never have more than 1 + var ref = list[0]; + var payload = ref[0]; + var ctx = ref[1]; + var t = ref[2]; + if (t && t !== 'onlyOnce') { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this.logger("($onlyOnce)", ("call run for " + evt)); + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); + } + return added; + }; + + /** + * This is a shorthand of $off + $on added in V1.5.0 + * @param {string} evt event name + * @param {function} callback to exeucte + * @param {object} [context = null] or pass a string as type + * @param {string} [type=on] what type of method to replace + * @return {} + */ + EventService.prototype.$replace = function $replace (evt, callback, context, type) { + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = 'on'; + + if (this.validateType(type)) { + this.$off(evt); + var method = this['$' + type]; + this.logger("($replace)", evt, callback); + return Reflect.apply(method, this, [evt, callback, context]) + } + throw new Error((type + " is not supported!")) + }; + + /** + * trigger the event + * @param {string} evt name NOT allow array anymore! + * @param {mixed} [payload = []] pass to fn + * @param {object|string} [context = null] overwrite what stored + * @param {string} [type=false] if pass this then we need to add type to store too + * @return {number} if it has been execute how many times + */ + EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { + if ( payload === void 0 ) payload = []; + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = false; + + this.validateEvt(evt); + var found = 0; + // first check the normal store + var nStore = this.normalStore; + this.logger('($trigger)', 'normalStore', nStore); + if (nStore.has(evt)) { + // @1.8.0 to add the suspend queue + var added = this.$queue(evt, payload, context, type); + this.logger('($trigger)', evt, 'found; add to queue: ', added); + if (added === true) { + this.logger('($trigger)', evt, 'not executed. Exit now.'); + return false; // not executed + } + var nSet = Array.from(nStore.get(evt)); + var ctn = nSet.length; + var hasOnce = false; + for (var i=0; i < ctn; ++i) { + ++found; + // this.logger('found', found) + var ref = nSet[i]; + var _ = ref[0]; + var callback = ref[1]; + var ctx = ref[2]; + var type$1 = ref[3]; + this.logger("($trigger)", ("call run for " + evt)); + this.run(callback, payload, context || ctx); + if (type$1 === 'once' || type$1 === 'onlyOnce') { + hasOnce = true; + } + } + if (hasOnce) { + nStore.delete(evt); + } + return found; + } + // now this is not register yet + this.addToLazyStore(evt, payload, context, type); + return found; + }; + + /** + * this is an alias to the $trigger + * @NOTE breaking change in V1.6.0 we swap the parameter around + * @param {string} evt event name + * @param {*} params pass to the callback + * @param {string} type of call + * @param {object} context what context callback execute in + * @return {*} from $trigger + */ + EventService.prototype.$call = function $call (evt, params, type, context) { + if ( type === void 0 ) type = false; + if ( context === void 0 ) context = null; + + var args = [evt, params, context, type]; + return Reflect.apply(this.$trigger, this, args) + }; + + /** + * remove the evt from all the stores + * @param {string} evt name + * @return {boolean} true actually delete something + */ + EventService.prototype.$off = function $off (evt) { + var this$1 = this; + + this.validateEvt(evt); + var stores = [ this.lazyStore, this.normalStore ]; + var found = false; + stores.forEach(function (store) { + if (store.has(evt)) { + found = true; + this$1.logger('($off)', evt); + store.delete(evt); + } + }); + return found; + }; + + /** + * return all the listener from the event + * @param {string} evtName event name + * @param {boolean} [full=false] if true then return the entire content + * @return {array|boolean} listerner(s) or false when not found + */ + EventService.prototype.$get = function $get (evt, full) { + if ( full === void 0 ) full = false; + + this.validateEvt(evt); + var store = this.normalStore; + if (store.has(evt)) { + return Array + .from(store.get(evt)) + .map( function (l) { + if (full) { + return l; + } + var key = l[0]; + var callback = l[1]; + return callback; + }) + } + return false; + }; + + /** + * store the return result from the run + * @param {*} value whatever return from callback + */ + prototypeAccessors.$done.set = function (value) { + this.logger('($done)', 'value: ', value); + if (this.keep) { + this.result.push(value); + } else { + this.result = value; + } + }; + + /** + * @TODO is there any real use with the keep prop? + * getter for $done + * @return {*} whatever last store result + */ + prototypeAccessors.$done.get = function () { + if (this.keep) { + this.logger('(get $done)', this.result); + return this.result[this.result.length - 1] + } + return this.result; + }; + + Object.defineProperties( EventService.prototype, prototypeAccessors ); + + return EventService; + }(NbEventServiceBase)); + + // default + + // this will generate a event emitter and will be use everywhere + // output + function getEventEmitter(debugOn) { + var logger = debugOn ? function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + args.unshift('[NBS]'); + console.log.apply(null, args); + }: undefined; + return new EventService({ logger: logger }) + } + + // this is the new Event base interface + /** + * this is the slim client without Fly, you pick the version of Fly to use + * This is a breaking change because it swap the input positions + * @param {object} fly fly.js + * @param {object} config configuration + * @return {object} the jsonql client instance + */ + function jsonqlStaticClient(fly, config) { + if ( config === void 0 ) config = {}; + + var contract = config.contract; + var opts = checkOptions$1(config); + var jsonqlBase = new JsonqlBaseClient(fly, opts); + var contractPromise = getContractFromConfig(jsonqlBase, contract); + var ee = getEventEmitter(opts.debugOn); + // finally + var methods = generator(jsonqlBase, opts, contractPromise, ee); + methods.eventEmitter = ee; + return methods; + } + + // This is the static version that build with the Fly for Browser + + // this is the slim client without Fly + function jsonqlStaticClientFull(config) { + if ( config === void 0 ) config = {}; + + return jsonqlStaticClient(new Fly(), config) + } + + return jsonqlStaticClientFull; + +}))); //# sourceMappingURL=jsonql-client.static.js.map diff --git a/packages/http-client/dist/jsonql-client.static.js.map b/packages/http-client/dist/jsonql-client.static.js.map index 9e063d38..fa64e484 100644 --- a/packages/http-client/dist/jsonql-client.static.js.map +++ b/packages/http-client/dist/jsonql-client.static.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client.static.js","sources":["../node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"+/hDAAA"} \ No newline at end of file +{"version":3,"file":"jsonql-client.static.js","sources":["../node_modules/lodash-es/isArray.js","../node_modules/rollup-plugin-node-globals/src/global.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/lodash-es/_arrayMap.js","../node_modules/lodash-es/_baseSlice.js","../node_modules/lodash-es/_baseFindIndex.js","../node_modules/lodash-es/_baseIsNaN.js","../node_modules/lodash-es/_strictIndexOf.js","../node_modules/lodash-es/_asciiToArray.js","../node_modules/lodash-es/_hasUnicode.js","../node_modules/lodash-es/_unicodeToArray.js","../node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-errors/src/resolver-not-found-error.js","../node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-errors/src/index.js","../node_modules/jsonql-errors/src/client-errors-handler.js","../node_modules/jsonql-params-validator/src/number.js","../node_modules/jsonql-params-validator/src/string.js","../node_modules/jsonql-params-validator/src/boolean.js","../node_modules/jsonql-params-validator/src/any.js","../node_modules/jsonql-params-validator/src/constants.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/_listCacheClear.js","../node_modules/lodash-es/eq.js","../node_modules/lodash-es/_stackDelete.js","../node_modules/lodash-es/_stackGet.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-params-validator/src/validator.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/negate.js","../node_modules/lodash-es/_baseFindKey.js","../node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-params-validator/src/options/check-options-sync.js","../node_modules/jsonql-params-validator/src/options/construct-config.js","../node_modules/jsonql-params-validator/src/options/index.js","../node_modules/jsonql-params-validator/index.js","../src/core/methods-generator.js","../src/core/jsonql-static-generator.js","../node_modules/jsonql-utils/src/contract.js","../node_modules/nb-event-service/src/hash-code.js","../src/utils.js","../node_modules/jwt-decode/lib/atob.js","../node_modules/jsonql-jwt/src/client/decode-token/decode-token.js","../node_modules/jsonql-utils/src/timestamp.js","../node_modules/store/plugins/defaults.js","../src/stores/local-store.js","../src/stores/session-store.js","../src/stores/index.js","../node_modules/jsonql-utils/src/params-api.js","../node_modules/jsonql-utils/src/results.js","../src/base/store-cls.js","../src/base/http-cls.js","../src/base/contract-cls.js","../src/base/auth-cls.js","../src/base/base-cls.js","../src/base/index.js","../src/options/base-options.js","../src/options/check-options.js","../src/options/index.js","../node_modules/nb-event-service/src/suspend.js","../node_modules/nb-event-service/src/store-service.js","../node_modules/nb-event-service/src/event-service.js","../node_modules/nb-event-service/index.js","../src/ee.js","../src/static.js","../src/static-full.js"],"sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length;\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg];\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @return {*} json object on success\n */\nconst parse = function(n) {\n try {\n return JSON.parse(n)\n } catch(e) {\n return n;\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false;\n /*\n console.info('obj', obj)\n console.error(e)\n throw new Error(e)\n */\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = (n) => {\n if (typeof n === 'string') {\n return parse(n)\n }\n return JSON.parse(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== '';\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n","/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error)\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","/**\n * This is a custom error to throw when could not find the resolver\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class JsonqlResolverNotFoundError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlResolverNotFoundError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlResolverNotFoundError);\n }\n }\n\n static get statusCode() {\n return 404;\n }\n\n static get name() {\n return 'JsonqlResolverNotFoundError';\n }\n}\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError);\n }\n }\n\n static get name() {\n return 'JsonqlEnumError';\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlTypeError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError);\n }\n }\n\n static get name() {\n return 'JsonqlTypeError';\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args)\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError)\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError';\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError';\n }\n}\n","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message)\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// server side\nimport Jsonql406Error from './406-error'\nimport Jsonql500Error from './500-error'\n\nimport JsonqlForbiddenError from './forbidden-error'\nimport JsonqlAuthorisationError from './authorisation-error'\nimport JsonqlContractAuthError from './contract-auth-error'\nimport JsonqlResolverAppError from './resolver-app-error'\nimport JsonqlResolverNotFoundError from './resolver-not-found-error'\n\n// check options error\nimport JsonqlEnumError from './enum-error'\nimport JsonqlTypeError from './type-error'\nimport JsonqlCheckerError from './checker-error'\n// share\nimport JsonqlValidationError from './validation-error'\nimport JsonqlError from './error'\n\nimport JsonqlServerError from './server-error'\n\nexport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlForbiddenError,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n};\n","// this will add directly to the then call in each http call\n\nimport * as errors from './index'\nimport getErrorByStatus from './get-error-by-status'\nimport { NO_ERROR_MSG } from 'jsonql-constants'\nconst { JsonqlError } = errors\n\n/**\n * We can not just check something like result.data what if the result if false?\n * @param {object} obj the result object\n * @param {string} key we want to check if its exist or not\n * @return {boolean} true on found\n */\nconst isObjectHasKey = (obj, key) => {\n const keys = Object.keys(obj)\n return !!keys.filter(k => key === k).length;\n}\n\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nexport default function clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false;\n}\n\nexport default checkIsString\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nexport const ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\n","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber;\n case STRING_TYPE:\n return checkIsString;\n case BOOLEAN_TYPE:\n return checkIsBoolean;\n default:\n return checkIsAny;\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false;\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false;\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p;\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length;\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length;\n}\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport filter from 'lodash-es/filter'\n\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true;\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (_value !== undefined) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true;\n }).length)\n }).length;\n }\n }\n return false;\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p;\n let _args = [arg];\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return Reflect.apply(checkIsObject, null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\n\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n checkIsObject,\n combineFn,\n notEmpty\n} from './index'\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params;\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false;\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (arg !== undefined) {\n return arg;\n }\n return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ))\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ))\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ))\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length:\n let ctn = params.length;\n // this happens when we have those array. type\n let _type = [ DEFAULT_TYPE ]\n // we only looking at the first one, this might be a @BUG\n /*\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n } */\n // if we use the params as guide then the rest will get throw out\n // which is not what we want, instead, anything without the param\n // will get a any type and optional flag\n return args.map((arg, i) => {\n let optional = i >= ctn ? true : !!params[i].optional\n let param = params[i] || { type: _type, name: `_${i}` }\n return {\n arg: optional ? getOptionalValue(arg, param) : arg,\n index: i,\n param,\n optional\n }\n })\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n // v1.4.4 this fixed the problem, the root level optional is from the last fn\n if (p.optional === true || p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length;\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport isFunction from 'lodash-es/isFunction'\nimport merge from 'lodash-es/merge'\nimport mapValues from 'lodash-es/mapValues'\n\nimport JsonqlEnumError from 'jsonql-errors/src/enum-error'\nimport JsonqlTypeError from 'jsonql-errors/src/type-error'\nimport JsonqlCheckerError from 'jsonql-errors/src/checker-error'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true;\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // log('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n // log(ENUM_KEY, value[ENUM_KEY])\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n // log(CHECKER_KEY, value[CHECKER_KEY])\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args;\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","// this is port back from the client to share across all projects\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return merge(\n runValidation(\n prepareArgsForValidation(config, appProps),\n cb\n ),\n constProps\n )\n}\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\nimport checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n };\n if (optional === true) {\n base[OPTIONAL_KEY] = true;\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv;\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker;\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias;\n }\n return base;\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__';\n\n/**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n checkConfigAsync,\n checkConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nexport const inArray = isInArray;\nexport const isObjectHasKey = isObjectHasKeyFn;\n","// breaking out the inner methods generator in here\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { LOGOUT_NAME, LOGIN_NAME, KEY_WORD } from 'jsonql-constants'\nimport { chainFns } from 'jsonql-utils/src/chain-fns'\nimport { injectToFn } from 'jsonql-utils/src/obj-define-props'\n\n/**\n * generate authorisation specific methods\n * @param {object} jsonqlInstance instance of this\n * @param {string} name of method\n * @param {object} opts configuration\n * @param {object} contract to match\n * @return {function} for use\n */\nconst authMethodGenerator = (jsonqlInstance, name, opts, contract) => {\n return (...args) => {\n const params = contract.auth[name].params;\n const values = params.map((p, i) => args[i])\n const header = args[params.length] || {};\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [name, values, header])\n )\n .catch(finalCatch)\n }\n}\n\n/**\n * Break up the different type each - create query methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let query = {}\n for (let queryFn in contract.query) {\n // to keep it clean we use a param to id the auth method\n // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn;\n // generate the query method\n query = injectToFn(query, queryFn, function queryFnHandler(...args) {\n const params = contract.query[queryFn].params;\n const _args = params.map((param, i) => args[i])\n // debug('query', queryFn, _params);\n // @TODO this need to change to a different way to add an extra header\n const header = {}\n // @TODO validate against the type\n return validateAsync(_args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [queryFn, _args, header])\n )\n .catch(finalCatch)\n })\n }\n obj.query = query;\n // create an alias to the helloWorld method\n obj.helloWorld = query.helloWorld;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create mutation methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let mutation = {}\n // process the mutation, the reason the mutation has a fixed number of parameters\n // there is only the payload, and conditions parameters\n // plus a header at the end\n for (let mutationFn in contract.mutation) {\n mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header = {}) {\n const args = [payload, conditions];\n const params = contract.mutation[mutationFn].params;\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .mutation\n .apply(jsonqlInstance, [mutationFn, payload, conditions, header])\n )\n .catch(finalCatch)\n })\n }\n obj.mutation = mutation;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create auth methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createAuthMethods = (obj, jsonqlInstance, ee, config, contract) => {\n if (config.enableAuth && contract.auth) {\n let auth = {} // v1.3.1 add back the auth prop name in contract\n const { loginHandlerName, logoutHandlerName } = config;\n if (contract.auth[loginHandlerName]) {\n // changing to the name the config specify\n auth[loginHandlerName] = function loginHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance))\n .then(token => {\n ee.$trigger(LOGIN_NAME, token)\n return token;\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) {\n auth[logoutHandlerName] = function logoutHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance))\n .then(r => {\n ee.$trigger(LOGOUT_NAME, r)\n return r;\n })\n }\n } else {\n auth[logoutHandlerName] = function logoutHandlerFn() {\n jsonqlInstance.postLogoutAction(KEY_WORD)\n ee.$trigger(LOGOUT_NAME, KEY_WORD)\n }\n }\n obj.auth = auth;\n }\n\n return obj;\n}\n\n/**\n * Here just generate the methods calls\n * @param {object} jsonqlInstance what it said\n * @param {object} ee event emitter\n * @param {object} config configuration\n * @param {object} contract the map\n * @return {object} with mapped methods\n */\nexport function methodsGenerator(jsonqlInstance, ee, config, contract) {\n let obj = {}\n const executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods)\n return executor(obj, jsonqlInstance, ee, config, contract)\n}\n","// This generator will use the old style\n// with default methods\nimport { ON_RESULT_PROP_NAME, ON_ERROR_PROP_NAME } from 'jsonql-constants'\nimport { createEvt } from 'jsonql-utils/src/generic'\n\nimport { methodsGenerator } from './methods-generator'\n\n/**\n * Group all the same methods together\n * @param {object} ee event emitters\n * @param {string} type query, mutation or auth\n * @param {string} resolverName use as the guide\n * @param {array} args from the call\n * @return {function} the handler itself\n */\nconst handler = (ee, type) => {\n // we don't run validate here because we want until the contract is ready\n return (resolverName, ...args) => (\n new Promise((resolver, rejecter) => {\n // this are the callbacks\n ee.$only(createEvt(type, resolverName, ON_RESULT_PROP_NAME), resolver)\n ee.$only(createEvt(type, resolverName, ON_ERROR_PROP_NAME), rejecter)\n // this is the main call\n ee.$trigger(type, { resolverName, args })\n })\n )\n}\n\n/**\n * @param {object} ee eventEmitter\n * @param {object} contract the map\n * @param {object} config configuration\n */\nconst validateRegisteredEvents = (ee, contract, config) => {\n const storedEvt = ee.$queues;\n const debug = config.debugOn;\n if (debug) {\n console.info('(validateRegisteredEvents)', 'storedEvt', storedEvt)\n }\n storedEvt.forEach(args => {\n let [type, payload] = args;\n let { resolverName } = payload;\n if (debug) {\n console.info('(validateRegisteredEvents)', type, resolverName)\n }\n if (!contract[type][resolverName]) {\n throw new Error(`${type}.${resolverName} not existed in contract!`)\n }\n })\n}\n\n/**\n * set up all the event handlers once the contract is ready\n * @param {object} jsonqlInstance what the name said\n * @param {object} ee event emitter\n * @param {object} config the configuration\n * @param {object} contract the map\n * @return {void} nothing\n */\nfunction setupEventHandlers(jsonqlInstance, ee, config, contract) {\n let methods = methodsGenerator(jsonqlInstance, ee, config, contract)\n validateRegisteredEvents(ee, contract, config)\n // create handler\n for (let type in methods) {\n // setup event listeners - only one listener per type\n ee.$only(type, function({resolverName, args}) {\n if (methods[type][resolverName]) {\n Reflect.apply(methods[type][resolverName], null, args)\n .then(result => {\n ee.$trigger(createEvt(type, resolverName, ON_RESULT_PROP_NAME), result)\n })\n .catch(err => {\n ee.$trigger(createEvt(type, resolverName, ON_ERROR_PROP_NAME), err)\n })\n } else {\n console.error(`${resolverName} is not defined in the contract!`)\n }\n })\n }\n // all done now release the queue if any\n setTimeout(() => {\n ee.$suspend = false;\n }, 1)\n}\n\n/**\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} config options\n * @param {object} contractPromise an unresolve promise\n * @param {object} ee eventEmitter\n * @return {object} constructed functions call\n */\nconst generator = (jsonqlInstance, config, contractPromise, ee) => {\n ee.$suspend = true; // hold all the calls\n // wait for the promise to resolve\n contractPromise.then(contract => {\n setupEventHandlers(jsonqlInstance, ee, config, contract)\n })\n // construct the api\n let obj = {\n query: handler(ee, 'query'),\n mutation: handler(ee, 'mutation'),\n auth: handler(ee, 'auth')\n }\n // allow getting the token for valdiate agains the socket\n obj.getToken = () => jsonqlInstance.rawAuthToken;\n // this will pass to the ws-client if needed\n // obj.eventEmitter = ee;\n // this will require a param\n if (config.exposeContract) {\n obj.getContract = () => jsonqlInstance.get()\n }\n if (config.enableAuth) {\n obj.userdata = () => jsonqlInstance.userdata;\n }\n obj.version = '__VERSION__';\n // output\n return obj;\n}\n\nexport default generator;\n","// split the contract into the node side and the generic side\nimport { isObjectHasKey } from './generic'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n SOCKET_NAME,\n QUERY_ARG_NAME,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlResolverNotFoundError } from 'jsonql-errors'\n/**\n * Check if the json is a contract file or not\n * @param {object} contract json object\n * @return {boolean} true\n */\nexport function checkIsContract(contract) {\n return isPlainObject(contract)\n && (\n isObjectHasKey(contract, QUERY_NAME)\n || isObjectHasKey(contract, MUTATION_NAME)\n || isObjectHasKey(contract, SOCKET_NAME)\n )\n}\n\n/**\n * Wrapper method that check if it's contract then return the contract or false\n * @param {object} contract the object to check\n * @return {boolean | object} false when it's not\n */\nexport function isContract(contract) {\n return checkIsContract(contract) ? contract : false;\n}\n\n/**\n * Ported from jsonql-params-validator but different\n * if we don't find the socket part then return false\n * @param {object} contract the contract object\n * @return {object|boolean} false on failed\n */\nexport function extractSocketPart(contract) {\n if (isObjectHasKey(contract, 'socket')) {\n return contract.socket;\n }\n return false;\n}\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @param {boolean} [fallback=false] this is a fall back option for old code\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport function groupByNamespace(contract, fallback = false) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n if (fallback) {\n return contract; // just return the whole contract\n }\n throw new JsonqlError(`socket not found in contract!`)\n }\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\n}\n\n/**\n * @NOTE ported from jsonql-ws-client\n * Got to make sure the connection order otherwise\n * it will hang\n * @param {object} nspSet contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspSet, publicNamespace) {\n let names = []; // need to make sure the order!\n for (let namespace in nspSet) {\n if (namespace === publicNamespace) {\n names[1] = namespace;\n } else {\n names[0] = namespace;\n }\n }\n return names;\n}\n\n\n/**\n * Extract the args from the payload\n * @param {object} payload to work with\n * @param {string} type of call\n * @return {array} args\n */\nexport function extractArgsFromPayload(payload, type) {\n switch (type) {\n case QUERY_NAME:\n return payload[QUERY_ARG_NAME];\n case MUTATION_NAME:\n return [\n payload[PAYLOAD_PARAM_NAME],\n payload[CONDITION_PARAM_NAME]\n ];\n default:\n throw new JsonqlError(`Unknown ${type} to extract argument from!`)\n }\n}\n\n/**\n * Like what the name said\n * @param {object} contract the contract json\n * @param {string} type query|mutation\n * @param {string} name of the function\n * @return {object} the params part of the contract\n */\nexport function extractParamsFromContract(contract, type, name) {\n try {\n const result = contract[type][name];\n // debug('extractParamsFromContract', result)\n if (!result) {\n // debug(name, type, contract)\n throw new JsonqlResolverNotFoundError(name, type)\n }\n return result;\n } catch(e) {\n throw new JsonqlResolverNotFoundError(name, e)\n }\n}\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport default function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n","// take only the module part which is what we use here\n// and export it again to use through out the client\n// this way we avoid those that we don't want node.js module got build into the code\nimport { isContract } from 'jsonql-utils/src/contract'\nimport hashCodeFn from 'nb-event-service/src/hash-code'\n/**\n * @param {object} jsonqlInstance the init instance of jsonql client\n * @param {object} contract the static contract\n * @return {object} contract may be from server\n */\nconst getContractFromConfig = function(jsonqlInstance, contract = {}) {\n if (isContract(contract)) {\n return Promise.resolve(contract)\n }\n return jsonqlInstance.getContract()\n}\n// wrapper method to make sure it's a string\nconst hashCode = str => hashCodeFn(str) + ''\n\n// simple util to check if an object has any properties\n// const hasProp = obj => isObject(obj) && Object.keys(obj).length\n\n// export some constants as well\n// since it's only use here there is no point of adding it to the constants module\n// or may be we add it back later\nconst ENDPOINT_TABLE = 'endpoint' // not in use anymore delete later @TODO\nconst USERDATA_TABLE = 'userdata'\nconst CLS_LOCAL_STORE_NAME = 'localStore'\nconst CLS_SESS_STORE_NAME = 'sessionStore'\nconst CLS_CONTRACT_NAME = 'contract'\nconst CLS_PROFILE_IDX = 'prof_idx'\nconst LOG_ERROR_SWITCH = '__error__'\nconst ZERO_IDX = 0\n// export\nexport {\n hashCode,\n getContractFromConfig,\n ENDPOINT_TABLE,\n USERDATA_TABLE,\n CLS_LOCAL_STORE_NAME,\n CLS_SESS_STORE_NAME,\n CLS_CONTRACT_NAME,\n CLS_PROFILE_IDX,\n LOG_ERROR_SWITCH,\n ZERO_IDX\n}\n","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\nfunction polyfill (input) {\n var str = String(input).replace(/=+$/, '');\n if (str.length % 4 == 1) {\n throw new InvalidCharacterError(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = '';\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n return output;\n}\n\n\nmodule.exports = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill;\n","// when the user is login with the jwt\n// we use call this to decode the token and then add the payload\n// to the resolver so the user can call ResolverName.userdata\n// and get back the payload\nimport jwt_decode from 'jwt-decode'\nimport isString from 'jsonql-params-validator/src/string'\nimport JsonqlError from 'jsonql-errors/src/error'\n\nconst timestamp = function (sec = false) {\n var time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n\n/**\n * We only check the nbf and exp\n * @param {object} token for checking\n * @return {object} token on success\n */\nfunction validate(token) {\n const start = token.iat || timestamp(true)\n // we only check the exp for the time being\n if (token.exp) {\n if (start >= token.exp) {\n const expired = new Date(token.exp).toISOString()\n throw new JsonqlError(`Token has expired on ${expired}`, token)\n }\n }\n return token;\n}\n\n/**\n * The browser client version it has far fewer options and it doesn't verify it\n * because it couldn't this is the job for the server\n * @TODO we need to add some extra proessing here to check for the exp field\n * @param {string} token to decrypted\n * @return {object} decrypted object\n */\nexport default function jwtDecode(token) {\n if (isString(token)) {\n const t = jwt_decode(token)\n return validate(t)\n }\n throw new JsonqlError('Token must be a string!')\n}\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n","module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n","// sort of persist on the user side\nimport engine from 'store/src/store-engine'\n\nimport localStorage from 'store/storages/localStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// @1.5.0 stop using the expired plugin, and deal with it ourself\n// import expiredPlugin from 'store/plugins/expire'\nimport eventsPlugin from 'store/plugins/events'\nimport compressionPlugin from 'store/plugins/compression'\n\nconst storages = [localStorage, cookieStorage]\nconst plugins = [defaultPlugin, eventsPlugin, compressionPlugin]\n\nconst localStore = engine.createStore(storages, plugins)\n\nexport default localStore\n","// session store with watch\nimport engine from 'store/src/store-engine'\n\nimport sessionStorage from 'store/storages/sessionStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// start using compression in 1.5.0 \nimport compressionPlugin from 'store/plugins/compression'\n// @1.5.0 stop using the expired plugin and deal it ourself\n// import expiredPlugin from 'store/plugins/expire'\n\nconst storages = [sessionStorage, cookieStorage]\nconst plugins = [defaultPlugin, compressionPlugin]\n\nconst sessionStore = engine.createStore(storages, plugins)\n\nexport default sessionStore\n","// export store interface\n// @TODO need to figure out how to make this as a outside dependencies instead of built into it\nimport localStoreEngine from './local-store'\nimport sessionStoreEngine from './session-store'\n\n// export back the raw version for development purposes\nexport const localStore = localStoreEngine\nexport const sessionStore = sessionStoreEngine\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport isString from 'lodash-es/isString'\n\nimport { timestamp } from './timestamp'\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? JSON.parse(payload) : payload;\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName\n * @param {*} payload\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload) {\n return {\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload;\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload;\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getNameFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// break up from node-middleware\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n API_REQUEST_METHODS,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME ,\n QUERY_ARG_NAME,\n DATA_KEY,\n ERROR_KEY,\n INDEX_KEY,\n EXT,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport { isObjectHasKey } from './generic'\nimport { timestamp } from './timestamp'\nimport isArray from 'lodash-es/isArray'\nimport merge from 'lodash-es/merge'\n/**\n * getting what is calling after the above check\n * @param {string} method of call\n * @return {mixed} false on failed\n */\nexport const getCallMethod = method => {\n const [ POST, PUT ] = API_REQUEST_METHODS;\n switch (true) {\n case method === POST:\n return QUERY_NAME;\n case method === PUT:\n return MUTATION_NAME;\n default:\n return false;\n }\n}\n\n/**\n * wrapper method\n * @param {mixed} result of fn return\n * @param {boolean|array} [ts=false] when pass this then we append a new value to the end\n * @return {string} stringify data\n */\nexport const packResult = function(result, ts = false) {\n let payload = { [DATA_KEY]: result }\n if (ts && isArray(ts)) {\n ts.push(timestamp())\n payload[TIMESTAMP_PARAM_NAME] = ts\n }\n return JSON.stringify(payload)\n}\n\n/**\n * Check if the error object contain out custom key\n * @param {*} e object\n * @return {boolean} true\n */\nexport const isJsonqlErrorObj = e => {\n const searchFields = ['detail', 'className']\n const test = !!searchFields.filter(field => isObjectHasKey(e, field)).length\n if (test) {\n return ['className', 'message', 'statusCode']\n .filter(field => isObjectHasKey(e, field))\n .map(field => (\n {\n [field]: typeof e[field] === 'object' ? e[field].toString() : e[field]\n }\n ))\n .reduce(merge, {detail: e.toString()}) // can only get as much as possible\n }\n return false;\n}\n\n/**\n * wrapper method - the output is trying to match up the structure of the Error sub class\n * @param {mixed} detail of fn error\n * @param {string} [className=JsonqlError] the errorName\n * @param {number} [statusCode=500] the original error code\n * @return {string} stringify error\n */\nexport const packError = function(detail, className = 'JsonqlError', statusCode = 0, message = '') {\n let errorObj = { detail, className, statusCode, message }\n // we need to check the detail object to see if it has detail, className and message\n // if it has then we should merge the object instead\n return JSON.stringify({\n [ERROR_KEY]: isJsonqlErrorObj(detail) || errorObj,\n [TIMESTAMP_PARAM_NAME]: timestamp()\n })\n}\n\n// ported from http-client\n\n/**\n * handle the return data\n * @TODO how to handle the return timestamp and calculate the diff?\n * @param {object} result return from server\n * @return {object} strip the data part out, or if the error is presented\n */\nexport const resultHandler = result => (\n (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result\n)\n","// new 1.5.0\n// create a class method to handle all the saving and retriving data\n// using the instanceKey to id the data hence allow to use multiple instance\nimport merge from 'lodash-es/merge'\nimport { localStore, sessionStore } from '../stores'\nimport { CLS_SESS_STORE_NAME, CLS_LOCAL_STORE_NAME, hashCode } from '../utils'\n\n// this becomes the base class instead of the HttpCls\nexport default class StoreClass {\n\n constructor(opts) {\n this.opts = opts\n // make it a string\n this.instanceKey = hashCode(this.opts.hostname)\n // pass this store for use later\n this.localStore = localStore\n this.sessionStore = sessionStore\n /*\n if (this.opts.debugOn) { // reuse this to clear out the data\n this.log('clear all stores')\n localStore.clearAll()\n sessionStore.clearAll()\n\n localStore.set('TEST', Date.now())\n sessionStore.set('TEST', Date.now())\n }\n */\n }\n // store in local storage id by the instanceKey\n // values should be an object so with key so we just merge\n // into the existing store without going through the keys\n __setMethod(storeType, values) {\n let store = this[storeType]\n let data = this.__getMethod(storeType)\n const skey = this.opts.storageKey\n const ikey = this.instanceKey\n store.set(skey, {\n [ikey]: data ? merge({}, data, values) : values\n })\n }\n // return the data id by the instaceKey\n __getMethod(storeType) {\n let store = this[storeType]\n let data = store.get(this.opts.storageKey)\n return data ? data[this.instanceKey] : false\n }\n // remove from local store id by instanceKey\n __delMethod(storeType, key) {\n let data = this.__getMethod(storeType)\n if (data) {\n let store = {}\n for (let k in data) {\n if (k !== key) {\n store[k] = data[k]\n }\n }\n this.__setMethod(storeType, store)\n }\n }\n // clear everything by this instanceKey\n __clearMethod(storeKey) {\n const skey = this.opts.storageKey\n const store = this[storeKey]\n let data = store.get(skey)\n if (data) {\n let _store = {}\n for (let k in data) {\n if (k !== this.instanceKey) {\n _store[k] = data[k]\n }\n }\n store.set(skey, _store)\n }\n }\n // Alias for different store\n set lset(values) {\n return this.__setMethod(CLS_LOCAL_STORE_NAME, values)\n }\n\n get lget() {\n return this.__getMethod(CLS_LOCAL_STORE_NAME)\n }\n\n ldel(key) {\n return this.__delMethod(CLS_LOCAL_STORE_NAME, key)\n }\n\n lclear() {\n return this.__clearMethod(CLS_LOCAL_STORE_NAME)\n }\n\n // store in session store id by the instanceKey\n set sset(values) {\n // this.log('--- sset ---', values)\n return this.__setMethod(CLS_SESS_STORE_NAME, values)\n }\n\n get sget() {\n return this.__getMethod(CLS_SESS_STORE_NAME)\n }\n\n sdel(key) {\n return this.__delMethod(CLS_SESS_STORE_NAME, key)\n }\n\n sclear() {\n return this.__clearMethod(CLS_SESS_STORE_NAME)\n }\n\n\n}\n","// base HttpClass\nimport merge from 'lodash-es/merge'\nimport {\n createQuery,\n createMutation,\n getNameFromPayload\n} from 'jsonql-utils/src/params-api'\nimport { cacheBurst, urlParams } from 'jsonql-utils/src/urls'\nimport { resultHandler } from 'jsonql-utils/src/results'\nimport { isObject, isString } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlServerError,\n JsonqlError,\n clientErrorsHandler\n} from 'jsonql-errors'\nimport {\n API_REQUEST_METHODS,\n DEFAULT_HEADER,\n JSONP_CALLBACK_NAME,\n SHOW_CONTRACT_DESC_PARAM\n} from 'jsonql-constants'\nimport { LOG_ERROR_SWITCH } from '../utils'\n\n// extract the one we need\nconst [ POST, PUT ] = API_REQUEST_METHODS\n\nimport StoreClass from './store-cls'\n\nexport default class HttpClass extends StoreClass {\n /**\n * The opts has been check at the init stage\n * @param {object} opts configuration options\n */\n constructor(opts) {\n super(opts)\n // change the way how we init Fly\n // flyio now become external depedencies and it makes it easier to switch\n // @BUG should we run test to check if we have the windows object?\n // this.log(opts)\n // this.fly = opts.Fly ? new opts.Fly() : new Fly()\n // to a different environment like WeChat mini app\n\n this.extraHeader = {};\n // @1.2.1 for adding query to the call on the fly\n this.extraParams = {};\n // this.log('start up opts', opts);\n this.reqInterceptor()\n this.resInterceptor()\n }\n\n // set headers for that one call\n set headers(header) {\n this.extraHeader = header;\n }\n\n /**\n * Create the reusage request method\n * @param {object} payload jsonql payload\n * @param {object} options extra options add the request\n * @param {object} headers extra headers add to the call\n * @return {object} the fly request instance\n */\n request(payload, options = {}, headers = {}) {\n this.headers = headers;\n let params = merge({}, cacheBurst(), this.extraParams)\n // @TODO need to add a jsonp url and payload\n if (this.opts.enableJsonp) {\n let resolverName = getNameFromPayload(payload)\n params = merge({}, params, {[JSONP_CALLBACK_NAME]: resolverName})\n payload = payload[resolverName]\n }\n // double up the url param and see what happen @TODO remove later\n const reqParams = merge({}, { method: POST, params }, options)\n this.log('request params', reqParams, this.jsonqlEndpoint)\n\n return this.fly.request(this.jsonqlEndpoint, payload, reqParams)\n }\n\n /**\n * This will replace the create baseRequest method\n *\n */\n reqInterceptor() {\n this.fly.interceptors.request.use(\n req => {\n const headers = this.getHeaders()\n this.log('request interceptor call', headers)\n\n for (let key in headers) {\n req.headers[key] = headers[key]\n }\n return req;\n }\n )\n }\n\n // @TODO\n processJsonp(result) {\n return resultHandler(result)\n }\n\n /**\n * This will be replacement of the first then call\n *\n */\n resInterceptor() {\n const self = this;\n const jsonp = self.opts.enableJsonp;\n this.fly.interceptors.response.use(\n res => {\n this.log('response interceptor call', res)\n self.cleanUp()\n // now more processing here\n // there is a problem if we throw the result.error here\n // the original data is lost, so we need to do what we did before\n // deal with that error in the first then instead\n const result = isString(res.data) ? JSON.parse(res.data) : res.data;\n if (jsonp) {\n return self.processJsonp(result)\n }\n return resultHandler(result)\n },\n // this get call when it's not 200\n err => {\n self.cleanUp()\n this.log(LOG_ERROR_SWITCH, err)\n throw new JsonqlServerError('Server side error', err)\n }\n )\n }\n\n /**\n * Get the headers inject into the call\n * @return {object} headers\n */\n getHeaders() {\n if (this.opts.enableAuth) {\n return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader)\n }\n return merge({}, DEFAULT_HEADER, this.extraHeader)\n }\n\n /**\n * Post http call operation to clean up things we need\n */\n cleanUp() {\n this.extraHeader = {}\n this.extraParams = {}\n }\n\n /**\n * GET for contract only\n * @return {promise} resolve the contract\n */\n getRemoteContract() {\n if (this.opts.showContractDesc) {\n this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM)\n }\n return this.request({}, {method: 'GET'}, this.contractHeader)\n .then(clientErrorsHandler)\n .then(result => {\n this.log('get contract result', result)\n // when refresh the window the result is different!\n // @TODO need to check the Koa side about why is that\n // also it should set a flag if we want the description or not\n if (result.cache && result.contract) {\n return result.contract;\n }\n // just the normal result\n return result\n })\n .catch(err => {\n this.log(LOG_ERROR_SWITCH, 'getRemoteContract err', err)\n throw new JsonqlServerError('getRemoteContract', err)\n })\n }\n\n /**\n * POST to server - query\n * @param {object} name of the resolver\n * @param {array} args arguments\n * @return {object} promise resolve to the resolver return\n */\n query(name, args = []) {\n return this.request(createQuery(name, args))\n .then(clientErrorsHandler)\n }\n\n /**\n * PUT to server - mutation\n * @param {string} name of resolver\n * @param {object} payload what it said\n * @param {object} conditions what it said\n * @return {object} promise resolve to the resolver return\n */\n mutation(name, payload = {}, conditions = {}) {\n return this.request(createMutation(name, payload, conditions), {method: PUT})\n .then(clientErrorsHandler)\n }\n\n}\n","// all the contract related methods will be here\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { timestamp } from 'jsonql-utils/src/timestamp'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { ENDPOINT_TABLE, CLS_CONTRACT_NAME } from '../utils'\nimport { localStore } from '../stores'\nimport HttpClass from './http-cls'\n\n// export\nexport default class ContractClass extends HttpClass {\n\n constructor(opts) {\n super(opts)\n }\n\n /**\n * return the contract public api\n * @return {object} contract\n */\n getContract() {\n const contract = this.readContract()\n this.log('getContract first call', contract)\n return contract ? Promise.resolve(contract)\n : this.getRemoteContract().then(this.storeContract.bind(this))\n }\n\n /**\n * We are changing the way how to auth to get the contract.json\n * Instead of in the url, we will be putting that key value in the header\n * @return {object} header\n */\n get contractHeader() {\n let base = {};\n if (this.opts.contractKey !== false) {\n base[this.opts.contractKeyName] = this.opts.contractKey;\n }\n return base;\n }\n\n /**\n * Save the contract to local store\n * @param {object} contract to save\n * @return {object|boolean} false when its not a contract or contract on OK\n */\n storeContract(contract) {\n // first need to check if the contract is a contract\n if (!isContract(contract)) {\n throw new JsonqlValidationError(`Contract is malformed!`)\n }\n this.lset = {[CLS_CONTRACT_NAME]: contract}\n // return it\n this.log('storeContract return result', contract)\n return contract;\n }\n\n /**\n * return the contract from options or localStore\n * @return {object|boolean} false on not found\n */\n readContract() {\n let contract = isContract(this.opts.contract)\n if (contract !== false) {\n return contract;\n }\n let data = this.lget\n if (data) {\n return data[CLS_CONTRACT_NAME]\n }\n return false;\n }\n}\n","// this is the new auth class that integrate with the jsonql-jwt\n// all the auth related methods will be here\nimport { decodeToken } from 'jsonql-jwt/src/client'\nimport { isNumber } from 'jsonql-params-validator'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { CREDENTIAL_STORAGE_KEY, AUTH_HEADER, BEARER } from 'jsonql-constants'\nimport { CLS_PROFILE_IDX, ZERO_IDX, USERDATA_TABLE } from '../utils'\nimport ContractClass from './contract-cls'\n// export\nexport default class AuthClass extends ContractClass {\n\n constructor(opts) {\n super(opts)\n if (opts.enableAuth) {\n this.setDecoder = decodeToken;\n }\n }\n\n /**\n * for overwrite\n * @param {string} token stored token\n * @return {string} token\n */\n decoder(token) {\n return token;\n }\n\n /**\n * set the profile index\n * @param {number} idx\n */\n set profileIndex(idx) {\n const key = CLS_PROFILE_IDX\n if (isNumber(idx)) {\n this[key] = idx;\n if (this.opts.persistToken) {\n this.lset = {[key]: idx}\n }\n return;\n }\n throw new JsonqlValidationError('profileIndex', `Expect idx to be number but got ${typeof idx}`)\n }\n\n /**\n * get the profile index\n * @return {number} idx\n */\n get profileIndex() {\n const key = CLS_PROFILE_IDX\n if (this.opts.persistToken) {\n const data = this.lget;\n if (data[key]) {\n return data[key]\n }\n }\n return this[key] ? this[key] : ZERO_IDX\n }\n\n /**\n * Return the token from session store\n * @param {number} [idx=false] profile index\n * @return {string} token\n */\n rawAuthToken(idx = false) {\n if (idx !== false) {\n this.profileIndex = idx;\n }\n // this should return from the base\n return this.jsonqlToken; // see base-cls\n }\n\n /**\n * Setter to add a decoder when retrieve user token\n * @param {function} d a decoder\n */\n set setDecoder(d) {\n if (typeof d === 'function') {\n this.decoder = d;\n }\n }\n\n /**\n * getter to return the session or local store set method\n * @param {*} data to save\n * @return {object} set method\n */\n set saveProfile(data) {\n if (this.opts.persistToken) {\n // this.log('--- saveProfile lset ---', data)\n this.lset = data\n } else {\n // this.log('--- saveProfile sset ---', data)\n this.sset = data\n }\n }\n\n /**\n * getter to return the session or local store get method\n * @return {object} get method\n */\n get readProfile() {\n return this.opts.persistToken ? this.lget : this.sget\n }\n\n // these were in the base class before but it should be here\n /**\n * save token\n * @param {string} token to store\n * @return {string|boolean} false on failed\n */\n set jsonqlToken(token) {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n // @TODO also have to make sure the token is not already existed!\n let tokens = (data && data[key]) ? data[key] : []\n tokens.push(token)\n this.saveProfile = {[key]: tokens}\n // store the userdata\n this.jsonqlUserdata = this.decoder(token)\n }\n\n /**\n * Jsonql token getter\n * 1.5.1 each token associate with the same profileIndex\n * @return {string|boolean} false when failed\n */\n get jsonqlToken() {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex])\n return data[key][this.profileIndex]\n }\n return false\n }\n\n /**\n * this one will use the sessionStore\n * basically we hook this onto the token store and decode it to store here\n * we only store one decoded user data at a time, but the token can be multiple\n */\n set jsonqlUserdata(userdata) {\n this.sset = {[USERDATA_TABLE]: userdata}\n }\n\n /**\n * this one store in the session store\n * get login userdata decoded jwt\n * 1.5.1 each userdata associate with the same profileIndex\n * @return {object|null}\n */\n get jsonqlUserdata() {\n const data = this.sget\n return data ? data[USERDATA_TABLE] : false\n }\n\n /**\n * Construct the auth header\n * @return {object} header\n */\n getAuthHeader() {\n const token = this.jsonqlToken // only call the getter to get the default one\n return token ? {[this.opts.AUTH_HEADER]: `${BEARER} ${token}`} : {};\n }\n\n /**\n * return all the stored token and decode it\n * @param {number} [idx=false] profile index\n * @return {array|boolean|string} false not found or array\n */\n getProfiles(idx = false) {\n const self = this; // just in case the scope problem\n const data = self.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n if (idx !== false && isNumber(idx)) {\n return data[key][idx] || false\n }\n return data[key].map(self.decoder.bind(self))\n }\n return false\n }\n\n /**\n * call after the login\n * @param {string} token return from server\n * @return {object} decoded token to userdata object\n */\n postLoginAction(token) {\n this.jsonqlToken = token\n return token\n }\n\n /**\n * call after the logout @TODO\n */\n postLogoutAction(...args) {\n console.info(`postLogoutAction`, args)\n }\n}\n","// this the core of the internal storage management\nimport { CREDENTIAL_STORAGE_KEY } from 'jsonql-constants'\n// import { isObject, isArray } from 'jsonql-params-validator'\n// import { JsonqlValidationError } from 'jsonql-errors'\n// import { timestamp } from 'jsonql-utils/src/timestamp'\n// import { inArray } from 'jsonql-utils/src/generic'\nimport { USERDATA_TABLE, LOG_ERROR_SWITCH } from '../utils'\nimport AuthCls from './auth-cls'\n\n// This class will only focus on the storage system\nexport default class JsonqlBaseClient extends AuthCls {\n // change the order of the interface in 1.4.10 to match up the top level\n constructor(fly, opts) {\n // change at 1.4.10 pass it directly without init it\n this.fly = fly;\n super(opts)\n }\n\n /**\n * construct the end point\n * @return {string} the end point to call\n */\n get jsonqlEndpoint() {\n const baseUrl = this.opts.hostname || ''\n return [baseUrl, this.opts.jsonqlPath].join('/')\n }\n\n /**\n * simple log\n */\n log(...args) {\n if (this.opts.debugOn === true) {\n const fns = ['info', 'error']\n const idx = (args[0] === LOG_ERROR_SWITCH) ? 1 : 0\n Reflect.apply(console[fns[idx]], console, args.splice(0, idx))\n }\n }\n\n}\n","// export interface\n// @public\nimport JsonqlBaseClient from './base-cls'\n\nexport default JsonqlBaseClient\n","// all the client configuration options here\nimport {\n JSONQL_PATH,\n CONTENT_TYPE,\n BEARER,\n CLIENT_STORAGE_KEY,\n CLIENT_AUTH_KEY,\n CONTRACT_KEY_NAME,\n AUTH_HEADER,\n ISSUER_NAME,\n LOGOUT_NAME,\n BOOLEAN_TYPE,\n STRING_TYPE,\n NUMBER_TYPE,\n DEFAULT_HEADER\n} from 'jsonql-constants'\nimport { createConfig } from 'jsonql-params-validator'\nexport const constProps = {\n contract: false,\n MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong?\n CONTENT_TYPE,\n BEARER,\n AUTH_HEADER\n}\n\n// grab the localhost name and put into the hostname as default\nconst getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n return null\n }\n}\n\nexport const appProps = {\n\n hostname: createConfig(getHostName(), [STRING_TYPE]), // required the hostname\n jsonqlPath: createConfig(JSONQL_PATH, [STRING_TYPE]), // The path on the server\n\n loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]),\n logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]),\n // add to koa v1.3.0 - this might remove in the future\n enableJsonp: createConfig(false, [BOOLEAN_TYPE]),\n enableAuth: createConfig(false, [BOOLEAN_TYPE]),\n // enable useJwt by default @TODO replace with something else and remove them later\n useJwt: createConfig(true, [BOOLEAN_TYPE]),\n // when true then store infinity or pass a time in seconds then we check against\n // the token date of creation\n persistToken: createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE]),\n // the header\n // v1.2.0 we are using this option during the dev\n // so it won't save anything to the localstorage and fetch a new contract\n // whenever the browser reload\n useLocalstorage: createConfig(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage\n storageKey: createConfig(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage\n authKey: createConfig(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage\n contractExpired: createConfig(0, [NUMBER_TYPE]),// -1 always fetch contract,\n // 0 never expired,\n // > 0 then compare the timestamp with the current one to see if we need to get contract again\n // useful during development\n keepContract: createConfig(true, [BOOLEAN_TYPE]),\n exposeContract: createConfig(false, [BOOLEAN_TYPE]),\n exposeStore: createConfig(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn \n // @1.2.1 new option for the contract-console to fetch the contract with description\n showContractDesc: createConfig(false, [BOOLEAN_TYPE]),\n contractKey: createConfig(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this\n contractKeyName: createConfig(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs\n enableTimeout: createConfig(false, [BOOLEAN_TYPE]), // @TODO\n timeout: createConfig(5000, [NUMBER_TYPE]), // 5 seconds\n returnInstance: createConfig(false, [BOOLEAN_TYPE]),\n allowReturnRawToken: createConfig(false, [BOOLEAN_TYPE]),\n debugOn: createConfig(false, [BOOLEAN_TYPE])\n}\n","// This is for the sync version therefore we don't need to care about the contract options\nimport { appProps, constProps } from './base-options'\nimport { checkConfig } from 'jsonql-params-validator'\n\nexport default function checkOptions(config) {\n return checkConfig(config, appProps, constProps)\n}\n","// export interface\nimport checkOptionsAsyncLocal from './check-options-async'\nimport checkOptionsLocal from './check-options'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport { objHasProp } from 'jsonql-utils/src/obj-define-props'\n/**\n * 1.5.0 overload the orginal functions to pass over the check\n */\nfunction checkOptionsAsync(config) {\n return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsyncLocal(config)\n}\n\n// sync version without needing the promise\nfunction checkOptions(config) {\n return objHasProp(config, CHECKED_KEY) ? config : checkOptionsLocal(config)\n}\n\nexport {\n checkOptionsAsync,\n checkOptions\n}\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n\nexport default class SuspendClass {\n\n constructor() {\n // suspend, release and queue\n this.__suspend__ = null;\n this.queueStore = new Set()\n /*\n this.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n })\n */\n }\n\n /**\n * setter to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n set $suspend(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend__;\n this.__suspend__ = value;\n this.logger('($suspend)', `Change from ${lastValue} --> ${value}`)\n if (lastValue === true && value === false) {\n setTimeout(() => {\n this.release()\n }, 1)\n }\n } else {\n throw new Error(`$suspend only accept Boolean value!`)\n }\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {any} value\n * @return {Boolean} true when added or false when it's not\n */\n $queue(...args) {\n if (this.__suspend__ === true) {\n this.logger('($queue)', 'added to $queue', args)\n // there shouldn't be any duplicate ...\n this.queueStore.add(args)\n }\n return this.__suspend__;\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size;\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n release() {\n let size = this.queueStore.size\n this.logger('(release)', `Release was called ${size}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('queue', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport genHaskKey from './hash-code'\nimport SuspendClass from './suspend'\n\nexport default class NbEventServiceBase extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger;\n }\n this.keep = config.keep;\n // for the $done setter\n this.result = config.keep ? [] : null;\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (typeof e !== 'string') {\n this.logger('(validateEvt)', e)\n throw new Error(`event name must be string type!`)\n }\n })\n return true;\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n return true;\n }\n }\n throw new Error(`callback required to be function type!`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n const types = ['on', 'only', 'once', 'onlyOnce']\n return !!types.filter(t => type === t).length;\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run)', callback, payload, ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName]; // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger('(takeFromStore)', `has ${evt}`, content)\n store.delete(evt)\n return content;\n }\n return false;\n }\n throw new Error(`${storeName} is not supported!`)\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n let fnSet;\n if (store.has(evt)) {\n this.logger('(addToStore)', `${evt} existed`)\n fnSet = store.get(evt)\n } else {\n this.logger('(addToStore)', `create new Set for ${evt}`)\n // this is new\n fnSet = new Set()\n }\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args;\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger('(addToStore)', `insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(l => {\n let [hash,] = l;\n if (hash === args[0]) {\n return true;\n }\n return false;\n }).length;\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true;\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list;\n return type !== t;\n }).length;\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n this.logger('(checkTypeInLazyStore)', store)\n if (store) {\n return !!Array\n .from(store)\n .filter(l => {\n let [,,t] = l;\n return t !== type;\n }).length\n }\n return false;\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger('(addToNormalStore)', evt, type, 'try to add to normal store')\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n this.logger('(addToNormalStore)', `${type} can add to ${evt} normal store`)\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store;\n return size;\n }\n return false;\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store;\n return size;\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg];\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n return genHaskKey(fn.toString()) + '';\n }\n}\n","// The top level\nimport NbStoreService from './store-service'\n// export\nexport default class EventService extends NbStoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on';\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger('($on)', `${evt} callback is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger('($on)', `${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0;\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($on)`, `call run on ${evt}`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n return size;\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n const type = 'once';\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (lazyStoreContent === false) {\n this.logger('($once)', `${evt} not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, type, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger('($once)', `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'only';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($only)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($only)', `${evt} found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( l => {\n const [ payload, ctx, t ] = l;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($only)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n })\n }\n return added;\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD added in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'onlyOnce';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== 'onlyOnce') {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($onlyOnce)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added;\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {}\n */\n $replace(evt, callback, context = null, type = 'on') {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n this.logger(`($replace)`, evt, callback)\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0;\n // first check the normal store\n let nStore = this.normalStore;\n this.logger('($trigger)', 'normalStore', nStore)\n if (nStore.has(evt)) {\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n this.logger('($trigger)', evt, 'found; add to queue: ', added)\n if (added === true) {\n this.logger('($trigger)', evt, 'not executed. Exit now.')\n return false; // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length;\n let hasOnce = false;\n let hasOnly = false;\n for (let i=0; i < ctn; ++i) {\n ++found;\n // this.logger('found', found)\n let [ _, callback, ctx, type ] = nSet[i]\n this.logger(`($trigger)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n if (type === 'once' || type === 'onlyOnce') {\n hasOnce = true;\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found;\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found;\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter around\n * @param {string} evt event name\n * @param {*} params pass to the callback\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, params, type = false, context = null) {\n let args = [evt, params, context, type]\n return Reflect.apply(this.$trigger, this, args)\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n let found = false;\n stores.forEach(store => {\n if (store.has(evt)) {\n found = true;\n this.logger('($off)', evt)\n store.delete(evt)\n }\n })\n return found;\n }\n\n /**\n * return all the listener from the event\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n this.validateEvt(evt)\n let store = this.normalStore;\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l;\n }\n let [key, callback, ] = l;\n return callback;\n })\n }\n return false;\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done)', 'value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value;\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n if (this.keep) {\n this.logger('(get $done)', this.result)\n return this.result[this.result.length - 1]\n }\n return this.result;\n }\n\n\n}\n","// default\nimport NBEventService from './src/event-service'\n\nexport default NBEventService\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// output\nexport default function(debugOn) {\n let logger = debugOn ? (...args) => {\n args.unshift('[NBS]')\n console.log.apply(null, args)\n }: undefined;\n return new NBEventService({ logger })\n}\n","// this is the new Event base interface\n// the export will be different and purposely design for framework that\n// is very hard to use Promise such as Vue\nimport jsonqlStaticGenerator from './core/jsonql-static-generator'\nimport JsonqlBaseClient from './base'\nimport { checkOptions } from './options'\nimport { getContractFromConfig } from './utils'\nimport getEventEmitter from './ee'\n/**\n * this is the slim client without Fly, you pick the version of Fly to use\n * This is a breaking change because it swap the input positions\n * @param {object} fly fly.js\n * @param {object} config configuration\n * @return {object} the jsonql client instance\n */\nexport default function jsonqlStaticClient(fly, config = {}) {\n const { contract } = config;\n const opts = checkOptions(config)\n const jsonqlBase = new JsonqlBaseClient(fly, opts)\n const contractPromise = getContractFromConfig(jsonqlBase, contract)\n const ee = getEventEmitter(opts.debugOn)\n // finally\n let methods = jsonqlStaticGenerator(jsonqlBase, opts, contractPromise, ee)\n methods.eventEmitter = ee;\n return methods;\n}\n","// This is the static version that build with the Fly for Browser\nimport Fly from 'flyio/dist/npm/fly'\nimport jsonqlStaticClient from './static'\n\n// this is the slim client without Fly\nexport default function jsonqlStaticClientFull(config = {}) {\n return jsonqlStaticClient(new Fly(), config)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/packages/http-client/dist/jsonql-client.umd.js b/packages/http-client/dist/jsonql-client.umd.js index e1414212..3203c88b 100644 --- a/packages/http-client/dist/jsonql-client.umd.js +++ b/packages/http-client/dist/jsonql-client.umd.js @@ -1,2 +1,9559 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClient=e()}(this,(function(){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r,n=e((function(t,e){var r;r=function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=2)}([function(t,e,r){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};t.exports={type:function(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()},isObject:function(t,e){return e?"object"===this.type(t):t&&"object"===(void 0===t?"undefined":n(t))},isFormData:function(t){return"undefined"!=typeof FormData&&t instanceof FormData},trim:function(t){return t.replace(/(^\s*)|(\s*$)/g,"")},encode:function(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")},formatParams:function(t){var e="",r=!0,n=this;return this.isObject(t)?(function t(o,i){var a=n.encode,u=n.type(o);if("array"==u)o.forEach((function(e,r){n.isObject(e)||(r=""),t(e,i+"%5B"+r+"%5D")}));else if("object"==u)for(var c in o)t(o[c],i?i+"%5B"+a(c)+"%5D":a(c));else r||(e+="&"),r=!1,e+=i+"="+a(o)}(t,""),e):t},merge:function(t,e){for(var r in e)t.hasOwnProperty(r)?this.isObject(e[r],1)&&this.isObject(t[r],1)&&this.merge(t[r],e[r]):t[r]=e[r];return t}}},,function(t,e,r){var n=function(){function t(t,e){for(var r=0;r0&&(t+=(-1===t.indexOf("?")?"?":"&")+w.join("&")),a.open(r.method,t);try{a.withCredentials=!!r.withCredentials,a.timeout=r.timeout||0,"stream"!==y&&(a.responseType=y)}catch(t){}var j=r.headers[u]||r.headers[c],S="application/x-www-form-urlencoded";for(var O in o.trim((j||"").toLowerCase())===S?e=o.formatParams(e):o.isFormData(e)||-1===["object","array"].indexOf(o.type(e))||(S="application/json;charset=utf-8",e=JSON.stringify(e)),j||b||(r.headers[u]=S),r.headers)if(O===u&&o.isFormData(e))delete r.headers[O];else try{a.setRequestHeader(O,r.headers[O])}catch(t){}function k(t,e,n){v(l.p,(function(){if(t){n&&(e.request=r);var o=t.call(l,e,Promise);e=void 0===o?e:o}d(e)||(e=Promise[0===n?"resolve":"reject"](e)),e.then((function(t){s(t)})).catch((function(t){h(t)}))}))}function E(t){t.engine=a,k(l.onerror,t,-1)}function A(t,e){this.message=t,this.status=e}a.onload=function(){try{var t=a.response||a.responseText;t&&r.parseJson&&-1!==(a.getResponseHeader(u)||"").indexOf("json")&&!o.isObject(t)&&(t=JSON.parse(t));var e=a.responseHeaders;if(!e){e={};var n=(a.getAllResponseHeaders()||"").split("\r\n");n.pop(),n.forEach((function(t){if(t){var r=t.split(":")[0];e[r]=a.getResponseHeader(r)}}))}var i=a.status,c=a.statusText,s={data:t,headers:e,status:i,statusText:c};if(o.merge(s,a._response),i>=200&&i<300||304===i)s.engine=a,s.request=r,k(l.handler,s,0);else{var f=new A(c,i);f.response=s,E(f)}}catch(f){E(new A(f.msg,a.status))}},a.onerror=function(t){E(new A(t.msg||"Network Error",0))},a.ontimeout=function(){E(new A("timeout [ "+a.timeout+"ms ]",1))},a._options=r,setTimeout((function(){a.send(b?null:e)}),0)}(n):s(n)}),(function(t){h(t)}))}))}));return h.engine=a,h}},{key:"all",value:function(t){return Promise.all(t)}},{key:"spread",value:function(t){return function(e){return t.apply(null,e)}}}]),t}();a.default=a,["get","post","put","patch","head","delete"].forEach((function(t){a.prototype[t]=function(e,r,n){return this.request(e,r,o.merge({method:t},n))}})),["lock","unlock","clear"].forEach((function(t){a.prototype[t]=function(){this.interceptors.request[t]()}})),t.exports=a}])},t.exports=r()})),o=(r=n)&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r,i="application/vnd.api+json",a={Accept:i,"Content-Type":[i,"charset=utf-8"].join(";")},u="query",c="mutation",s="socket",f="payload",l="condition",p="TS",h=["POST","PUT"],d="type",v="optional",g="enumv",y="args",b="checker",m="alias",_="__checked__",w={desc:"y"},j="No message",S=Array.isArray,O="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},k="object"==typeof O&&O&&O.Object===Object&&O,E="object"==typeof self&&self&&self.Object===Object&&self,A=k||E||Function("return this")(),x=A.Symbol,T=Object.prototype,P=T.hasOwnProperty,q=T.toString,C=x?x.toStringTag:void 0;var $=Object.prototype.toString;var z="[object Null]",N="[object Undefined]",R=x?x.toStringTag:void 0;function M(t){return null==t?void 0===t?N:z:R&&R in Object(t)?function(t){var e=P.call(t,C),r=t[C];try{t[C]=void 0;var n=!0}catch(t){}var o=q.call(t);return n&&(e?t[C]=r:delete t[C]),o}(t):function(t){return $.call(t)}(t)}function F(t,e){return function(r){return t(e(r))}}var I=F(Object.getPrototypeOf,Object);function J(t){return null!=t&&"object"==typeof t}var D="[object Object]",U=Function.prototype,H=Object.prototype,L=U.toString,B=H.hasOwnProperty,K=L.call(Object);function G(t){if(!J(t)||M(t)!=D)return!1;var e=I(t);if(null===e)return!0;var r=B.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&L.call(r)==K}function V(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&nt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var mt=function(t){return S(t)?t:[t]},_t=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),xt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),Pt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),qt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Ct=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),$t=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),zt=Object.freeze({__proto__:null,Jsonql406Error:wt,Jsonql500Error:jt,JsonqlForbiddenError:St,JsonqlAuthorisationError:Ot,JsonqlContractAuthError:kt,JsonqlResolverAppError:Et,JsonqlResolverNotFoundError:At,JsonqlEnumError:xt,JsonqlTypeError:Tt,JsonqlCheckerError:Pt,JsonqlValidationError:qt,JsonqlError:Ct,JsonqlServerError:$t}),Nt=Ct,Rt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function Mt(t){if(Rt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||j,a=e.detail||e;if(o&&zt[o])throw new zt[r](i,a);throw new Nt(i,a)}return t}function Ft(t){return!!function(t){return G(t)&&(_t(t,u)||_t(t,c)||_t(t,s))}(t)&&t}function It(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var Jt=function(t,e){return void 0===e&&(e={}),Ft(e)?Promise.resolve(e):t.getContract()},Dt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function Ut(t){this.message=t}Ut.prototype=new Error,Ut.prototype.name="InvalidCharacterError";var Ht="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new Ut("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=Dt.indexOf(n);return a};var Lt=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Ht(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return Ht(e)}};function Bt(t){this.message=t}Bt.prototype=new Error,Bt.prototype.name="InvalidTokenError";var Kt=function(t,e){if("string"!=typeof t)throw new Bt("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(Lt(t.split(".")[r]))}catch(t){throw new Bt("Invalid token specified: "+t.message)}},Gt=Bt;Kt.InvalidTokenError=Gt;var Vt="[object String]";function Wt(t){return"string"==typeof t||!S(t)&&J(t)&&M(t)==Vt}var Yt=function(t){return""!==bt(t)&&Wt(t)},Qt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Xt(t){if(Yt(t))return function(t){var e=t.iat||Qt(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Ct("Token has expired on "+r,t)}return t}(Kt(t));throw new Ct("Token must be a string!")}var Zt=function(t){return!!S(t)||null!=t&&""!==bt(t)},te="[object Number]";function ee(t){return function(t){return"number"==typeof t||J(t)&&M(t)==te}(t)&&t!=+t}var re=function(t){return!Wt(t)&&!ee(parseFloat(t))},ne=function(t){return null!=t&&"boolean"==typeof t},oe=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==bt(t)&&(!1===e||!0===e&&null!==t)},ie=d,ae=v,ue=g,ce=y,se=b,fe=m,le="continue",pe=function(t){switch(t){case"number":return re;case"string":return Yt;case"boolean":return ne;default:return oe}},he=function(t,e){return void 0===e&&(e=""),!!S(t)&&(""===e||""===bt(e)||!(t.filter((function(t){return!pe(e)(t)})).length>0))},de=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ve=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!pe(e)(t)})).length)})).length:e.length>e.filter((function(t){return!he(r,t)})).length};var ge,ye=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[ge?a:++n];if(!1===e(o[u],u,o))break}return t};var be="[object Arguments]";function me(t){return J(t)&&M(t)==be}var _e=Object.prototype,we=_e.hasOwnProperty,je=_e.propertyIsEnumerable,Se=me(function(){return arguments}())?me:function(t){return J(t)&&we.call(t,"callee")&&!je.call(t,"callee")};var Oe="object"==typeof exports&&exports&&!exports.nodeType&&exports,ke=Oe&&"object"==typeof module&&module&&!module.nodeType&&module,Ee=ke&&ke.exports===Oe?A.Buffer:void 0,Ae=(Ee?Ee.isBuffer:void 0)||function(){return!1},xe=9007199254740991,Te=/^(?:0|[1-9]\d*)$/;function Pe(t,e){var r=typeof t;return!!(e=null==e?xe:e)&&("number"==r||"symbol"!=r&&Te.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=qe}var $e={};$e["[object Float32Array]"]=$e["[object Float64Array]"]=$e["[object Int8Array]"]=$e["[object Int16Array]"]=$e["[object Int32Array]"]=$e["[object Uint8Array]"]=$e["[object Uint8ClampedArray]"]=$e["[object Uint16Array]"]=$e["[object Uint32Array]"]=!0,$e["[object Arguments]"]=$e["[object Array]"]=$e["[object ArrayBuffer]"]=$e["[object Boolean]"]=$e["[object DataView]"]=$e["[object Date]"]=$e["[object Error]"]=$e["[object Function]"]=$e["[object Map]"]=$e["[object Number]"]=$e["[object Object]"]=$e["[object RegExp]"]=$e["[object Set]"]=$e["[object String]"]=$e["[object WeakMap]"]=!1;var ze,Ne="object"==typeof exports&&exports&&!exports.nodeType&&exports,Re=Ne&&"object"==typeof module&&module&&!module.nodeType&&module,Me=Re&&Re.exports===Ne&&k.process,Fe=function(){try{var t=Re&&Re.require&&Re.require("util").types;return t||Me&&Me.binding&&Me.binding("util")}catch(t){}}(),Ie=Fe&&Fe.isTypedArray,Je=Ie?(ze=Ie,function(t){return ze(t)}):function(t){return J(t)&&Ce(t.length)&&!!$e[M(t)]},De=Object.prototype.hasOwnProperty;function Ue(t,e){var r=S(t),n=!r&&Se(t),o=!r&&!n&&Ae(t),i=!r&&!n&&!o&&Je(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},ir.prototype.set=function(t,e){var r=this.__data__,n=nr(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var ar,ur=A["__core-js_shared__"],cr=(ar=/[^.]+$/.exec(ur&&ur.keys&&ur.keys.IE_PROTO||""))?"Symbol(src)_1."+ar:"";var sr=Function.prototype.toString;function fr(t){if(null!=t){try{return sr.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var lr=/^\[object .+?Constructor\]$/,pr=Function.prototype,hr=Object.prototype,dr=pr.toString,vr=hr.hasOwnProperty,gr=RegExp("^"+dr.call(vr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function yr(t){return!(!Ge(t)||function(t){return!!cr&&cr in t}(t))&&(Xe(t)?gr:lr).test(fr(t))}function br(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return yr(r)?r:void 0}var mr=br(A,"Map"),_r=br(Object,"create");var wr="__lodash_hash_undefined__",jr=Object.prototype.hasOwnProperty;var Sr=Object.prototype.hasOwnProperty;var Or="__lodash_hash_undefined__";function kr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&zr?new qr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=de(t))?!ve({arg:r},e):!pe(t)(r))})).length)})).length}return!1},eo=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(to,null,a);case"array"===t:return!he(e.arg);case!1!==(r=de(t)):return!ve(e,r);default:return!pe(t)(e.arg)}},ro=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},no=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!he(e))throw new Ct("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!he(t))throw new Ct("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?ro(t,a):t,index:r,param:a,optional:i}}));default:throw new Ct("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Zt(e)&&!(r.type.length>r.type.filter((function(e){return eo(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return eo(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},oo=function(){try{var t=br(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function io(t,e,r){"__proto__"==e&&oo?oo(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function ao(t,e,r){(void 0===r||rr(t[e],r))&&(void 0!==r||e in t)||io(t,e,r)}var uo="object"==typeof exports&&exports&&!exports.nodeType&&exports,co=uo&&"object"==typeof module&&module&&!module.nodeType&&module,so=co&&co.exports===uo?A.Buffer:void 0,fo=so?so.allocUnsafe:void 0;function lo(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new Rr(n).set(new Rr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var po=Object.create,ho=function(){function t(){}return function(e){if(!Ge(e))return{};if(po)return po(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function vo(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var go=Object.prototype.hasOwnProperty;function yo(t,e,r){var n=t[e];go.call(t,e)&&rr(n,r)&&(void 0!==r||e in t)||io(t,e,r)}var bo=Object.prototype.hasOwnProperty;function mo(t){if(!Ge(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Le(t),r=[];for(var n in t)("constructor"!=n||!e&&bo.call(t,n))&&r.push(n);return r}function _o(t){return Ze(t)?Ue(t,!0):mo(t)}function wo(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=Ao)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Eo);function qo(t,e){return Po(function(t,e,r){return e=ko(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=ko(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Co.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!Ge(r))return!1;var n=typeof e;return!!("number"==n?Ze(r)&&Pe(e,r.length):"string"==n&&e in r)&&rr(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=0;e--){var r=Ni().key(e);t(Ri(r),r)}},remove:function(t){return Ni().removeItem(t)},clearAll:function(){return Ni().clear()}};function Ni(){return $i.localStorage}function Ri(t){return Ni().getItem(t)}var Mi=yi.trim,Fi={name:"cookieStorage",read:function(t){if(!t||!Ui(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Ii.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Ii.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Ji,remove:Di,clearAll:function(){Ji((function(t,e){Di(e)}))}},Ii=yi.Global.document;function Ji(t){for(var e=Ii.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Mi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Di(t){t&&Ui(t)&&(Ii.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Ui(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Ii.cookie)}var Hi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Li=yi.bind,Bi=yi.each,Ki=yi.create,Gi=yi.slice,Vi=function(){var t=Ki(Wi,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Li(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Li(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),Bi(r,(function(e,r){t.fire(r,void 0,e)}))}}};var Wi={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Li(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Gi(arguments,1);Bi(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},Yi=e((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),Qi=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=Yi.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=Yi.compress(this._serialize(r));t(e,n)}}};var Xi=[zi,Fi],Zi=[Hi,Vi,Qi],ta=Pi.createStore(Xi,Zi),ea=yi.Global;function ra(){return ea.sessionStorage}function na(t){return ra().getItem(t)}var oa=[{name:"sessionStorage",read:na,write:function(t,e){return ra().setItem(t,e)},each:function(t){for(var e=ra().length-1;e>=0;e--){var r=ra().key(e);t(na(r),r)}},remove:function(t){return ra().removeItem(t)},clearAll:function(){return ra().clear()}},Fi],ia=[Hi,Qi],aa=Pi.createStore(oa,ia),ua=ta,ca=aa,sa=function(t){var e;return(e={}).args=t,e};function fa(t,e){var r;return(r={})[t]=e,r[p]=[pi()],r}var la=function(t){return _t(t,"data")&&!_t(t,"error")?t.data:t},pa=function(t){this.opts=t,this.instanceKey=It(this.opts.hostname)+"",this.localStore=ua,this.sessionStore=ca},ha={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};pa.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?$o({},o,e):e,r))},pa.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},pa.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},pa.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},ha.lset.set=function(t){return this.__setMethod("localStore",t)},ha.lget.get=function(){return this.__getMethod("localStore")},pa.prototype.ldel=function(t){return this.__delMethod("localStore",t)},pa.prototype.lclear=function(){return this.__clearMethod("localStore")},ha.sset.set=function(t){return this.__setMethod("sessionStore",t)},ha.sget.get=function(){return this.__getMethod("sessionStore")},pa.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},pa.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(pa.prototype,ha);var da=h[0],va=h[1],ga=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Xt)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(ci(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new qt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&ci(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!Ft(t))throw new qt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=Ft(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={headers:{configurable:!0}};return r.headers.set=function(t){this.extraHeader=t},e.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=$o({},{_cb:pi()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=$o({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=$o({},{method:da,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},e.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},e.prototype.processJsonp=function(t){return la(t)},e.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=ui(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):la(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new $t("Server side error",r)}))},e.prototype.getHeaders=function(){return this.opts.enableAuth?$o({},a,this.getAuthHeader(),this.extraHeader):$o({},a,this.extraHeader)},e.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},e.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=$o({},this.extraParams,w)),this.request({},{method:"GET"},this.contractHeader).then(Mt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new $t("getRemoteContract",e)}))},e.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Wt(t)&&S(e)){var n=sa(e);return!0===r?n:fa(t,n)}throw new qt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(Mt)},e.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[f]=e,o[l]=r,!0===n)return o;if(Wt(t))return fa(t,o);throw new qt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:va}).then(Mt)},Object.defineProperties(e.prototype,r),e}(pa)))),ya=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,mt(t))}),Reflect.apply(t,null,r))}};function ba(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function ma(t,e,r,n){void 0===n&&(n=!1);var o=ba(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var _a=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return si(r,i).then((function(){return t.query.apply(t,[e,a,u])}))}},wa=function(t,e,r,n,o){var i={},a=function(t){i=ma(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return si(a,i).then((function(){return e.query.apply(e,[t,a,u])}))}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},ja=function(t,e,r,n,o){var i={},a=function(t){i=ma(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return si(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])}))}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Sa=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=_a(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=_a(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var Oa=function(t,e,r,n){var o=function(t,e,r,n){return ya(wa,ja,Sa)({},t,e,r,n)}(t,n,e,r);return e.enableAuth&&(o.userdata=function(){return t.jsonqlUserdata},o.getToken=function(e){return void 0===e&&(e=!1),t.rawAuthToken(e)},o.profileIndex=function(e){if(void 0===e&&(e=!1),!1===e)return t.profileIndex;t.profileIndex=e},o.getProfiles=function(e){return void 0===e&&(e=!1),t.getProfiles(e)}),e.exposeContract&&(o.getContract=function(){return t.getContract()}),e.exposeStore&&(o.tmpSave=function(t){},o.tmpGet=function(t){},o.tmpDel=function(t){},o.persistSave=function(t){},o.persistGet=function(t){},o.persistDel=function(t){}),o.eventEmitter=n,o.version="1.5.1",o.log=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return Reflect.apply(t.log,t,["[DEV DEBUG]"].concat(e))},o},ka={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:i,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Ea={hostname:fi(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:fi("jsonql",["string"]),loginHandlerName:fi("login",["string"]),logoutHandlerName:fi("logout",["string"]),enableJsonp:fi(!1,["boolean"]),enableAuth:fi(!1,["boolean"]),useJwt:fi(!0,["boolean"]),persistToken:fi(!1,["boolean","number"]),useLocalstorage:fi(!0,["boolean"]),storageKey:fi("jsonqlstore",["string"]),authKey:fi("jsonqlauthkey",["string"]),contractExpired:fi(0,["number"]),keepContract:fi(!0,["boolean"]),exposeContract:fi(!1,["boolean"]),exposeStore:fi(!1,["boolean"]),showContractDesc:fi(!1,["boolean"]),contractKey:fi(!1,["boolean"]),contractKeyName:fi("X-JSONQL-CV-KEY",["string"]),enableTimeout:fi(!1,["boolean"]),timeout:fi(5e3,["number"]),returnInstance:fi(!1,["boolean"]),allowReturnRawToken:fi(!1,["boolean"]),debugOn:fi(!1,["boolean"])};function Aa(t){return ba(t,_)?Promise.resolve(t):function(t){var e=t.contract;return li(t,Ea,ka).then((function(t){return t.contract=e,t}))}(t)}var xa=new WeakMap,Ta=new WeakMap,Pa=function(){this.__suspend__=null,this.queueStore=new Set},qa={$suspend:{configurable:!0},$queues:{configurable:!0}};qa.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Pa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},qa.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Pa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Pa.prototype,qa);var Ca=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){xa.set(this,t)},r.normalStore.get=function(){return xa.get(this)},r.lazyStore.set=function(t){Ta.set(this,t)},r.lazyStore.get=function(){return Ta.get(this)},e.prototype.hashFnToKey=function(t){return It(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Pa));function $a(t,e){var r;return function(t,e,r){return void 0===e&&(e={}),Aa(e).then((function(t){return{baseClient:new ga(r,t),opts:t}})).then((function(e){var r=e.baseClient,n=e.opts;return Jt(r,n.contract).then((function(e){return Oa(r,n,e,t)}))}))}((r=e.debugOn,new Ca({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),e,t)}return function(t){return void 0===t&&(t={}),$a(new o,t)}})); +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.jsonqlClient = factory()); +}(this, (function () { 'use strict'; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var fly = createCommonjsModule(function (module, exports) { + (function webpackUniversalModuleDefinition(root, factory) { + { module.exports = factory(); } + })(commonjsGlobal, function() { + return /******/ (function(modules) { // webpackBootstrap + /******/ // The module cache + /******/ var installedModules = {}; + /******/ + /******/ // The require function + /******/ function __webpack_require__(moduleId) { + /******/ + /******/ // Check if module is in cache + /******/ if(installedModules[moduleId]) { + /******/ return installedModules[moduleId].exports; + /******/ } + /******/ // Create a new module (and put it into the cache) + /******/ var module = installedModules[moduleId] = { + /******/ i: moduleId, + /******/ l: false, + /******/ exports: {} + /******/ }; + /******/ + /******/ // Execute the module function + /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + /******/ + /******/ // Flag the module as loaded + /******/ module.l = true; + /******/ + /******/ // Return the exports of the module + /******/ return module.exports; + /******/ } + /******/ + /******/ + /******/ // expose the modules object (__webpack_modules__) + /******/ __webpack_require__.m = modules; + /******/ + /******/ // expose the module cache + /******/ __webpack_require__.c = installedModules; + /******/ + /******/ // identity function for calling harmony imports with the correct context + /******/ __webpack_require__.i = function(value) { return value; }; + /******/ + /******/ // define getter function for harmony exports + /******/ __webpack_require__.d = function(exports, name, getter) { + /******/ if(!__webpack_require__.o(exports, name)) { + /******/ Object.defineProperty(exports, name, { + /******/ configurable: false, + /******/ enumerable: true, + /******/ get: getter + /******/ }); + /******/ } + /******/ }; + /******/ + /******/ // getDefaultExport function for compatibility with non-harmony modules + /******/ __webpack_require__.n = function(module) { + /******/ var getter = module && module.__esModule ? + /******/ function getDefault() { return module['default']; } : + /******/ function getModuleExports() { return module; }; + /******/ __webpack_require__.d(getter, 'a', getter); + /******/ return getter; + /******/ }; + /******/ + /******/ // Object.prototype.hasOwnProperty.call + /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; + /******/ + /******/ // __webpack_public_path__ + /******/ __webpack_require__.p = ""; + /******/ + /******/ // Load entry module and return exports + /******/ return __webpack_require__(__webpack_require__.s = 2); + /******/ }) + /************************************************************************/ + /******/ ([ + /* 0 */ + /***/ (function(module, exports, __webpack_require__) { + + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + module.exports = { + type: function type(ob) { + return Object.prototype.toString.call(ob).slice(8, -1).toLowerCase(); + }, + isObject: function isObject(ob, real) { + if (real) { + return this.type(ob) === "object"; + } else { + return ob && (typeof ob === 'undefined' ? 'undefined' : _typeof(ob)) === 'object'; + } + }, + isFormData: function isFormData(val) { + return typeof FormData !== 'undefined' && val instanceof FormData; + }, + trim: function trim(str) { + return str.replace(/(^\s*)|(\s*$)/g, ''); + }, + encode: function encode(val) { + return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); + }, + formatParams: function formatParams(data) { + var str = ""; + var first = true; + var that = this; + if (!this.isObject(data)) { + return data; + } + + function _encode(sub, path) { + var encode = that.encode; + var type = that.type(sub); + if (type == "array") { + sub.forEach(function (e, i) { + if (!that.isObject(e)) { i = ""; } + _encode(e, path + ('%5B' + i + '%5D')); + }); + } else if (type == "object") { + for (var key in sub) { + if (path) { + _encode(sub[key], path + "%5B" + encode(key) + "%5D"); + } else { + _encode(sub[key], encode(key)); + } + } + } else { + if (!first) { + str += "&"; + } + first = false; + str += path + "=" + encode(sub); + } + } + + _encode(data, ""); + return str; + }, + + // Do not overwrite existing attributes + merge: function merge(a, b) { + for (var key in b) { + if (!a.hasOwnProperty(key)) { + a[key] = b[key]; + } else if (this.isObject(b[key], 1) && this.isObject(a[key], 1)) { + this.merge(a[key], b[key]); + } + } + return a; + } + }; + + /***/ }), + /* 1 */, + /* 2 */ + /***/ (function(module, exports, __webpack_require__) { + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var utils = __webpack_require__(0); + var isBrowser = typeof document !== "undefined"; + + var Fly = function () { + function Fly(engine) { + _classCallCheck(this, Fly); + + this.engine = engine || XMLHttpRequest; + + this.default = this; //For typeScript + + /** + * Add lock/unlock API for interceptor. + * + * Once an request/response interceptor is locked, the incoming request/response + * will be added to a queue before they enter the interceptor, they will not be + * continued until the interceptor is unlocked. + * + * @param [interceptor] either is interceptors.request or interceptors.response + */ + function wrap(interceptor) { + var resolve = void 0; + var reject = void 0; + + function _clear() { + interceptor.p = resolve = reject = null; + } + + utils.merge(interceptor, { + lock: function lock() { + if (!resolve) { + interceptor.p = new Promise(function (_resolve, _reject) { + resolve = _resolve; + reject = _reject; + }); + } + }, + unlock: function unlock() { + if (resolve) { + resolve(); + _clear(); + } + }, + clear: function clear() { + if (reject) { + reject("cancel"); + _clear(); + } + } + }); + } + + var interceptors = this.interceptors = { + response: { + use: function use(handler, onerror) { + this.handler = handler; + this.onerror = onerror; + } + }, + request: { + use: function use(handler) { + this.handler = handler; + } + } + }; + + var irq = interceptors.request; + var irp = interceptors.response; + wrap(irp); + wrap(irq); + + this.config = { + method: "GET", + baseURL: "", + headers: {}, + timeout: 0, + params: {}, // Default Url params + parseJson: true, // Convert response data to JSON object automatically. + withCredentials: false + }; + } + + _createClass(Fly, [{ + key: "request", + value: function request(url, data, options) { + var _this = this; + + var engine = new this.engine(); + var contentType = "Content-Type"; + var contentTypeLowerCase = contentType.toLowerCase(); + var interceptors = this.interceptors; + var requestInterceptor = interceptors.request; + var responseInterceptor = interceptors.response; + var requestInterceptorHandler = requestInterceptor.handler; + var promise = new Promise(function (resolve, reject) { + if (utils.isObject(url)) { + options = url; + url = options.url; + } + options = options || {}; + options.headers = options.headers || {}; + + function isPromise(p) { + // some polyfill implementation of Promise may be not standard, + // so, we test by duck-typing + return p && p.then && p.catch; + } + + /** + * If the request/response interceptor has been locked, + * the new request/response will enter a queue. otherwise, it will be performed directly. + * @param [promise] if the promise exist, means the interceptor is locked. + * @param [callback] + */ + function enqueueIfLocked(promise, callback) { + if (promise) { + promise.then(function () { + callback(); + }); + } else { + callback(); + } + } + + // make the http request + function makeRequest(options) { + data = options.body; + // Normalize the request url + url = utils.trim(options.url); + var baseUrl = utils.trim(options.baseURL || ""); + if (!url && isBrowser && !baseUrl) { url = location.href; } + if (url.indexOf("http") !== 0) { + var isAbsolute = url[0] === "/"; + if (!baseUrl && isBrowser) { + var arr = location.pathname.split("/"); + arr.pop(); + baseUrl = location.protocol + "//" + location.host + (isAbsolute ? "" : arr.join("/")); + } + if (baseUrl[baseUrl.length - 1] !== "/") { + baseUrl += "/"; + } + url = baseUrl + (isAbsolute ? url.substr(1) : url); + if (isBrowser) { + + // Normalize the url which contains the ".." or ".", such as + // "http://xx.com/aa/bb/../../xx" to "http://xx.com/xx" . + var t = document.createElement("a"); + t.href = url; + url = t.href; + } + } + + var responseType = utils.trim(options.responseType || ""); + var needQuery = ["GET", "HEAD", "DELETE", "OPTION"].indexOf(options.method) !== -1; + var dataType = utils.type(data); + var params = options.params || {}; + + // merge url params when the method is "GET" (data is object) + if (needQuery && dataType === "object") { + params = utils.merge(data, params); + } + // encode params to String + params = utils.formatParams(params); + + // save url params + var _params = []; + if (params) { + _params.push(params); + } + // Add data to url params when the method is "GET" (data is String) + if (needQuery && data && dataType === "string") { + _params.push(data); + } + + // make the final url + if (_params.length > 0) { + url += (url.indexOf("?") === -1 ? "?" : "&") + _params.join("&"); + } + + engine.open(options.method, url); + + // try catch for ie >=9 + try { + engine.withCredentials = !!options.withCredentials; + engine.timeout = options.timeout || 0; + if (responseType !== "stream") { + engine.responseType = responseType; + } + } catch (e) {} + + var customContentType = options.headers[contentType] || options.headers[contentTypeLowerCase]; + + // default content type + var _contentType = "application/x-www-form-urlencoded"; + // If the request data is json object, transforming it to json string, + // and set request content-type to "json". In browser, the data will + // be sent as RequestBody instead of FormData + if (utils.trim((customContentType || "").toLowerCase()) === _contentType) { + data = utils.formatParams(data); + } else if (!utils.isFormData(data) && ["object", "array"].indexOf(utils.type(data)) !== -1) { + _contentType = 'application/json;charset=utf-8'; + data = JSON.stringify(data); + } + //If user doesn't set content-type, set default. + if (!(customContentType || needQuery)) { + options.headers[contentType] = _contentType; + } + + for (var k in options.headers) { + if (k === contentType && utils.isFormData(data)) { + // Delete the content-type, Let the browser set it + delete options.headers[k]; + } else { + try { + // In browser environment, some header fields are readonly, + // write will cause the exception . + engine.setRequestHeader(k, options.headers[k]); + } catch (e) {} + } + } + + function onresult(handler, data, type) { + enqueueIfLocked(responseInterceptor.p, function () { + if (handler) { + //如果失败,添加请求信息 + if (type) { + data.request = options; + } + var ret = handler.call(responseInterceptor, data, Promise); + data = ret === undefined ? data : ret; + } + if (!isPromise(data)) { + data = Promise[type === 0 ? "resolve" : "reject"](data); + } + data.then(function (d) { + resolve(d); + }).catch(function (e) { + reject(e); + }); + }); + } + + function onerror(e) { + e.engine = engine; + onresult(responseInterceptor.onerror, e, -1); + } + + function Err(msg, status) { + this.message = msg; + this.status = status; + } + + engine.onload = function () { + try { + // The xhr of IE9 has not response field + var response = engine.response || engine.responseText; + if (response && options.parseJson && (engine.getResponseHeader(contentType) || "").indexOf("json") !== -1 + // Some third engine implementation may transform the response text to json object automatically, + // so we should test the type of response before transforming it + && !utils.isObject(response)) { + response = JSON.parse(response); + } + + var headers = engine.responseHeaders; + // In browser + if (!headers) { + headers = {}; + var items = (engine.getAllResponseHeaders() || "").split("\r\n"); + items.pop(); + items.forEach(function (e) { + if (!e) { return; } + var key = e.split(":")[0]; + headers[key] = engine.getResponseHeader(key); + }); + } + var status = engine.status; + var statusText = engine.statusText; + var _data = { data: response, headers: headers, status: status, statusText: statusText }; + // The _response filed of engine is set in adapter which be called in engine-wrapper.js + utils.merge(_data, engine._response); + if (status >= 200 && status < 300 || status === 304) { + _data.engine = engine; + _data.request = options; + onresult(responseInterceptor.handler, _data, 0); + } else { + var e = new Err(statusText, status); + e.response = _data; + onerror(e); + } + } catch (e) { + onerror(new Err(e.msg, engine.status)); + } + }; + + engine.onerror = function (e) { + onerror(new Err(e.msg || "Network Error", 0)); + }; + + engine.ontimeout = function () { + onerror(new Err("timeout [ " + engine.timeout + "ms ]", 1)); + }; + engine._options = options; + setTimeout(function () { + engine.send(needQuery ? null : data); + }, 0); + } + + enqueueIfLocked(requestInterceptor.p, function () { + utils.merge(options, JSON.parse(JSON.stringify(_this.config))); + var headers = options.headers; + headers[contentType] = headers[contentType] || headers[contentTypeLowerCase] || ""; + delete headers[contentTypeLowerCase]; + options.body = data || options.body; + url = utils.trim(url || ""); + options.method = options.method.toUpperCase(); + options.url = url; + var ret = options; + if (requestInterceptorHandler) { + ret = requestInterceptorHandler.call(requestInterceptor, options, Promise) || options; + } + if (!isPromise(ret)) { + ret = Promise.resolve(ret); + } + ret.then(function (d) { + //if options continue + if (d === options) { + makeRequest(d); + } else { + resolve(d); + } + }, function (err) { + reject(err); + }); + }); + }); + promise.engine = engine; + return promise; + } + }, { + key: "all", + value: function all(promises) { + return Promise.all(promises); + } + }, { + key: "spread", + value: function spread(callback) { + return function (arr) { + return callback.apply(null, arr); + }; + } + }]); + + return Fly; + }(); + + //For typeScript + + + Fly.default = Fly; + + ["get", "post", "put", "patch", "head", "delete"].forEach(function (e) { + Fly.prototype[e] = function (url, data, option) { + return this.request(url, data, utils.merge({ method: e }, option)); + }; + }); + ["lock", "unlock", "clear"].forEach(function (e) { + Fly.prototype[e] = function () { + this.interceptors.request[e](); + }; + }); + module.exports = Fly; + + /***/ }) + /******/ ]); + }); + }); + + var Fly = unwrapExports(fly); + + // the core stuff to id if it's calling with jsonql + var DATA_KEY = 'data'; + var ERROR_KEY = 'error'; + + var JSONQL_PATH = 'jsonql'; + // according to the json query spec + var CONTENT_TYPE = 'application/vnd.api+json'; + var CHARSET = 'charset=utf-8'; + var DEFAULT_HEADER = { + 'Accept': CONTENT_TYPE, + 'Content-Type': [ CONTENT_TYPE, CHARSET ].join(';') + }; + + // export const INDEX = 'index'; use INDEX_KEY instead + var DEFAULT_TYPE = 'any'; + + // @TODO remove this is not in use + // export const CLIENT_CONFIG_FILE = '.clients.json'; + // export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js'; + // type of resolvers + var QUERY_NAME = 'query'; + var MUTATION_NAME = 'mutation'; + var SOCKET_NAME = 'socket'; + // for calling the mutation + var PAYLOAD_PARAM_NAME = 'payload'; // @TODO shortern them + var CONDITION_PARAM_NAME = 'condition'; + var QUERY_ARG_NAME = 'args'; + var TIMESTAMP_PARAM_NAME = 'TS'; + // new jsonp + var JSONP_CALLBACK_NAME = 'jsonqlJsonpCallback'; + + // methods allow + var API_REQUEST_METHODS = ['POST', 'PUT']; + // for contract-cli + var KEY_WORD = 'continue'; + + var TYPE_KEY = 'type'; + var OPTIONAL_KEY = 'optional'; + var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word + var ARGS_KEY = 'args'; + var CHECKER_KEY = 'checker'; + var ALIAS_KEY = 'alias'; + var CHECKED_KEY = '__checked__'; + var LOGIN_NAME = 'login'; + var ISSUER_NAME = LOGIN_NAME; // legacy issue need to replace them later + var LOGOUT_NAME = 'logout'; + + var AUTH_HEADER = 'Authorization'; + var BEARER = 'Bearer'; + + // for client use @TODO need to clean this up some of them are not in use + var CREDENTIAL_STORAGE_KEY = 'jsonqlcredential'; + var CLIENT_STORAGE_KEY = 'jsonqlstore'; + var CLIENT_AUTH_KEY = 'jsonqlauthkey'; + // contract key + var CONTRACT_KEY_NAME = 'X-JSONQL-CV-KEY'; + var SHOW_CONTRACT_DESC_PARAM = {desc: 'y'}; + + var OR_SEPERATOR = '|'; + + var STRING_TYPE = 'string'; + var BOOLEAN_TYPE = 'boolean'; + var ARRAY_TYPE = 'array'; + var OBJECT_TYPE = 'object'; + + var NUMBER_TYPE = 'number'; + var ARRAY_TYPE_LFT = 'array.<'; + var ARRAY_TYPE_RGT = '>'; + + var NO_ERROR_MSG = 'No message'; + var NO_STATUS_CODE = -1; + var HSA_ALGO = 'HS256'; + + /** + * 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; + + 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$1 = root.Symbol; + + /** 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$1 ? Symbol$1.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$1 ? Symbol$1.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); + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** Built-in value references. */ + var getPrototype = overArg(Object.getPrototypeOf, Object); + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @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 objectTag = '[object Object]'; + + /** Used for built-in method references. */ + var funcProto = Function.prototype, + objectProto$2 = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty$1 = objectProto$2.hasOwnProperty; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty$1.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * 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; + } + + /** `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$1 ? Symbol$1.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(''); + } + + // bunch of generic helpers + + /** + * DIY in Array + * @param {array} arr to check from + * @param {*} value to check against + * @return {boolean} true on found + */ + var inArray = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; + + // quick and dirty to turn non array to array + var toArray = function (arg) { return isArray(arg) ? arg : [arg]; }; + + /** + * @param {object} obj for search + * @param {string} key target + * @return {boolean} true on success + */ + var isObjectHasKey = function(obj, key) { + try { + var keys = Object.keys(obj); + return inArray(keys, key) + } catch(e) { + // @BUG when the obj is not an OBJECT we got some weird output + return false; + /* + console.info('obj', obj) + console.error(e) + throw new Error(e) + */ + } + }; + + /** + * This is a custom error to throw when server throw a 406 + * 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 Jsonql406Error = /*@__PURE__*/(function (Error) { + function Jsonql406Error() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + this.message = args[0]; + this.detail = args[1]; + // We can't access the static name from an instance + // but we can do it like this + this.className = Jsonql406Error.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Jsonql406Error); + } + } + + if ( Error ) Jsonql406Error.__proto__ = Error; + Jsonql406Error.prototype = Object.create( Error && Error.prototype ); + Jsonql406Error.prototype.constructor = Jsonql406Error; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 406; + }; + + staticAccessors.name.get = function () { + return 'Jsonql406Error'; + }; + + Object.defineProperties( Jsonql406Error, staticAccessors ); + + return Jsonql406Error; + }(Error)); + + /** + * This is a custom error to throw when server throw a 500 + * 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 Jsonql500Error = /*@__PURE__*/(function (Error) { + function Jsonql500Error() { + 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 = Jsonql500Error.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Jsonql500Error); + } + } + + if ( Error ) Jsonql500Error.__proto__ = Error; + Jsonql500Error.prototype = Object.create( Error && Error.prototype ); + Jsonql500Error.prototype.constructor = Jsonql500Error; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 500; + }; + + staticAccessors.name.get = function () { + return 'Jsonql500Error'; + }; + + Object.defineProperties( Jsonql500Error, staticAccessors ); + + return Jsonql500Error; + }(Error)); + + /** + * this is the 403 Forbidden error + * that means this user is not login + * use the 401 for try to login and failed + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ + var JsonqlForbiddenError = /*@__PURE__*/(function (Error) { + function JsonqlForbiddenError() { + 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 = JsonqlForbiddenError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlForbiddenError); + } + } + + if ( Error ) JsonqlForbiddenError.__proto__ = Error; + JsonqlForbiddenError.prototype = Object.create( Error && Error.prototype ); + JsonqlForbiddenError.prototype.constructor = JsonqlForbiddenError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 403; + }; + + staticAccessors.name.get = function () { + return 'JsonqlForbiddenError'; + }; + + Object.defineProperties( JsonqlForbiddenError, staticAccessors ); + + return JsonqlForbiddenError; + }(Error)); + + /** + * This is a custom error to throw when pass credential but fail + * 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 JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { + function JsonqlAuthorisationError() { + 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 = JsonqlAuthorisationError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlAuthorisationError); + } + } + + if ( Error ) JsonqlAuthorisationError.__proto__ = Error; + JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); + JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 401; + }; + + staticAccessors.name.get = function () { + return 'JsonqlAuthorisationError'; + }; + + Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); + + return JsonqlAuthorisationError; + }(Error)); + + /** + * This is a custom error when not supply the credential and try to get contract + * 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 JsonqlContractAuthError = /*@__PURE__*/(function (Error) { + function JsonqlContractAuthError() { + 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 = JsonqlContractAuthError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlContractAuthError); + } + } + + if ( Error ) JsonqlContractAuthError.__proto__ = Error; + JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); + JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 401; + }; + + staticAccessors.name.get = function () { + return 'JsonqlContractAuthError'; + }; + + Object.defineProperties( JsonqlContractAuthError, staticAccessors ); + + return JsonqlContractAuthError; + }(Error)); + + /** + * This is a custom error to throw when the resolver throw error and capture inside the middleware + * 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 JsonqlResolverAppError = /*@__PURE__*/(function (Error) { + function JsonqlResolverAppError() { + 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 = JsonqlResolverAppError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlResolverAppError); + } + } + + if ( Error ) JsonqlResolverAppError.__proto__ = Error; + JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); + JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 500; + }; + + staticAccessors.name.get = function () { + return 'JsonqlResolverAppError'; + }; + + Object.defineProperties( JsonqlResolverAppError, staticAccessors ); + + return JsonqlResolverAppError; + }(Error)); + + /** + * This is a custom error to throw when could not find the resolver + * 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 JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { + function JsonqlResolverNotFoundError() { + 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 = JsonqlResolverNotFoundError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlResolverNotFoundError); + } + } + + if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; + JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); + JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 404; + }; + + staticAccessors.name.get = function () { + return 'JsonqlResolverNotFoundError'; + }; + + Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); + + return JsonqlResolverNotFoundError; + }(Error)); + + // this get throw from within the checkOptions when run through the enum failed + var JsonqlEnumError = /*@__PURE__*/(function (Error) { + function JsonqlEnumError() { + 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 = JsonqlEnumError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlEnumError); + } + } + + if ( Error ) JsonqlEnumError.__proto__ = Error; + JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); + JsonqlEnumError.prototype.constructor = JsonqlEnumError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlEnumError'; + }; + + Object.defineProperties( JsonqlEnumError, staticAccessors ); + + return JsonqlEnumError; + }(Error)); + + // this will throw from inside the checkOptions + var JsonqlTypeError = /*@__PURE__*/(function (Error) { + function JsonqlTypeError() { + 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 = JsonqlTypeError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlTypeError); + } + } + + if ( Error ) JsonqlTypeError.__proto__ = Error; + JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); + JsonqlTypeError.prototype.constructor = JsonqlTypeError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlTypeError'; + }; + + Object.defineProperties( JsonqlTypeError, staticAccessors ); + + return JsonqlTypeError; + }(Error)); + + // allow supply a custom checker function + // if that failed then we throw this error + var JsonqlCheckerError = /*@__PURE__*/(function (Error) { + function JsonqlCheckerError() { + 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 = JsonqlCheckerError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlCheckerError); + } + } + + if ( Error ) JsonqlCheckerError.__proto__ = Error; + JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); + JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlCheckerError'; + }; + + Object.defineProperties( JsonqlCheckerError, staticAccessors ); + + return JsonqlCheckerError; + }(Error)); + + // custom validation error class + // when validaton failed + var JsonqlValidationError = /*@__PURE__*/(function (Error) { + function JsonqlValidationError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlValidationError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlValidationError); + } + } + + if ( Error ) JsonqlValidationError.__proto__ = Error; + JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); + JsonqlValidationError.prototype.constructor = JsonqlValidationError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlValidationError'; + }; + + Object.defineProperties( JsonqlValidationError, staticAccessors ); + + return JsonqlValidationError; + }(Error)); + + /** + * This is a custom error to throw whenever a error happen inside the jsonql + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ + var JsonqlError = /*@__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)); + + // this is from an example from Koa team to use for internal middleware ctx.throw + // but after the test the res.body part is unable to extract the required data + // I keep this one here for future reference + + var JsonqlServerError = /*@__PURE__*/(function (Error) { + function JsonqlServerError(statusCode, message) { + Error.call(this, message); + this.statusCode = statusCode; + this.className = JsonqlServerError.name; + } + + if ( Error ) JsonqlServerError.__proto__ = Error; + JsonqlServerError.prototype = Object.create( Error && Error.prototype ); + JsonqlServerError.prototype.constructor = JsonqlServerError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlServerError'; + }; + + Object.defineProperties( JsonqlServerError, staticAccessors ); + + return JsonqlServerError; + }(Error)); + + // server side + + var errors = /*#__PURE__*/Object.freeze({ + __proto__: null, + Jsonql406Error: Jsonql406Error, + Jsonql500Error: Jsonql500Error, + JsonqlForbiddenError: JsonqlForbiddenError, + JsonqlAuthorisationError: JsonqlAuthorisationError, + JsonqlContractAuthError: JsonqlContractAuthError, + JsonqlResolverAppError: JsonqlResolverAppError, + JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, + JsonqlEnumError: JsonqlEnumError, + JsonqlTypeError: JsonqlTypeError, + JsonqlCheckerError: JsonqlCheckerError, + JsonqlValidationError: JsonqlValidationError, + JsonqlError: JsonqlError, + JsonqlServerError: JsonqlServerError + }); + + // this will add directly to the then call in each http call + var JsonqlError$1 = JsonqlError; + + /** + * We can not just check something like result.data what if the result if false? + * @param {object} obj the result object + * @param {string} key we want to check if its exist or not + * @return {boolean} true on found + */ + var isObjectHasKey$1 = function (obj, key) { + var keys = Object.keys(obj); + return !!keys.filter(function (k) { return key === k; }).length; + }; + + /** + * It will ONLY have our own jsonql specific implement check + * @param {object} result the server return result + * @return {object} this will just throw error + */ + function clientErrorsHandler(result) { + if (isObjectHasKey$1(result, 'error')) { + var error = result.error; + var className = error.className; + var name = error.name; + var errorName = className || name; + // just throw the whole thing back + var msg = error.message || NO_ERROR_MSG; + var detail = error.detail || error; + if (errorName && errors[errorName]) { + throw new errors[className](msg, detail) + } + throw new JsonqlError$1(msg, detail) + } + // pass through to the next + return result; + } + + /** + * this will put into generator call at the very end and catch + * the error throw from inside then throw again + * this is necessary because we split calls inside and the throw + * will not reach the actual client unless we do it this way + * @param {object} e Error + * @return {void} just throw + */ + function finalCatch(e) { + // this is a hack to get around the validateAsync not actually throw error + // instead it just rejected it with the array of failed parameters + if (Array.isArray(e)) { + // if we want the message then I will have to create yet another function + // to wrap this function to provide the name prop + throw new JsonqlValidationError('', e) + } + var msg = e.message || NO_ERROR_MSG; + var detail = e.detail || e; + // @BUG the instance of not always work for some reason! + // need to figure out a better way to find out the type of the error + switch (true) { + case e instanceof Jsonql406Error: + throw new Jsonql406Error(msg, detail) + case e instanceof Jsonql500Error: + throw new Jsonql500Error(msg, detail) + case e instanceof JsonqlForbiddenError: + throw new JsonqlForbiddenError(msg, detail) + case e instanceof JsonqlAuthorisationError: + throw new JsonqlAuthorisationError(msg, detail) + case e instanceof JsonqlContractAuthError: + throw new JsonqlContractAuthError(msg, detail) + case e instanceof JsonqlResolverAppError: + throw new JsonqlResolverAppError(msg, detail) + case e instanceof JsonqlResolverNotFoundError: + throw new JsonqlResolverNotFoundError(msg, detail) + case e instanceof JsonqlEnumError: + throw new JsonqlEnumError(msg, detail) + case e instanceof JsonqlTypeError: + throw new JsonqlTypeError(msg, detail) + case e instanceof JsonqlCheckerError: + throw new JsonqlCheckerError(msg, detail) + case e instanceof JsonqlValidationError: + throw new JsonqlValidationError(msg, detail) + case e instanceof JsonqlServerError: + throw new JsonqlServerError(msg, detail) + default: + throw new JsonqlError(msg, detail) + } + } + + // split the contract into the node side and the generic side + /** + * Check if the json is a contract file or not + * @param {object} contract json object + * @return {boolean} true + */ + function checkIsContract(contract) { + return isPlainObject(contract) + && ( + isObjectHasKey(contract, QUERY_NAME) + || isObjectHasKey(contract, MUTATION_NAME) + || isObjectHasKey(contract, SOCKET_NAME) + ) + } + + /** + * Wrapper method that check if it's contract then return the contract or false + * @param {object} contract the object to check + * @return {boolean | object} false when it's not + */ + function isContract(contract) { + return checkIsContract(contract) ? contract : false; + } + + /** + * generate a 32bit hash based on the function.toString() + * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery + * @param {string} s the converted to string function + * @return {string} the hashed function string + */ + function hashCode(s) { + return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) + } + + // take only the module part which is what we use here + /** + * @param {object} jsonqlInstance the init instance of jsonql client + * @param {object} contract the static contract + * @return {object} contract may be from server + */ + var getContractFromConfig = function(jsonqlInstance, contract) { + if ( contract === void 0 ) contract = {}; + + if (isContract(contract)) { + return Promise.resolve(contract) + } + return jsonqlInstance.getContract() + }; + // wrapper method to make sure it's a string + var hashCode$1 = function (str) { return hashCode(str) + ''; }; + var USERDATA_TABLE = 'userdata'; + var CLS_LOCAL_STORE_NAME = 'localStore'; + var CLS_SESS_STORE_NAME = 'sessionStore'; + var CLS_CONTRACT_NAME = 'contract'; + var CLS_PROFILE_IDX = 'prof_idx'; + var LOG_ERROR_SWITCH = '__error__'; + var ZERO_IDX = 0; + + /** + * The code was extracted from: + * https://github.com/davidchambers/Base64.js + */ + + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + + function InvalidCharacterError(message) { + this.message = message; + } + + InvalidCharacterError.prototype = new Error(); + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + + function polyfill (input) { + var str = String(input).replace(/=+$/, ''); + if (str.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); + } + for ( + // initialize result and counters + var bc = 0, bs, buffer, idx = 0, output = ''; + // get next character + buffer = str.charAt(idx++); + // character found in table? initialize bit storage and add its ascii value; + ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, + // and if not first of each 4 characters, + // convert the first 8 bits to one ascii character + bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 + ) { + // try to find character in table (0-63, not found => -1) + buffer = chars.indexOf(buffer); + } + return output; + } + + + var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; + + function b64DecodeUnicode(str) { + return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { + var code = p.charCodeAt(0).toString(16).toUpperCase(); + if (code.length < 2) { + code = '0' + code; + } + return '%' + code; + })); + } + + var base64_url_decode = function(str) { + var output = str.replace(/-/g, "+").replace(/_/g, "/"); + switch (output.length % 4) { + case 0: + break; + case 2: + output += "=="; + break; + case 3: + output += "="; + break; + default: + throw "Illegal base64url string!"; + } + + try{ + return b64DecodeUnicode(output); + } catch (err) { + return atob(output); + } + }; + + function InvalidTokenError(message) { + this.message = message; + } + + InvalidTokenError.prototype = new Error(); + InvalidTokenError.prototype.name = 'InvalidTokenError'; + + var lib = function (token,options) { + if (typeof token !== 'string') { + throw new InvalidTokenError('Invalid token specified'); + } + + options = options || {}; + var pos = options.header === true ? 0 : 1; + try { + return JSON.parse(base64_url_decode(token.split('.')[pos])); + } catch (e) { + throw new InvalidTokenError('Invalid token specified: ' + e.message); + } + }; + + var InvalidTokenError_1 = InvalidTokenError; + lib.InvalidTokenError = InvalidTokenError_1; + + /** `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; + }; + + // when the user is login with the jwt + + 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 = lib(token); + return validate(t) + } + throw new JsonqlError('Token must be a string!') + } + + /** + * Check several parameter that there is something in the param + * @param {*} param input + * @return {boolean} + */ + var isNotEmpty = function (a) { + if (isArray(a)) { + return true; + } + return a !== undefined && a !== null && trim(a) !== ''; + }; + + /** `Object#toString` result references. */ + var numberTag = '[object Number]'; + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + // validator numbers + /** + * @2015-05-04 found a problem if the value is a number like string + * it will pass, so add a chck if it's string before we pass to next + * @param {number} value expected value + * @return {boolean} true if OK + */ + var checkIsNumber = function(value) { + return isString(value) ? false : !isNaN( parseFloat(value) ) + }; + + // check for boolean + + /** + * @param {boolean} value expected + * @return {boolean} true if OK + */ + var checkIsBoolean = function(value) { + return value !== null && value !== undefined && typeof value === 'boolean' + }; + + // validate any thing only check if there is something + + /** + * @param {*} value the value + * @param {boolean} [checkNull=true] strict check if there is null value + * @return {boolean} true is OK + */ + var checkIsAny = function(value, checkNull) { + if ( checkNull === void 0 ) checkNull = true; + + if (value !== undefined && value !== '' && trim(value) !== '') { + if (checkNull === false || (checkNull === true && value !== null)) { + return true; + } + } + return false; + }; + + // Good practice rule - No magic number + + var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; + var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; + var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; + // @TODO the jsdoc return array. and we should also allow array syntax + var DEFAULT_TYPE$1 = DEFAULT_TYPE; + var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; + var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; + + var TYPE_KEY$1 = TYPE_KEY; + var OPTIONAL_KEY$1 = OPTIONAL_KEY; + var ENUM_KEY$1 = ENUM_KEY; + var ARGS_KEY$1 = ARGS_KEY; + var CHECKER_KEY$1 = CHECKER_KEY; + var ALIAS_KEY$1 = ALIAS_KEY; + + var ARRAY_TYPE$1 = ARRAY_TYPE; + var OBJECT_TYPE$1 = OBJECT_TYPE; + var STRING_TYPE$1 = STRING_TYPE; + var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; + var NUMBER_TYPE$1 = NUMBER_TYPE; + var KEY_WORD$1 = KEY_WORD; + var OR_SEPERATOR$1 = OR_SEPERATOR; + + // not actually in use + // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; + + // primitive types + + /** + * this is a wrapper method to call different one based on their type + * @param {string} type to check + * @return {function} a function to handle the type + */ + var combineFn = function(type) { + switch (type) { + case NUMBER_TYPE$1: + return checkIsNumber; + case STRING_TYPE$1: + return checkIsString; + case BOOLEAN_TYPE$1: + return checkIsBoolean; + default: + return checkIsAny; + } + }; + + // validate array type + + /** + * @param {array} value expected + * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well + * @return {boolean} true if OK + */ + var checkIsArray = function(value, type) { + if ( type === void 0 ) type=''; + + if (isArray(value)) { + if (type === '' || trim(type)==='') { + return true; + } + // we test it in reverse + // @TODO if the type is an array (OR) then what? + // we need to take into account this could be an array + var c = value.filter(function (v) { return !combineFn(type)(v); }); + return !(c.length > 0) + } + return false; + }; + + /** + * check if it matches the array. pattern + * @param {string} type + * @return {boolean|array} false means NO, always return array + */ + var isArrayLike = function(type) { + // @TODO could that have something like array<> instead of array.<>? missing the dot? + // because type script is Array without the dot + if (type.indexOf(ARRAY_TYPE_LFT$1) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { + var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); + if (_type.indexOf(OR_SEPERATOR$1)) { + return _type.split(OR_SEPERATOR$1) + } + return [_type] + } + return false; + }; + + /** + * we might encounter something like array. then we need to take it apart + * @param {object} p the prepared object for processing + * @param {string|array} type the type came from + * @return {boolean} for the filter to operate on + */ + var arrayTypeHandler = function(p, type) { + var arg = p.arg; + // need a special case to handle the OR type + // we need to test the args instead of the type(s) + if (type.length > 1) { + return !arg.filter(function (v) { return ( + !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) + ); }).length; + } + // type is array so this will be or! + return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length; + }; + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]'; + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** Used for built-in method references. */ + var objectProto$3 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$2 = objectProto$3.hasOwnProperty; + + /** Built-in value references. */ + var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + function stubFalse() { + return false; + } + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Built-in value references. */ + var Buffer = moduleExports ? root.Buffer : undefined; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER = 9007199254740991; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER$1 = 9007199254740991; + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; + } + + /** `Object#toString` result references. */ + var argsTag$1 = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag$1 = '[object Number]', + objectTag$1 = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag$1 = '[object String]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag$1] = + typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag$1] = + typedArrayTags[weakMapTag] = false; + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** Detect free variable `exports`. */ + var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports$1 && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** Used for built-in method references. */ + var objectProto$4 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$3 = objectProto$4.hasOwnProperty; + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$3.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** Used for built-in method references. */ + var objectProto$5 = Object.prototype; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; + + return value === proto; + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeKeys = overArg(Object.keys, Object); + + /** Used for built-in method references. */ + var objectProto$6 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$4 = objectProto$6.hasOwnProperty; + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$4.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** `Object#toString` result references. */ + var asyncTag = '[object AsyncFunction]', + funcTag$1 = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike$1(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** Used for built-in method references. */ + var arrayProto = Array.prototype; + + /** Built-in value references. */ + var splice = arrayProto.splice; + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** Used to detect overreaching core-js shims. */ + var coreJsData = root['__core-js_shared__']; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** Used for built-in method references. */ + var funcProto$1 = Function.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString$1 = funcProto$1.toString; + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString$1.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used for built-in method references. */ + var funcProto$2 = Function.prototype, + objectProto$7 = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString$2 = funcProto$2.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty$5 = objectProto$7.hasOwnProperty; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString$2.call(hasOwnProperty$5).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /* Built-in method references that are verified to be native. */ + var Map$1 = getNative(root, 'Map'); + + /* Built-in method references that are verified to be native. */ + var nativeCreate = getNative(Object, 'create'); + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used for built-in method references. */ + var objectProto$8 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$6 = objectProto$8.hasOwnProperty; + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty$6.call(data, key) ? data[key] : undefined; + } + + /** Used for built-in method references. */ + var objectProto$9 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$7 = objectProto$9.hasOwnProperty; + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key); + } + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; + return this; + } + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map$1 || ListCache), + 'string': new Hash + }; + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED$2); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** Built-in value references. */ + var Uint8Array$1 = root.Uint8Array; + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$1 = 1, + COMPARE_UNORDERED_FLAG$1 = 2; + + /** `Object#toString` result references. */ + var boolTag$1 = '[object Boolean]', + dateTag$1 = '[object Date]', + errorTag$1 = '[object Error]', + mapTag$1 = '[object Map]', + numberTag$2 = '[object Number]', + regexpTag$1 = '[object RegExp]', + setTag$1 = '[object Set]', + stringTag$2 = '[object String]', + symbolTag$1 = '[object Symbol]'; + + var arrayBufferTag$1 = '[object ArrayBuffer]', + dataViewTag$1 = '[object DataView]'; + + /** Used to convert symbols to primitives and strings. */ + var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined, + symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag$1: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag$1: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array$1(object), new Uint8Array$1(other))) { + return false; + } + return true; + + case boolTag$1: + case dateTag$1: + case numberTag$2: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag$1: + return object.name == other.name && object.message == other.message; + + case regexpTag$1: + case stringTag$2: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag$1: + var convert = mapToArray; + + case setTag$1: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG$1; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag$1: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + function stubArray() { + return []; + } + + /** Used for built-in method references. */ + var objectProto$a = Object.prototype; + + /** Built-in value references. */ + var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols = Object.getOwnPropertySymbols; + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable$1.call(object, symbol); + }); + }; + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$2 = 1; + + /** Used for built-in method references. */ + var objectProto$b = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$8 = objectProto$b.hasOwnProperty; + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(root, 'DataView'); + + /* Built-in method references that are verified to be native. */ + var Promise$1 = getNative(root, 'Promise'); + + /* Built-in method references that are verified to be native. */ + var Set$1 = getNative(root, 'Set'); + + /* Built-in method references that are verified to be native. */ + var WeakMap$1 = getNative(root, 'WeakMap'); + + /** `Object#toString` result references. */ + var mapTag$2 = '[object Map]', + objectTag$2 = '[object Object]', + promiseTag = '[object Promise]', + setTag$2 = '[object Set]', + weakMapTag$1 = '[object WeakMap]'; + + var dataViewTag$2 = '[object DataView]'; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map$1), + promiseCtorString = toSource(Promise$1), + setCtorString = toSource(Set$1), + weakMapCtorString = toSource(WeakMap$1); + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$2) || + (Map$1 && getTag(new Map$1) != mapTag$2) || + (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || + (Set$1 && getTag(new Set$1) != setTag$2) || + (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag$2 ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag$2; + case mapCtorString: return mapTag$2; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag$2; + case weakMapCtorString: return weakMapTag$1; + } + } + return result; + }; + } + + var getTag$1 = getTag; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$3 = 1; + + /** `Object#toString` result references. */ + var argsTag$2 = '[object Arguments]', + arrayTag$1 = '[object Array]', + objectTag$3 = '[object Object]'; + + /** Used for built-in method references. */ + var objectProto$c = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$9 = objectProto$c.hasOwnProperty; + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag$1 : getTag$1(object), + othTag = othIsArr ? arrayTag$1 : getTag$1(other); + + objTag = objTag == argsTag$2 ? objectTag$3 : objTag; + othTag = othTag == argsTag$2 ? objectTag$3 : othTag; + + var objIsObj = objTag == objectTag$3, + othIsObj = othTag == objectTag$3, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { + var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$4 = 1, + COMPARE_UNORDERED_FLAG$2 = 2; + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** Error message constants. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** Used to match property names within property paths. */ + var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** Used as references for various `Number` constants. */ + var INFINITY$1 = 1 / 0; + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$5 = 1, + COMPARE_UNORDERED_FLAG$3 = 2; + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); + }; + } + + /** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + function identity(value) { + return value; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ + function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + // validate object type + /** + * @TODO if provide with the keys then we need to check if the key:value type as well + * @param {object} value expected + * @param {array} [keys=null] if it has the keys array to compare as well + * @return {boolean} true if OK + */ + var checkIsObject = function(value, keys) { + if ( keys === void 0 ) keys=null; + + if (isPlainObject(value)) { + if (!keys) { + return true; + } + if (checkIsArray(keys)) { + // please note we DON'T care if some is optional + // plese refer to the contract.json for the keys + return !keys.filter(function (key) { + var _value = value[key.name]; + return !(key.type.length > key.type.filter(function (type) { + var tmp; + if (_value !== undefined) { + if ((tmp = isArrayLike(type)) !== false) { + return !arrayTypeHandler({arg: _value}, tmp) + // return tmp.filter(t => !checkIsArray(_value, t)).length; + // @TODO there might be an object within an object with keys as well :S + } + return !combineFn(type)(_value) + } + return true; + }).length) + }).length; + } + } + return false; + }; + + /** + * fold this into it's own function to handler different object type + * @param {object} p the prepared object for process + * @return {boolean} + */ + var objectTypeHandler = function(p) { + var arg = p.arg; + var param = p.param; + var _args = [arg]; + if (Array.isArray(param.keys) && param.keys.length) { + _args.push(param.keys); + } + // just simple check + return Reflect.apply(checkIsObject, null, _args) + }; + + // move the index.js code here that make more sense to find where things are + // import debug from 'debug' + // const debugFn = debug('jsonql-params-validator:validator') + // also export this for use in other places + + /** + * We need to handle those optional parameter without a default value + * @param {object} params from contract.json + * @return {boolean} for filter operation false is actually OK + */ + var optionalHandler = function( params ) { + var arg = params.arg; + var param = params.param; + if (isNotEmpty(arg)) { + // debug('call optional handler', arg, params); + // loop through the type in param + return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } + ).length) + } + return false; + }; + + /** + * actually picking the validator + * @param {*} type for checking + * @param {*} value for checking + * @return {boolean} true on OK + */ + var validateHandler = function(type, value) { + var tmp; + switch (true) { + case type === OBJECT_TYPE$1: + // debugFn('call OBJECT_TYPE') + return !objectTypeHandler(value) + case type === ARRAY_TYPE$1: + // debugFn('call ARRAY_TYPE') + return !checkIsArray(value.arg) + // @TODO when the type is not present, it always fall through here + // so we need to find a way to actually pre-check the type first + // AKA check the contract.json map before running here + case (tmp = isArrayLike(type)) !== false: + // debugFn('call ARRAY_LIKE: %O', value) + return !arrayTypeHandler(value, tmp) + default: + return !combineFn(type)(value.arg) + } + }; + + /** + * it get too longer to fit in one line so break it out from the fn below + * @param {*} arg value + * @param {object} param config + * @return {*} value or apply default value + */ + var getOptionalValue = function(arg, param) { + if (arg !== undefined) { + return arg; + } + return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null) + }; + + /** + * padding the arguments with defaultValue if the arguments did not provide the value + * this will be the name export + * @param {array} args normalized arguments + * @param {array} params from contract.json + * @return {array} merge the two together + */ + var normalizeArgs = function(args, params) { + // first we should check if this call require a validation at all + // there will be situation where the function doesn't need args and params + if (!checkIsArray(params)) { + // debugFn('params value', params) + throw new JsonqlError(PARAMS_NOT_ARRAY_ERR) + } + if (params.length === 0) { + return []; + } + if (!checkIsArray(args)) { + throw new JsonqlError(ARGS_NOT_ARRAY_ERR) + } + // debugFn(args, params); + // fall through switch + switch(true) { + case args.length == params.length: // standard + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, + param: params[i] + } + ); }) + case params[0].variable === true: // using spread syntax + var type = params[0].type; + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, // keep the index for reference + param: params[i] || { type: type, name: '_' } + } + ); }) + // with optional defaultValue parameters + case args.length < params.length: + return params.map(function (param, i) { return ( + { + param: param, + index: i, + arg: getOptionalValue(args[i], param), + optional: param.optional || false + } + ); }) + // this one pass more than it should have anything after the args.length will be cast as any type + case args.length > params.length: + var ctn = params.length; + // this happens when we have those array. type + var _type = [ DEFAULT_TYPE$1 ]; + // we only looking at the first one, this might be a @BUG + /* + if ((tmp = isArrayLike(params[0].type[0])) !== false) { + _type = tmp; + } */ + // if we use the params as guide then the rest will get throw out + // which is not what we want, instead, anything without the param + // will get a any type and optional flag + return args.map(function (arg, i) { + var optional = i >= ctn ? true : !!params[i].optional; + var param = params[i] || { type: _type, name: ("_" + i) }; + return { + arg: optional ? getOptionalValue(arg, param) : arg, + index: i, + param: param, + optional: optional + } + }) + // @TODO find out if there is more cases not cover + default: // this should never happen + // debugFn('args', args) + // debugFn('params', params) + // this is unknown therefore we just throw it! + throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) + } + }; + + // what we want is after the validaton we also get the normalized result + // which is with the optional property if the argument didn't provide it + /** + * process the array of params back to their arguments + * @param {array} result the params result + * @return {array} arguments + */ + var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; + + /** + * validator main interface + * @param {array} args the arguments pass to the method call + * @param {array} params from the contract for that method + * @param {boolean} [withResul=false] if true then this will return the normalize result as well + * @return {array} empty array on success, or failed parameter and reasons + */ + var validateSync = function(args, params, withResult) { + var obj; + + if ( withResult === void 0 ) withResult = false; + var cleanArgs = normalizeArgs(args, params); + var checkResult = cleanArgs.filter(function (p) { + // v1.4.4 this fixed the problem, the root level optional is from the last fn + if (p.optional === true || p.param.optional === true) { + return optionalHandler(p) + } + // because array of types means OR so if one pass means pass + return !(p.param.type.length > p.param.type.filter( + function (type) { return validateHandler(type, p); } + ).length) + }); + // using the same convention we been using all this time + return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) + }; + + /** + * A wrapper method that return promise + * @param {array} args arguments + * @param {array} params from contract.json + * @param {boolean} [withResul=false] if true then this will return the normalize result as well + * @return {object} promise.then or catch + */ + var validateAsync = function(args, params, withResult) { + if ( withResult === void 0 ) withResult = false; + + return new Promise(function (resolver, rejecter) { + var result = validateSync(args, params, withResult); + if (withResult) { + return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) + : resolver(result[DATA_KEY]) + } + // the different is just in the then or catch phrase + return result.length ? rejecter(result) : resolver([]) + }) + }; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** Detect free variable `exports`. */ + var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; + + /** Built-in value references. */ + var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, + allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** Built-in value references. */ + var objectCreate = Object.create; + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike$1(value); + } + + /** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; + } + + /** Used for built-in method references. */ + var objectProto$d = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$a = objectProto$d.hasOwnProperty; + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty$a.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** Used for built-in method references. */ + var objectProto$e = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$b = objectProto$e.hasOwnProperty; + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty$b.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike$1(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeMax = Math.max; + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ + function constant(value) { + return function() { + return value; + }; + } + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeNow = Date.now; + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike$1(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** Error message constants. */ + var FUNC_ERROR_TEXT$1 = 'Expected a function'; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$1); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols$1 = Object.getOwnPropertySymbols; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = baseIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(baseIteratee(predicate))); + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate), baseForOwn); + } + + /** + * @param {array} arr Array for check + * @param {*} value target + * @return {boolean} true on successs + */ + var isInArray = function(arr, value) { + return !!arr.filter(function (a) { return a === value; }).length; + }; + + var isObjectHasKey$2 = function(obj, key) { + var keys = Object.keys(obj); + return isInArray(keys, key) + }; + + // just not to make my head hurt + var isEmpty = function (value) { return !isNotEmpty(value); }; + + /** + * Map the alias to their key then grab their value over + * @param {object} config the user supplied config + * @param {object} appProps the default option map + * @return {object} the config keys replaced with the appProps key by the ALIAS + */ + function mapAliasConfigKeys(config, appProps) { + // need to do two steps + // 1. take key with alias key + var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$1]; } ); + if (isEqual(aliasMap, {})) { + return config; + } + return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) + } + + /** + * We only want to run the valdiation against the config (user supplied) value + * but keep the defaultOptions untouch + * @param {object} config configuraton supplied by user + * @param {object} appProps the default options map + * @return {object} the pristine values that will add back to the final output + */ + function preservePristineValues(config, appProps) { + // @BUG this will filter out those that is alias key + // we need to first map the alias keys back to their full key + var _config = mapAliasConfigKeys(config, appProps); + // take the default value out + var pristineValues = mapValues( + omitBy(appProps, function (value, key) { return isObjectHasKey$2(_config, key); }), + function (value) { return value.args; } + ); + // for testing the value + var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !isObjectHasKey$2(_config, key); }); + // output + return { + pristineValues: pristineValues, + checkAgainstAppProps: checkAgainstAppProps, + config: _config // passing this correct values back + } + } + + /** + * This will take the value that is ONLY need to check + * @param {object} config that one + * @param {object} props map for creating checking + * @return {object} put that arg into the args + */ + function processConfigAction(config, props) { + // debugFn('processConfigAction', props) + // v.1.2.0 add checking if its mark optional and the value is empty then pass + return mapValues(props, function (value, key) { + var obj, obj$1; + + return ( + config[key] === undefined || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) + ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) + : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) + ); + } + ) + } + + /** + * Quick transform + * @TODO we should only validate those that is pass from the config + * and pass through those values that is from the defaultOptions + * @param {object} opts that one + * @param {object} appProps mutation configuration options + * @return {object} put that arg into the args + */ + function prepareArgsForValidation(opts, appProps) { + var ref = preservePristineValues(opts, appProps); + var config = ref.config; + var pristineValues = ref.pristineValues; + var checkAgainstAppProps = ref.checkAgainstAppProps; + // output + return [ + processConfigAction(config, checkAgainstAppProps), + pristineValues + ] + } + + // breaking the whole thing up to see what cause the multiple calls issue + + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:options:validation') + + /** + * just make sure it returns an array to use + * @param {*} arg input + * @return {array} output + */ + var toArray$1 = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; + + /** + * DIY in array + * @param {array} arr to check against + * @param {*} value to check + * @return {boolean} true on OK + */ + var inArray$1 = function (arr, value) { return ( + !!arr.filter(function (v) { return v === value; }).length + ); }; + + /** + * break out to make the code easier to read + * @param {object} value to process + * @param {function} cb the validateSync + * @return {array} empty on success + */ + function validateHandler$1(value, cb) { + var obj; + + // cb is the validateSync methods + var args = [ + [ value[ARGS_KEY$1] ], + [( obj = {}, obj[TYPE_KEY$1] = toArray$1(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] + ]; + // debugFn('validateHandler', args) + return Reflect.apply(cb, null, args) + } + + /** + * Check against the enum value if it's provided + * @param {*} value to check + * @param {*} enumv to check against if it's not false + * @return {boolean} true on OK + */ + var enumHandler = function (value, enumv) { + if (checkIsArray(enumv)) { + return inArray$1(enumv, value) + } + return true; + }; + + /** + * Allow passing a function to check the value + * There might be a problem here if the function is incorrect + * and that will makes it hard to debug what is going on inside + * @TODO there could be a few feature add to this one under different circumstance + * @param {*} value to check + * @param {function} checker for checking + */ + var checkerHandler = function (value, checker) { + try { + return isFunction(checker) ? checker.apply(null, [value]) : false; + } catch (e) { + return false; + } + }; + + /** + * Taken out from the runValidaton this only validate the required values + * @param {array} args from the config2argsAction + * @param {function} cb validateSync + * @return {array} of configuration values + */ + function runValidationAction(cb) { + return function (value, key) { + // debugFn('runValidationAction', key, value) + if (value[KEY_WORD$1]) { + return value[ARGS_KEY$1] + } + var check = validateHandler$1(value, cb); + if (check.length) { + // log('runValidationAction', key, value) + throw new JsonqlTypeError(key, check) + } + if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { + // log(ENUM_KEY, value[ENUM_KEY]) + throw new JsonqlEnumError(key) + } + if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { + // log(CHECKER_KEY, value[CHECKER_KEY]) + throw new JsonqlCheckerError(key) + } + return value[ARGS_KEY$1] + } + } + + /** + * @param {object} args from the config2argsAction + * @param {function} cb validateSync + * @return {object} of configuration values + */ + function runValidation(args, cb) { + var argsForValidate = args[0]; + var pristineValues = args[1]; + // turn the thing into an array and see what happen here + // debugFn('_args', argsForValidate) + var result = mapValues(argsForValidate, runValidationAction(cb)); + return merge(result, pristineValues) + } + + /// this is port back from the client to share across all projects + + // import debug from 'debug' + // const debugFn = debug('jsonql-params-validator:check-options-async') + + /** + * Quick transform + * @param {object} config that one + * @param {object} appProps mutation configuration options + * @return {object} put that arg into the args + */ + var configToArgs = function (config, appProps) { + return Promise.resolve( + prepareArgsForValidation(config, appProps) + ) + }; + + /** + * @param {object} config user provide configuration option + * @param {object} appProps mutation configuration options + * @param {object} constProps the immutable configuration options + * @param {function} cb the validateSync method + * @return {object} Promise resolve merge config object + */ + function checkOptionsAsync(config, appProps, constProps, cb) { + if ( config === void 0 ) config = {}; + + return configToArgs(config, appProps) + .then(function (args1) { return runValidation(args1, cb); }) + // next if every thing good then pass to final merging + .then(function (args2) { return merge({}, args2, constProps); }) + } + + // create function to construct the config entry so we don't need to keep building object + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:construct-config'); + /** + * @param {*} args value + * @param {string} type for value + * @param {boolean} [optional=false] + * @param {boolean|array} [enumv=false] + * @param {boolean|function} [checker=false] + * @return {object} config entry + */ + function constructConfig(args, type, optional, enumv, checker, alias) { + if ( optional === void 0 ) optional=false; + if ( enumv === void 0 ) enumv=false; + if ( checker === void 0 ) checker=false; + if ( alias === void 0 ) alias=false; + + var base = {}; + base[ARGS_KEY] = args; + base[TYPE_KEY] = type; + if (optional === true) { + base[OPTIONAL_KEY] = true; + } + if (checkIsArray(enumv)) { + base[ENUM_KEY] = enumv; + } + if (isFunction(checker)) { + base[CHECKER_KEY] = checker; + } + if (isString(alias)) { + base[ALIAS_KEY] = alias; + } + return base; + } + + // export also create wrapper methods + + /** + * This has a different interface + * @param {*} value to supply + * @param {string|array} type for checking + * @param {object} params to map against the config check + * @param {array} params.enumv NOT enum + * @param {boolean} params.optional false then nothing + * @param {function} params.checker need more work on this one later + * @param {string} params.alias mostly for cmd + */ + var createConfig = function (value, type, params) { + if ( params === void 0 ) params = {}; + + // Note the enumv not ENUM + // const { enumv, optional, checker, alias } = params; + // let args = [value, type, optional, enumv, checker, alias]; + var o = params[OPTIONAL_KEY]; + var e = params[ENUM_KEY]; + var c = params[CHECKER_KEY]; + var a = params[ALIAS_KEY]; + return constructConfig.apply(null, [value, type, o, e, c, a]) + }; + + /** + * We recreate the method here to avoid the circlar import + * @param {object} config user supply configuration + * @param {object} appProps mutation options + * @param {object} [constantProps={}] optional: immutation options + * @return {object} all checked configuration + */ + var checkConfigAsync = function(validateSync) { + return function(config, appProps, constantProps) { + if ( constantProps === void 0 ) constantProps= {}; + + return checkOptionsAsync(config, appProps, constantProps, validateSync) + } + }; + + // export + var isString$1 = checkIsString; + var isNumber$1 = checkIsNumber; + var validateAsync$1 = validateAsync; + + var createConfig$1 = createConfig; + + var checkConfigAsync$1 = checkConfigAsync(validateSync); + + var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; + + var appProps = { + algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), + expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), + notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), + audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), + subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), + issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), + noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), + header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), + keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), + mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) + }; + + /** + * @param {boolean} sec return in second or not + * @return {number} timestamp + */ + var timestamp$1 = function (sec) { + if ( sec === void 0 ) sec = false; + + var time = Date.now(); + return sec ? Math.floor( time / 1000 ) : time; + }; + + var assign = make_assign(); + var create = make_create(); + var trim$1 = make_trim(); + var Global = (typeof window !== 'undefined' ? window : commonjsGlobal); + + var util = { + assign: assign, + create: create, + trim: trim$1, + bind: bind, + slice: slice, + each: each, + map: map, + pluck: pluck, + isList: isList, + isFunction: isFunction$1, + isObject: isObject$1, + Global: Global + }; + + function make_assign() { + if (Object.assign) { + return Object.assign + } else { + return function shimAssign(obj, props1, props2, etc) { + var arguments$1 = arguments; + + for (var i = 1; i < arguments.length; i++) { + each(Object(arguments$1[i]), function(val, key) { + obj[key] = val; + }); + } + return obj + } + } + } + + function make_create() { + if (Object.create) { + return function create(obj, assignProps1, assignProps2, etc) { + var assignArgsList = slice(arguments, 1); + return assign.apply(this, [Object.create(obj)].concat(assignArgsList)) + } + } else { + function F() {} // eslint-disable-line no-inner-declarations + return function create(obj, assignProps1, assignProps2, etc) { + var assignArgsList = slice(arguments, 1); + F.prototype = obj; + return assign.apply(this, [new F()].concat(assignArgsList)) + } + } + } + + function make_trim() { + if (String.prototype.trim) { + return function trim(str) { + return String.prototype.trim.call(str) + } + } else { + return function trim(str) { + return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '') + } + } + } + + function bind(obj, fn) { + return function() { + return fn.apply(obj, Array.prototype.slice.call(arguments, 0)) + } + } + + function slice(arr, index) { + return Array.prototype.slice.call(arr, index || 0) + } + + function each(obj, fn) { + pluck(obj, function(val, key) { + fn(val, key); + return false + }); + } + + function map(obj, fn) { + var res = (isList(obj) ? [] : {}); + pluck(obj, function(v, k) { + res[k] = fn(v, k); + return false + }); + return res + } + + function pluck(obj, fn) { + if (isList(obj)) { + for (var i=0; i= 0; i--) { + var key = localStorage().key(i); + fn(read(key), key); + } + } + + function remove(key) { + return localStorage().removeItem(key) + } + + function clearAll() { + return localStorage().clear() + } + + // cookieStorage is useful Safari private browser mode, where localStorage + // doesn't work but cookies do. This implementation is adopted from + // https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage + + + var Global$2 = util.Global; + var trim$2 = util.trim; + + var cookieStorage = { + name: 'cookieStorage', + read: read$1, + write: write$1, + each: each$3, + remove: remove$1, + clearAll: clearAll$1, + }; + + var doc = Global$2.document; + + function read$1(key) { + if (!key || !_has(key)) { return null } + var regexpStr = "(?:^|.*;\\s*)" + + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"; + return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")) + } + + function each$3(callback) { + var cookies = doc.cookie.split(/; ?/g); + for (var i = cookies.length - 1; i >= 0; i--) { + if (!trim$2(cookies[i])) { + continue + } + var kvp = cookies[i].split('='); + var key = unescape(kvp[0]); + var val = unescape(kvp[1]); + callback(val, key); + } + } + + function write$1(key, data) { + if(!key) { return } + doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; + } + + function remove$1(key) { + if (!key || !_has(key)) { + return + } + doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; + } + + function clearAll$1() { + each$3(function(_, key) { + remove$1(key); + }); + } + + function _has(key) { + return (new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie) + } + + var defaults = defaultsPlugin; + + function defaultsPlugin() { + var defaultValues = {}; + + return { + defaults: defaults, + get: get + } + + function defaults(_, values) { + defaultValues = values; + } + + function get(super_fn, key) { + var val = super_fn(); + return (val !== undefined ? val : defaultValues[key]) + } + } + + var bind$2 = util.bind; + var each$4 = util.each; + var create$2 = util.create; + var slice$2 = util.slice; + + var events = eventsPlugin; + + function eventsPlugin() { + var pubsub = _newPubSub(); + + return { + watch: watch, + unwatch: unwatch, + once: once, + + set: set, + remove: remove, + clearAll: clearAll + } + + // new pubsub functions + function watch(_, key, listener) { + return pubsub.on(key, bind$2(this, listener)) + } + function unwatch(_, subId) { + pubsub.off(subId); + } + function once(_, key, listener) { + pubsub.once(key, bind$2(this, listener)); + } + + // overwrite function to fire when appropriate + function set(super_fn, key, val) { + var oldVal = this.get(key); + super_fn(); + pubsub.fire(key, val, oldVal); + } + function remove(super_fn, key) { + var oldVal = this.get(key); + super_fn(); + pubsub.fire(key, undefined, oldVal); + } + function clearAll(super_fn) { + var oldVals = {}; + this.each(function(val, key) { + oldVals[key] = val; + }); + super_fn(); + each$4(oldVals, function(oldVal, key) { + pubsub.fire(key, undefined, oldVal); + }); + } + } + + + function _newPubSub() { + return create$2(_pubSubBase, { + _id: 0, + _subSignals: {}, + _subCallbacks: {} + }) + } + + var _pubSubBase = { + _id: null, + _subCallbacks: null, + _subSignals: null, + on: function(signal, callback) { + if (!this._subCallbacks[signal]) { + this._subCallbacks[signal] = {}; + } + this._id += 1; + this._subCallbacks[signal][this._id] = callback; + this._subSignals[this._id] = signal; + return this._id + }, + off: function(subId) { + var signal = this._subSignals[subId]; + delete this._subCallbacks[signal][subId]; + delete this._subSignals[subId]; + }, + once: function(signal, callback) { + var subId = this.on(signal, bind$2(this, function() { + callback.apply(this, arguments); + this.off(subId); + })); + }, + fire: function(signal) { + var args = slice$2(arguments, 1); + each$4(this._subCallbacks[signal], function(callback) { + callback.apply(this, args); + }); + } + }; + + var lzString = createCommonjsModule(function (module) { + /* eslint-disable */ + // Copyright (c) 2013 Pieroxy + // This work is free. You can redistribute it and/or modify it + // under the terms of the WTFPL, Version 2 + // For more information see LICENSE.txt or http://www.wtfpl.net/ + // + // For more information, the home page: + // http://pieroxy.net/blog/pages/lz-string/testing.html + // + // LZ-based compression algorithm, version 1.4.4 + var LZString = (function() { + + // private property + var f = String.fromCharCode; + var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; + var baseReverseDic = {}; + + function getBaseValue(alphabet, character) { + if (!baseReverseDic[alphabet]) { + baseReverseDic[alphabet] = {}; + for (var i=0 ; i>> 8; + buf[i*2+1] = current_value % 256; + } + return buf; + }, + + //decompress from uint8array (UCS-2 big endian format) + decompressFromUint8Array:function (compressed) { + if (compressed===null || compressed===undefined){ + return LZString.decompress(compressed); + } else { + var buf=new Array(compressed.length/2); // 2 bytes per character + for (var i=0, TotalLen=buf.length; i> 1; + } + } else { + value = 1; + for (i=0 ; i> 1; + } + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + delete context_dictionaryToCreate[context_w]; + } else { + value = context_dictionary[context_w]; + for (i=0 ; i> 1; + } + + + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + // Add wc to the dictionary. + context_dictionary[context_wc] = context_dictSize++; + context_w = String(context_c); + } + } + + // Output the code for w. + if (context_w !== "") { + if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) { + if (context_w.charCodeAt(0)<256) { + for (i=0 ; i> 1; + } + } else { + value = 1; + for (i=0 ; i> 1; + } + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + delete context_dictionaryToCreate[context_w]; + } else { + value = context_dictionary[context_w]; + for (i=0 ; i> 1; + } + + + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + } + + // Mark the end of the stream + value = 2; + for (i=0 ; i> 1; + } + + // Flush the last char + while (true) { + context_data_val = (context_data_val << 1); + if (context_data_position == bitsPerChar-1) { + context_data.push(getCharFromInt(context_data_val)); + break; + } + else { context_data_position++; } + } + return context_data.join(''); + }, + + decompress: function (compressed) { + if (compressed == null) { return ""; } + if (compressed == "") { return null; } + return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); }); + }, + + _decompress: function (length, resetValue, getNextValue) { + var dictionary = [], + next, + enlargeIn = 4, + dictSize = 4, + numBits = 3, + entry = "", + result = [], + i, + w, + bits, resb, maxpower, power, + c, + data = {val:getNextValue(0), position:resetValue, index:1}; + + for (i = 0; i < 3; i += 1) { + dictionary[i] = i; + } + + bits = 0; + maxpower = Math.pow(2,2); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + switch (next = bits) { + case 0: + bits = 0; + maxpower = Math.pow(2,8); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + c = f(bits); + break; + case 1: + bits = 0; + maxpower = Math.pow(2,16); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + c = f(bits); + break; + case 2: + return ""; + } + dictionary[3] = c; + w = c; + result.push(c); + while (true) { + if (data.index > length) { + return ""; + } + + bits = 0; + maxpower = Math.pow(2,numBits); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + switch (c = bits) { + case 0: + bits = 0; + maxpower = Math.pow(2,8); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + + dictionary[dictSize++] = f(bits); + c = dictSize-1; + enlargeIn--; + break; + case 1: + bits = 0; + maxpower = Math.pow(2,16); + power=1; + while (power!=maxpower) { + resb = data.val & data.position; + data.position >>= 1; + if (data.position == 0) { + data.position = resetValue; + data.val = getNextValue(data.index++); + } + bits |= (resb>0 ? 1 : 0) * power; + power <<= 1; + } + dictionary[dictSize++] = f(bits); + c = dictSize-1; + enlargeIn--; + break; + case 2: + return result.join(''); + } + + if (enlargeIn == 0) { + enlargeIn = Math.pow(2, numBits); + numBits++; + } + + if (dictionary[c]) { + entry = dictionary[c]; + } else { + if (c === dictSize) { + entry = w + w.charAt(0); + } else { + return null; + } + } + result.push(entry); + + // Add w+entry[0] to the dictionary. + dictionary[dictSize++] = w + entry.charAt(0); + enlargeIn--; + + w = entry; + + if (enlargeIn == 0) { + enlargeIn = Math.pow(2, numBits); + numBits++; + } + + } + } + }; + return LZString; + })(); + + if( module != null ) { + module.exports = LZString; + } + }); + + var compression = compressionPlugin; + + function compressionPlugin() { + return { + get: get, + set: set, + } + + function get(super_fn, key) { + var val = super_fn(key); + if (!val) { return val } + var decompressed = lzString.decompress(val); + // fallback to existing values that are not compressed + return (decompressed == null) ? val : this._deserialize(decompressed) + } + + function set(super_fn, key, val) { + var compressed = lzString.compress(this._serialize(val)); + super_fn(key, compressed); + } + } + + // sort of persist on the user side + + var storages = [localStorage_1, cookieStorage]; + var plugins = [defaults, events, compression]; + + var localStore = storeEngine.createStore(storages, plugins); + + var Global$3 = util.Global; + + var sessionStorage_1 = { + name: 'sessionStorage', + read: read$2, + write: write$2, + each: each$5, + remove: remove$2, + clearAll: clearAll$2 + }; + + function sessionStorage() { + return Global$3.sessionStorage + } + + function read$2(key) { + return sessionStorage().getItem(key) + } + + function write$2(key, data) { + return sessionStorage().setItem(key, data) + } + + function each$5(fn) { + for (var i = sessionStorage().length - 1; i >= 0; i--) { + var key = sessionStorage().key(i); + fn(read$2(key), key); + } + } + + function remove$2(key) { + return sessionStorage().removeItem(key) + } + + function clearAll$2() { + return sessionStorage().clear() + } + + // session store with watch + // @1.5.0 stop using the expired plugin and deal it ourself + // import expiredPlugin from 'store/plugins/expire' + + var storages$1 = [sessionStorage_1, cookieStorage]; + var plugins$1 = [defaults, compression]; + + var sessionStore = storeEngine.createStore(storages$1, plugins$1); + + // export store interface + + // export back the raw version for development purposes + var localStore$1 = localStore; + var sessionStore$1 = sessionStore; + + // ported from jsonql-params-validator + + /** + * @param {*} args arguments to send + *@return {object} formatted payload + */ + var formatPayload = function (args) { + var obj; + + return ( + ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) + ); + }; + + /** + * Get name from the payload (ported back from jsonql-koa) + * @param {*} payload to extract from + * @return {string} name + */ + function getNameFromPayload(payload) { + return Object.keys(payload)[0] + } + + /** + * wrapper method to add the timestamp as well + * @param {string} resolverName + * @param {*} payload + * @return {object} delierable + */ + function createDeliverable(resolverName, payload) { + var obj; + + return ( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME] = [ timestamp$1() ], obj ) + } + + /** + * @param {string} resolverName name of function + * @param {array} [args=[]] from the ...args + * @param {boolean} [jsonp = false] add v1.3.0 to koa + * @return {object} formatted argument + */ + function createQuery(resolverName, args, jsonp) { + if ( args === void 0 ) args = []; + if ( jsonp === void 0 ) jsonp = false; + + if (isString(resolverName) && isArray(args)) { + var payload = formatPayload(args); + if (jsonp === true) { + return payload; + } + return createDeliverable(resolverName, payload) + } + throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) + } + + /** + * @param {string} resolverName name of function + * @param {*} payload to send + * @param {object} [condition={}] for what + * @param {boolean} [jsonp = false] add v1.3.0 to koa + * @return {object} formatted argument + */ + function createMutation(resolverName, payload, condition, jsonp) { + if ( condition === void 0 ) condition = {}; + if ( jsonp === void 0 ) jsonp = false; + + var _payload = {}; + _payload[PAYLOAD_PARAM_NAME] = payload; + _payload[CONDITION_PARAM_NAME] = condition; + if (jsonp === true) { + return _payload; + } + if (isString(resolverName)) { + return createDeliverable(resolverName, _payload) + } + throw new JsonqlValidationError("[createMutation] expect resolverName to be string!", { resolverName: resolverName, payload: payload, condition: condition }) + } + + /** + * @return {object} _cb as key with timestamp + */ + var cacheBurst = function () { return ({ _cb: timestamp$1() }); }; + + // break up from node-middleware + + // ported from http-client + + /** + * handle the return data + * @TODO how to handle the return timestamp and calculate the diff? + * @param {object} result return from server + * @return {object} strip the data part out, or if the error is presented + */ + var resultHandler = function (result) { return ( + (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result + ); }; + + // new 1.5.0 + + // this becomes the base class instead of the HttpCls + var StoreClass = function StoreClass(opts) { + this.opts = opts; + // make it a string + this.instanceKey = hashCode$1(this.opts.hostname); + // pass this store for use later + this.localStore = localStore$1; + this.sessionStore = sessionStore$1; + /* + if (this.opts.debugOn) { // reuse this to clear out the data + this.log('clear all stores') + localStore.clearAll() + sessionStore.clearAll() + + localStore.set('TEST', Date.now()) + sessionStore.set('TEST', Date.now()) + } + */ + }; + + var prototypeAccessors = { lset: { configurable: true },lget: { configurable: true },sset: { configurable: true },sget: { configurable: true } }; + // store in local storage id by the instanceKey + // values should be an object so with key so we just merge + // into the existing store without going through the keys + StoreClass.prototype.__setMethod = function __setMethod (storeType, values) { + var obj; + + var store = this[storeType]; + var data = this.__getMethod(storeType); + var skey = this.opts.storageKey; + var ikey = this.instanceKey; + store.set(skey, ( obj = {}, obj[ikey] = data ? merge({}, data, values) : values, obj )); + }; + // return the data id by the instaceKey + StoreClass.prototype.__getMethod = function __getMethod (storeType) { + var store = this[storeType]; + var data = store.get(this.opts.storageKey); + return data ? data[this.instanceKey] : false + }; + // remove from local store id by instanceKey + StoreClass.prototype.__delMethod = function __delMethod (storeType, key) { + var data = this.__getMethod(storeType); + if (data) { + var store = {}; + for (var k in data) { + if (k !== key) { + store[k] = data[k]; + } + } + this.__setMethod(storeType, store); + } + }; + // clear everything by this instanceKey + StoreClass.prototype.__clearMethod = function __clearMethod (storeKey) { + var skey = this.opts.storageKey; + var store = this[storeKey]; + var data = store.get(skey); + if (data) { + var _store = {}; + for (var k in data) { + if (k !== this.instanceKey) { + _store[k] = data[k]; + } + } + store.set(skey, _store); + } + }; + // Alias for different store + prototypeAccessors.lset.set = function (values) { + return this.__setMethod(CLS_LOCAL_STORE_NAME, values) + }; + + prototypeAccessors.lget.get = function () { + return this.__getMethod(CLS_LOCAL_STORE_NAME) + }; + + StoreClass.prototype.ldel = function ldel (key) { + return this.__delMethod(CLS_LOCAL_STORE_NAME, key) + }; + + StoreClass.prototype.lclear = function lclear () { + return this.__clearMethod(CLS_LOCAL_STORE_NAME) + }; + + // store in session store id by the instanceKey + prototypeAccessors.sset.set = function (values) { + // this.log('--- sset ---', values) + return this.__setMethod(CLS_SESS_STORE_NAME, values) + }; + + prototypeAccessors.sget.get = function () { + return this.__getMethod(CLS_SESS_STORE_NAME) + }; + + StoreClass.prototype.sdel = function sdel (key) { + return this.__delMethod(CLS_SESS_STORE_NAME, key) + }; + + StoreClass.prototype.sclear = function sclear () { + return this.__clearMethod(CLS_SESS_STORE_NAME) + }; + + Object.defineProperties( StoreClass.prototype, prototypeAccessors ); + + // base HttpClass + + // extract the one we need + var POST = API_REQUEST_METHODS[0]; + var PUT = API_REQUEST_METHODS[1]; + + var HttpClass = /*@__PURE__*/(function (StoreClass) { + function HttpClass(opts) { + StoreClass.call(this, opts); + // change the way how we init Fly + // flyio now become external depedencies and it makes it easier to switch + // @BUG should we run test to check if we have the windows object? + // this.log(opts) + // this.fly = opts.Fly ? new opts.Fly() : new Fly() + // to a different environment like WeChat mini app + + this.extraHeader = {}; + // @1.2.1 for adding query to the call on the fly + this.extraParams = {}; + // this.log('start up opts', opts); + this.reqInterceptor(); + this.resInterceptor(); + } + + if ( StoreClass ) HttpClass.__proto__ = StoreClass; + HttpClass.prototype = Object.create( StoreClass && StoreClass.prototype ); + HttpClass.prototype.constructor = HttpClass; + + var prototypeAccessors = { headers: { configurable: true } }; + + // set headers for that one call + prototypeAccessors.headers.set = function (header) { + this.extraHeader = header; + }; + + /** + * Create the reusage request method + * @param {object} payload jsonql payload + * @param {object} options extra options add the request + * @param {object} headers extra headers add to the call + * @return {object} the fly request instance + */ + HttpClass.prototype.request = function request (payload, options, headers) { + var obj; + + if ( options === void 0 ) options = {}; + if ( headers === void 0 ) headers = {}; + this.headers = headers; + var params = merge({}, cacheBurst(), this.extraParams); + // @TODO need to add a jsonp url and payload + if (this.opts.enableJsonp) { + var resolverName = getNameFromPayload(payload); + params = merge({}, params, ( obj = {}, obj[JSONP_CALLBACK_NAME] = resolverName, obj )); + payload = payload[resolverName]; + } + // double up the url param and see what happen @TODO remove later + var reqParams = merge({}, { method: POST, params: params }, options); + this.log('request params', reqParams, this.jsonqlEndpoint); + + return this.fly.request(this.jsonqlEndpoint, payload, reqParams) + }; + + /** + * This will replace the create baseRequest method + * + */ + HttpClass.prototype.reqInterceptor = function reqInterceptor () { + var this$1 = this; + + this.fly.interceptors.request.use( + function (req) { + var headers = this$1.getHeaders(); + this$1.log('request interceptor call', headers); + + for (var key in headers) { + req.headers[key] = headers[key]; + } + return req; + } + ); + }; + + // @TODO + HttpClass.prototype.processJsonp = function processJsonp (result) { + return resultHandler(result) + }; + + /** + * This will be replacement of the first then call + * + */ + HttpClass.prototype.resInterceptor = function resInterceptor () { + var this$1 = this; + + var self = this; + var jsonp = self.opts.enableJsonp; + this.fly.interceptors.response.use( + function (res) { + this$1.log('response interceptor call', res); + self.cleanUp(); + // now more processing here + // there is a problem if we throw the result.error here + // the original data is lost, so we need to do what we did before + // deal with that error in the first then instead + var result = isString$1(res.data) ? JSON.parse(res.data) : res.data; + if (jsonp) { + return self.processJsonp(result) + } + return resultHandler(result) + }, + // this get call when it's not 200 + function (err) { + self.cleanUp(); + this$1.log(LOG_ERROR_SWITCH, err); + throw new JsonqlServerError('Server side error', err) + } + ); + }; + + /** + * Get the headers inject into the call + * @return {object} headers + */ + HttpClass.prototype.getHeaders = function getHeaders () { + if (this.opts.enableAuth) { + return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader) + } + return merge({}, DEFAULT_HEADER, this.extraHeader) + }; + + /** + * Post http call operation to clean up things we need + */ + HttpClass.prototype.cleanUp = function cleanUp () { + this.extraHeader = {}; + this.extraParams = {}; + }; + + /** + * GET for contract only + * @return {promise} resolve the contract + */ + HttpClass.prototype.getRemoteContract = function getRemoteContract () { + var this$1 = this; + + if (this.opts.showContractDesc) { + this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM); + } + return this.request({}, {method: 'GET'}, this.contractHeader) + .then(clientErrorsHandler) + .then(function (result) { + this$1.log('get contract result', result); + // when refresh the window the result is different! + // @TODO need to check the Koa side about why is that + // also it should set a flag if we want the description or not + if (result.cache && result.contract) { + return result.contract; + } + // just the normal result + return result + }) + .catch(function (err) { + this$1.log(LOG_ERROR_SWITCH, 'getRemoteContract err', err); + throw new JsonqlServerError('getRemoteContract', err) + }) + }; + + /** + * POST to server - query + * @param {object} name of the resolver + * @param {array} args arguments + * @return {object} promise resolve to the resolver return + */ + HttpClass.prototype.query = function query (name, args) { + if ( args === void 0 ) args = []; + + return this.request(createQuery(name, args)) + .then(clientErrorsHandler) + }; + + /** + * PUT to server - mutation + * @param {string} name of resolver + * @param {object} payload what it said + * @param {object} conditions what it said + * @return {object} promise resolve to the resolver return + */ + HttpClass.prototype.mutation = function mutation (name, payload, conditions) { + if ( payload === void 0 ) payload = {}; + if ( conditions === void 0 ) conditions = {}; + + return this.request(createMutation(name, payload, conditions), {method: PUT}) + .then(clientErrorsHandler) + }; + + Object.defineProperties( HttpClass.prototype, prototypeAccessors ); + + return HttpClass; + }(StoreClass)); + + // all the contract related methods will be here + + // export + var ContractClass = /*@__PURE__*/(function (HttpClass) { + function ContractClass(opts) { + HttpClass.call(this, opts); + } + + if ( HttpClass ) ContractClass.__proto__ = HttpClass; + ContractClass.prototype = Object.create( HttpClass && HttpClass.prototype ); + ContractClass.prototype.constructor = ContractClass; + + var prototypeAccessors = { contractHeader: { configurable: true } }; + + /** + * return the contract public api + * @return {object} contract + */ + ContractClass.prototype.getContract = function getContract () { + var contract = this.readContract(); + this.log('getContract first call', contract); + return contract ? Promise.resolve(contract) + : this.getRemoteContract().then(this.storeContract.bind(this)) + }; + + /** + * We are changing the way how to auth to get the contract.json + * Instead of in the url, we will be putting that key value in the header + * @return {object} header + */ + prototypeAccessors.contractHeader.get = function () { + var base = {}; + if (this.opts.contractKey !== false) { + base[this.opts.contractKeyName] = this.opts.contractKey; + } + return base; + }; + + /** + * Save the contract to local store + * @param {object} contract to save + * @return {object|boolean} false when its not a contract or contract on OK + */ + ContractClass.prototype.storeContract = function storeContract (contract) { + var obj; + + // first need to check if the contract is a contract + if (!isContract(contract)) { + throw new JsonqlValidationError("Contract is malformed!") + } + this.lset = ( obj = {}, obj[CLS_CONTRACT_NAME] = contract, obj ); + // return it + this.log('storeContract return result', contract); + return contract; + }; + + /** + * return the contract from options or localStore + * @return {object|boolean} false on not found + */ + ContractClass.prototype.readContract = function readContract () { + var contract = isContract(this.opts.contract); + if (contract !== false) { + return contract; + } + var data = this.lget; + if (data) { + return data[CLS_CONTRACT_NAME] + } + return false; + }; + + Object.defineProperties( ContractClass.prototype, prototypeAccessors ); + + return ContractClass; + }(HttpClass)); + + // this is the new auth class that integrate with the jsonql-jwt + // export + var AuthClass = /*@__PURE__*/(function (ContractClass) { + function AuthClass(opts) { + ContractClass.call(this, opts); + if (opts.enableAuth) { + this.setDecoder = jwtDecode; + } + } + + if ( ContractClass ) AuthClass.__proto__ = ContractClass; + AuthClass.prototype = Object.create( ContractClass && ContractClass.prototype ); + AuthClass.prototype.constructor = AuthClass; + + var prototypeAccessors = { profileIndex: { configurable: true },setDecoder: { configurable: true },saveProfile: { configurable: true },readProfile: { configurable: true },jsonqlToken: { configurable: true },jsonqlUserdata: { configurable: true } }; + + /** + * for overwrite + * @param {string} token stored token + * @return {string} token + */ + AuthClass.prototype.decoder = function decoder (token) { + return token; + }; + + /** + * set the profile index + * @param {number} idx + */ + prototypeAccessors.profileIndex.set = function (idx) { + var obj; + + var key = CLS_PROFILE_IDX; + if (isNumber$1(idx)) { + this[key] = idx; + if (this.opts.persistToken) { + this.lset = ( obj = {}, obj[key] = idx, obj ); + } + return; + } + throw new JsonqlValidationError('profileIndex', ("Expect idx to be number but got " + (typeof idx))) + }; + + /** + * get the profile index + * @return {number} idx + */ + prototypeAccessors.profileIndex.get = function () { + var key = CLS_PROFILE_IDX; + if (this.opts.persistToken) { + var data = this.lget; + if (data[key]) { + return data[key] + } + } + return this[key] ? this[key] : ZERO_IDX + }; + + /** + * Return the token from session store + * @param {number} [idx=false] profile index + * @return {string} token + */ + AuthClass.prototype.rawAuthToken = function rawAuthToken (idx) { + if ( idx === void 0 ) idx = false; + + if (idx !== false) { + this.profileIndex = idx; + } + // this should return from the base + return this.jsonqlToken; // see base-cls + }; + + /** + * Setter to add a decoder when retrieve user token + * @param {function} d a decoder + */ + prototypeAccessors.setDecoder.set = function (d) { + if (typeof d === 'function') { + this.decoder = d; + } + }; + + /** + * getter to return the session or local store set method + * @param {*} data to save + * @return {object} set method + */ + prototypeAccessors.saveProfile.set = function (data) { + if (this.opts.persistToken) { + // this.log('--- saveProfile lset ---', data) + this.lset = data; + } else { + // this.log('--- saveProfile sset ---', data) + this.sset = data; + } + }; + + /** + * getter to return the session or local store get method + * @return {object} get method + */ + prototypeAccessors.readProfile.get = function () { + return this.opts.persistToken ? this.lget : this.sget + }; + + // these were in the base class before but it should be here + /** + * save token + * @param {string} token to store + * @return {string|boolean} false on failed + */ + prototypeAccessors.jsonqlToken.set = function (token) { + var obj; + + var data = this.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + // @TODO also have to make sure the token is not already existed! + var tokens = (data && data[key]) ? data[key] : []; + tokens.push(token); + this.saveProfile = ( obj = {}, obj[key] = tokens, obj ); + // store the userdata + this.jsonqlUserdata = this.decoder(token); + }; + + /** + * Jsonql token getter + * 1.5.1 each token associate with the same profileIndex + * @return {string|boolean} false when failed + */ + prototypeAccessors.jsonqlToken.get = function () { + var data = this.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + if (data && data[key]) { + this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex]); + return data[key][this.profileIndex] + } + return false + }; + + /** + * this one will use the sessionStore + * basically we hook this onto the token store and decode it to store here + * we only store one decoded user data at a time, but the token can be multiple + */ + prototypeAccessors.jsonqlUserdata.set = function (userdata) { + var obj; + + this.sset = ( obj = {}, obj[USERDATA_TABLE] = userdata, obj ); + }; + + /** + * this one store in the session store + * get login userdata decoded jwt + * 1.5.1 each userdata associate with the same profileIndex + * @return {object|null} + */ + prototypeAccessors.jsonqlUserdata.get = function () { + var data = this.sget; + return data ? data[USERDATA_TABLE] : false + }; + + /** + * Construct the auth header + * @return {object} header + */ + AuthClass.prototype.getAuthHeader = function getAuthHeader () { + var obj; + + var token = this.jsonqlToken; // only call the getter to get the default one + return token ? ( obj = {}, obj[this.opts.AUTH_HEADER] = (BEARER + " " + token), obj ) : {}; + }; + + /** + * return all the stored token and decode it + * @param {number} [idx=false] profile index + * @return {array|boolean|string} false not found or array + */ + AuthClass.prototype.getProfiles = function getProfiles (idx) { + if ( idx === void 0 ) idx = false; + + var self = this; // just in case the scope problem + var data = self.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + if (data && data[key]) { + if (idx !== false && isNumber$1(idx)) { + return data[key][idx] || false + } + return data[key].map(self.decoder.bind(self)) + } + return false + }; + + /** + * call after the login + * @param {string} token return from server + * @return {object} decoded token to userdata object + */ + AuthClass.prototype.postLoginAction = function postLoginAction (token) { + this.jsonqlToken = token; + return token + }; + + /** + * call after the logout @TODO + */ + AuthClass.prototype.postLogoutAction = function postLogoutAction () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + console.info("postLogoutAction", args); + }; + + Object.defineProperties( AuthClass.prototype, prototypeAccessors ); + + return AuthClass; + }(ContractClass)); + + // this the core of the internal storage management + + // This class will only focus on the storage system + var JsonqlBaseClient = /*@__PURE__*/(function (AuthCls) { + function JsonqlBaseClient(fly, opts) { + // change at 1.4.10 pass it directly without init it + this.fly = fly; + AuthCls.call(this, opts); + } + + if ( AuthCls ) JsonqlBaseClient.__proto__ = AuthCls; + JsonqlBaseClient.prototype = Object.create( AuthCls && AuthCls.prototype ); + JsonqlBaseClient.prototype.constructor = JsonqlBaseClient; + + var prototypeAccessors = { jsonqlEndpoint: { configurable: true } }; + + /** + * construct the end point + * @return {string} the end point to call + */ + prototypeAccessors.jsonqlEndpoint.get = function () { + var baseUrl = this.opts.hostname || ''; + return [baseUrl, this.opts.jsonqlPath].join('/') + }; + + /** + * simple log + */ + JsonqlBaseClient.prototype.log = function log () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (this.opts.debugOn === true) { + var fns = ['info', 'error']; + var idx = (args[0] === LOG_ERROR_SWITCH) ? 1 : 0; + Reflect.apply(console[fns[idx]], console, args.splice(0, idx)); + } + }; + + Object.defineProperties( JsonqlBaseClient.prototype, prototypeAccessors ); + + return JsonqlBaseClient; + }(AuthClass)); + + // export interface + + /** + * using just the map reduce to chain multiple functions together + * @param {function} mainFn the init function + * @param {array} moreFns as many as you want to take the last value and return a new one + * @return {function} accept value for the mainFn + */ + var chainFns = function (mainFn) { + var moreFns = [], len = arguments.length - 1; + while ( len-- > 0 ) moreFns[ len ] = arguments[ len + 1 ]; + + return ( + function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return ( + moreFns.reduce(function (value, nextFn) { return ( + // change here to check if the return value is array then we spread it + Reflect.apply(nextFn, null, toArray(value)) + ); }, Reflect.apply(mainFn, null, args)) + ); + } + ); + }; + + /** + * check if the object has name property + * @param {object} obj the object to check + * @param {string} name the prop name + * @return {*} the value or undefined + */ + function objHasProp(obj, name) { + var prop = Object.getOwnPropertyDescriptor(obj, name); + return prop !== undefined && prop.value ? prop.value : prop; + } + + /** + * 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 {string} name the name of the object to get inject also for checking + * @param {object} data to inject into the function static interface + * @param {boolean} [overwrite=false] if we want to overwrite the existing data + * @return {function} added property resolver + */ + function injectToFn(resolver, name, data, overwrite) { + if ( overwrite === void 0 ) overwrite = false; + + var check = objHasProp(resolver, name); + if (overwrite === false && check !== undefined) { + // console.info(`NOT INJECTED`) + return resolver; + } + /* this will throw error! + if (overwrite === true && check !== undefined) { + delete resolver[name] // delete this property + } + */ + // console.info(`INJECTED`) + Object.defineProperty(resolver, name, { + value: data, + writable: overwrite // if its set to true then we should able to overwrite it + }); + + return resolver; + } + + // breaking out the inner methods generator in here + + /** + * generate authorisation specific methods + * @param {object} jsonqlInstance instance of this + * @param {string} name of method + * @param {object} opts configuration + * @param {object} contract to match + * @return {function} for use + */ + var authMethodGenerator = function (jsonqlInstance, name, opts, contract) { + return function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var params = contract.auth[name].params; + var values = params.map(function (p, i) { return args[i]; }); + var header = args[params.length] || {}; + return validateAsync$1(args, params) + .then(function () { return jsonqlInstance + .query + .apply(jsonqlInstance, [name, values, header]); } + ) + .catch(finalCatch) + } + }; + + /** + * Break up the different type each - create query methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createQueryMethods = function (obj, jsonqlInstance, ee, config, contract) { + var query = {}; + var loop = function ( queryFn ) { + // to keep it clean we use a param to id the auth method + // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; + // generate the query method + query = injectToFn(query, queryFn, function queryFnHandler() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var params = contract.query[queryFn].params; + var _args = params.map(function (param, i) { return args[i]; }); + // debug('query', queryFn, _params); + // @TODO this need to change to a different way to add an extra header + var header = {}; + // @TODO validate against the type + return validateAsync$1(_args, params) + .then(function () { return jsonqlInstance + .query + .apply(jsonqlInstance, [queryFn, _args, header]); } + ) + .catch(finalCatch) + }); + }; + + for (var queryFn in contract.query) loop( queryFn ); + obj.query = query; + // create an alias to the helloWorld method + obj.helloWorld = query.helloWorld; + return [ obj, jsonqlInstance, ee, config, contract ] + }; + + /** + * create mutation methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createMutationMethods = function (obj, jsonqlInstance, ee, config, contract) { + var mutation = {}; + // process the mutation, the reason the mutation has a fixed number of parameters + // there is only the payload, and conditions parameters + // plus a header at the end + var loop = function ( mutationFn ) { + mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header) { + if ( header === void 0 ) header = {}; + + var args = [payload, conditions]; + var params = contract.mutation[mutationFn].params; + return validateAsync$1(args, params) + .then(function () { return jsonqlInstance + .mutation + .apply(jsonqlInstance, [mutationFn, payload, conditions, header]); } + ) + .catch(finalCatch) + }); + }; + + for (var mutationFn in contract.mutation) loop( mutationFn ); + obj.mutation = mutation; + return [ obj, jsonqlInstance, ee, config, contract ] + }; + + /** + * create auth methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createAuthMethods = function (obj, jsonqlInstance, ee, config, contract) { + if (config.enableAuth && contract.auth) { + var auth = {}; // v1.3.1 add back the auth prop name in contract + var loginHandlerName = config.loginHandlerName; + var logoutHandlerName = config.logoutHandlerName; + if (contract.auth[loginHandlerName]) { + // changing to the name the config specify + auth[loginHandlerName] = function loginHandlerFn() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract); + return fn.apply(null, args) + .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance)) + .then(function (token) { + ee.$trigger(LOGIN_NAME, token); + return token; + }) + }; + } + // @TODO allow to logout one particular profile or all of them + if (contract.auth[logoutHandlerName]) { + auth[logoutHandlerName] = function logoutHandlerFn() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract); + return fn.apply(null, args) + .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance)) + .then(function (r) { + ee.$trigger(LOGOUT_NAME, r); + return r; + }) + }; + } else { + auth[logoutHandlerName] = function logoutHandlerFn() { + jsonqlInstance.postLogoutAction(KEY_WORD); + ee.$trigger(LOGOUT_NAME, KEY_WORD); + }; + } + obj.auth = auth; + } + + return obj; + }; + + /** + * Here just generate the methods calls + * @param {object} jsonqlInstance what it said + * @param {object} ee event emitter + * @param {object} config configuration + * @param {object} contract the map + * @return {object} with mapped methods + */ + function methodsGenerator(jsonqlInstance, ee, config, contract) { + var obj = {}; + var executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods); + return executor(obj, jsonqlInstance, ee, config, contract) + } + + // Generate the resolver for developer to use + + /** + * @param {object} jsonqlInstance jsonql class instance + * @param {object} config options + * @param {object} contract the contract + * @param {object} ee eventEmitter + * @return {object} constructed functions call + */ + var generator = function (jsonqlInstance, config, contract, ee) { + // V1.3.0 - now everything wrap inside this method + var client = methodsGenerator(jsonqlInstance, ee, config, contract); + // create the rest of the methods + if (config.enableAuth) { + /** + * new method to allow retrieve the current login user data + * @TODO allow to pass an id to switch to different userdata + * @return {*} userdata + */ + client.userdata = function () { return jsonqlInstance.jsonqlUserdata; }; + // allow getting the token for valdiate agains the socket + // if it's not require auth there is no point of calling getToken + client.getToken = function (idx) { + if ( idx === void 0 ) idx = false; + + return jsonqlInstance.rawAuthToken(idx); + }; + // switch profile or read back what is the currenct index + client.profileIndex = function (idx) { + if ( idx === void 0 ) idx = false; + + if (idx === false) { + return jsonqlInstance.profileIndex + } + jsonqlInstance.profileIndex = idx; + }; + // new in 1.5.1 to return different profiles + client.getProfiles = function (idx) { + if ( idx === void 0 ) idx = false; + + return jsonqlInstance.getProfiles(idx); + }; + } + // this will pass to the ws-client if needed + // client.eventEmitter = ee; + // this will require a param + if (config.exposeContract) { + // 1.4.0 change from the get (raw) to the getContract cache and raw version + client.getContract = function () { return jsonqlInstance.getContract(); }; + } + // allow developer to access the store api + if (config.exposeStore) { + // @TODO in 1.5.2 + client.tmpSave = function (data) {}; + client.tmpGet = function (key) { + }; + client.tmpDel = function (key) { + }; + + client.persistSave = function (data) {}; + client.persistGet = function (key) { + }; + client.persistDel = function (key) { + }; + } + // this is for the ws to use later - but this could be dangerous because it's expose the internal + client.eventEmitter = ee; + client.version = '1.5.1'; + // use this method then we can hook into the debugOn at the same time + client.log = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return Reflect.apply(jsonqlInstance.log, jsonqlInstance, ['[DEV DEBUG]'].concat(args)); + }; + // output + return client; + }; + + // all the client configuration options here + var constProps = { + contract: false, + MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong? + CONTENT_TYPE: CONTENT_TYPE, + BEARER: BEARER, + AUTH_HEADER: AUTH_HEADER + }; + + // grab the localhost name and put into the hostname as default + var getHostName = function () { + try { + return [window.location.protocol, window.location.host].join('//') + } catch(e) { + return null + } + }; + + var appProps$1 = { + + hostname: createConfig$1(getHostName(), [STRING_TYPE]), // required the hostname + jsonqlPath: createConfig$1(JSONQL_PATH, [STRING_TYPE]), // The path on the server + + loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), + logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), + // add to koa v1.3.0 - this might remove in the future + enableJsonp: createConfig$1(false, [BOOLEAN_TYPE]), + enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), + // enable useJwt by default @TODO replace with something else and remove them later + useJwt: createConfig$1(true, [BOOLEAN_TYPE]), + // when true then store infinity or pass a time in seconds then we check against + // the token date of creation + persistToken: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE]), + // the header + // v1.2.0 we are using this option during the dev + // so it won't save anything to the localstorage and fetch a new contract + // whenever the browser reload + useLocalstorage: createConfig$1(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage + storageKey: createConfig$1(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage + authKey: createConfig$1(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage + contractExpired: createConfig$1(0, [NUMBER_TYPE]),// -1 always fetch contract, + // 0 never expired, + // > 0 then compare the timestamp with the current one to see if we need to get contract again + // useful during development + keepContract: createConfig$1(true, [BOOLEAN_TYPE]), + exposeContract: createConfig$1(false, [BOOLEAN_TYPE]), + exposeStore: createConfig$1(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn + // @1.2.1 new option for the contract-console to fetch the contract with description + showContractDesc: createConfig$1(false, [BOOLEAN_TYPE]), + contractKey: createConfig$1(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this + contractKeyName: createConfig$1(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs + enableTimeout: createConfig$1(false, [BOOLEAN_TYPE]), // @TODO + timeout: createConfig$1(5000, [NUMBER_TYPE]), // 5 seconds + returnInstance: createConfig$1(false, [BOOLEAN_TYPE]), + allowReturnRawToken: createConfig$1(false, [BOOLEAN_TYPE]), + debugOn: createConfig$1(false, [BOOLEAN_TYPE]) + }; + + // we must ensure the user passing the correct options + + function checkOptionsAsync$1(config) { + var contract = config.contract; + return checkConfigAsync$1(config, appProps$1, constProps) + .then(function (opts) { + opts.contract = contract; + return opts; + }) + } + + // export interface + /** + * 1.5.0 overload the orginal functions to pass over the check + */ + function checkOptionsAsync$2(config) { + return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsync$1(config) + } + + // this is new for the flyio and normalize the name from now on + + /** + * Main interface for jsonql fetch api + * @param {object} ee EventEmitter + * @param {object} config + * @param {object} fly this is really pain in the backside ... long story + * @return {object} jsonql client + */ + function jsonqlAsync(ee, config, fly) { + if ( config === void 0 ) config = {}; + + return checkOptionsAsync$2(config) + .then(function (opts) { return ( + { + baseClient: new JsonqlBaseClient(fly, opts), + opts: opts + } + ); }) + .then( function (ref) { + var baseClient = ref.baseClient; + var opts = ref.opts; + + return ( + getContractFromConfig(baseClient, opts.contract) + .then(function (contract) { return generator(baseClient, opts, contract, ee); }) + ); + } + ) + } + + var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); + var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); + + // making all the functionality on it's own + // import { WatchClass } from './watch' + + var SuspendClass = function SuspendClass() { + // suspend, release and queue + this.__suspend__ = null; + this.queueStore = new Set(); + /* + this.watch('suspend', function(value, prop, oldValue) { + this.logger(`${prop} set from ${oldValue} to ${value}`) + // it means it set the suspend = true then release it + if (oldValue === true && value === false) { + // we want this happen after the return happens + setTimeout(() => { + this.release() + }, 1) + } + return value; // we need to return the value to store it + }) + */ + }; + + var prototypeAccessors$1 = { $suspend: { configurable: true },$queues: { configurable: true } }; + + /** + * setter to set the suspend and check if it's boolean value + * @param {boolean} value to trigger + */ + prototypeAccessors$1.$suspend.set = function (value) { + var this$1 = this; + + if (typeof value === 'boolean') { + var lastValue = this.__suspend__; + this.__suspend__ = value; + this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); + if (lastValue === true && value === false) { + setTimeout(function () { + this$1.release(); + }, 1); + } + } else { + throw new Error("$suspend only accept Boolean value!") + } + }; + + /** + * queuing call up when it's in suspend mode + * @param {any} value + * @return {Boolean} true when added or false when it's not + */ + SuspendClass.prototype.$queue = function $queue () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (this.__suspend__ === true) { + this.logger('($queue)', 'added to $queue', args); + // there shouldn't be any duplicate ... + this.queueStore.add(args); + } + return this.__suspend__; + }; + + /** + * a getter to get all the store queue + * @return {array} Set turn into Array before return + */ + prototypeAccessors$1.$queues.get = function () { + var size = this.queueStore.size; + this.logger('($queues)', ("size: " + size)); + if (size > 0) { + return Array.from(this.queueStore) + } + return [] + }; + + /** + * Release the queue + * @return {int} size if any + */ + SuspendClass.prototype.release = function release () { + var this$1 = this; + + var size = this.queueStore.size; + this.logger('(release)', ("Release was called " + size)); + if (size > 0) { + var queue = Array.from(this.queueStore); + this.queueStore.clear(); + this.logger('queue', queue); + queue.forEach(function (args) { + this$1.logger(args); + Reflect.apply(this$1.$trigger, this$1, args); + }); + this.logger(("Release size " + (this.queueStore.size))); + } + }; + + Object.defineProperties( SuspendClass.prototype, prototypeAccessors$1 ); + + // break up the main file because its getting way too long + + var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { + function NbEventServiceBase(config) { + if ( config === void 0 ) config = {}; + + SuspendClass.call(this); + if (config.logger && typeof config.logger === 'function') { + this.logger = config.logger; + } + this.keep = config.keep; + // for the $done setter + this.result = config.keep ? [] : null; + // we need to init the store first otherwise it could be a lot of checking later + this.normalStore = new Map(); + this.lazyStore = new Map(); + } + + if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; + NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); + NbEventServiceBase.prototype.constructor = NbEventServiceBase; + + var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; + + /** + * validate the event name(s) + * @param {string[]} evt event name + * @return {boolean} true when OK + */ + NbEventServiceBase.prototype.validateEvt = function validateEvt () { + var this$1 = this; + var evt = [], len = arguments.length; + while ( len-- ) evt[ len ] = arguments[ len ]; + + evt.forEach(function (e) { + if (typeof e !== 'string') { + this$1.logger('(validateEvt)', e); + throw new Error("event name must be string type!") + } + }); + return true; + }; + + /** + * Simple quick check on the two main parameters + * @param {string} evt event name + * @param {function} callback function to call + * @return {boolean} true when OK + */ + NbEventServiceBase.prototype.validate = function validate (evt, callback) { + if (this.validateEvt(evt)) { + if (typeof callback === 'function') { + return true; + } + } + throw new Error("callback required to be function type!") + }; + + /** + * Check if this type is correct or not added in V1.5.0 + * @param {string} type for checking + * @return {boolean} true on OK + */ + NbEventServiceBase.prototype.validateType = function validateType (type) { + var types = ['on', 'only', 'once', 'onlyOnce']; + return !!types.filter(function (t) { return type === t; }).length; + }; + + /** + * Run the callback + * @param {function} callback function to execute + * @param {array} payload for callback + * @param {object} ctx context or null + * @return {void} the result store in $done + */ + NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { + this.logger('(run)', callback, payload, ctx); + this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); + }; + + /** + * Take the content out and remove it from store id by the name + * @param {string} evt event name + * @param {string} [storeName = lazyStore] name of store + * @return {object|boolean} content or false on not found + */ + NbEventServiceBase.prototype.takeFromStore = function takeFromStore (evt, storeName) { + if ( storeName === void 0 ) storeName = 'lazyStore'; + + var store = this[storeName]; // it could be empty at this point + if (store) { + this.logger('(takeFromStore)', storeName, store); + if (store.has(evt)) { + var content = store.get(evt); + this.logger('(takeFromStore)', ("has " + evt), content); + store.delete(evt); + return content; + } + return false; + } + throw new Error((storeName + " is not supported!")) + }; + + /** + * The add to store step is similar so make it generic for resuse + * @param {object} store which store to use + * @param {string} evt event name + * @param {spread} args because the lazy store and normal store store different things + * @return {array} store and the size of the store + */ + NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { + var args = [], len = arguments.length - 2; + while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; + + var fnSet; + if (store.has(evt)) { + this.logger('(addToStore)', (evt + " existed")); + fnSet = store.get(evt); + } else { + this.logger('(addToStore)', ("create new Set for " + evt)); + // this is new + fnSet = new Set(); + } + // lazy only store 2 items - this is not the case in V1.6.0 anymore + // we need to check the first parameter is string or not + if (args.length > 2) { + if (Array.isArray(args[0])) { // lazy store + // check if this type of this event already register in the lazy store + var t = args[2]; + if (!this.checkTypeInLazyStore(evt, t)) { + fnSet.add(args); + } + } else { + if (!this.checkContentExist(args, fnSet)) { + this.logger('(addToStore)', "insert new", args); + fnSet.add(args); + } + } + } else { // add straight to lazy store + fnSet.add(args); + } + store.set(evt, fnSet); + return [store, fnSet.size] + }; + + /** + * @param {array} args for compare + * @param {object} fnSet A Set to search from + * @return {boolean} true on exist + */ + NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { + var list = Array.from(fnSet); + return !!list.filter(function (l) { + var hash = l[0]; + if (hash === args[0]) { + return true; + } + return false; + }).length; + }; + + /** + * get the existing type to make sure no mix type add to the same store + * @param {string} evtName event name + * @param {string} type the type to check + * @return {boolean} true you can add, false then you can't add this type + */ + NbEventServiceBase.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { + this.validateEvt(evtName, type); + var all = this.$get(evtName, true); + if (all === false) { + // pristine it means you can add + return true; + } + // it should only have ONE type in ONE event store + return !all.filter(function (list) { + var t = list[3]; + return type !== t; + }).length; + }; + + /** + * This is checking just the lazy store because the structure is different + * therefore we need to use a new method to check it + */ + NbEventServiceBase.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { + this.validateEvt(evtName, type); + var store = this.lazyStore.get(evtName); + this.logger('(checkTypeInLazyStore)', store); + if (store) { + return !!Array + .from(store) + .filter(function (l) { + var t = l[2]; + return t !== type; + }).length + } + return false; + }; + + /** + * wrapper to re-use the addToStore, + * V1.3.0 add extra check to see if this type can add to this evt + * @param {string} evt event name + * @param {string} type on or once + * @param {function} callback function + * @param {object} context the context the function execute in or null + * @return {number} size of the store + */ + NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { + if ( context === void 0 ) context = null; + + this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); + // @TODO we need to check the existing store for the type first! + if (this.checkTypeInStore(evt, type)) { + this.logger('(addToNormalStore)', (type + " can add to " + evt + " normal store")); + var key = this.hashFnToKey(callback); + var args = [this.normalStore, evt, key, callback, context, type]; + var ref = Reflect.apply(this.addToStore, this, args); + var _store = ref[0]; + var size = ref[1]; + this.normalStore = _store; + return size; + } + return false; + }; + + /** + * Add to lazy store this get calls when the callback is not register yet + * so we only get a payload object or even nothing + * @param {string} evt event name + * @param {array} payload of arguments or empty if there is none + * @param {object} [context=null] the context the callback execute in + * @param {string} [type=false] register a type so no other type can add to this evt + * @return {number} size of the store + */ + NbEventServiceBase.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { + if ( payload === void 0 ) payload = []; + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = false; + + // this is add in V1.6.0 + // when there is type then we will need to check if this already added in lazy store + // and no other type can add to this lazy store + var args = [this.lazyStore, evt, this.toArray(payload), context]; + if (type) { + args.push(type); + } + var ref = Reflect.apply(this.addToStore, this, args); + var _store = ref[0]; + var size = ref[1]; + this.lazyStore = _store; + return size; + }; + + /** + * make sure we store the argument correctly + * @param {*} arg could be array + * @return {array} make sured + */ + NbEventServiceBase.prototype.toArray = function toArray (arg) { + return Array.isArray(arg) ? arg : [arg]; + }; + + /** + * setter to store the Set in private + * @param {object} obj a Set + */ + prototypeAccessors.normalStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); + }; + + /** + * @return {object} Set object + */ + prototypeAccessors.normalStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) + }; + + /** + * setter to store the Set in lazy store + * @param {object} obj a Set + */ + prototypeAccessors.lazyStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); + }; + + /** + * @return {object} the lazy store Set + */ + prototypeAccessors.lazyStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) + }; + + /** + * generate a hashKey to identify the function call + * The build-in store some how could store the same values! + * @param {function} fn the converted to string function + * @return {string} hashKey + */ + NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { + return hashCode(fn.toString()) + ''; + }; + + Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); + + return NbEventServiceBase; + }(SuspendClass)); + + // The top level + // export + var EventService = /*@__PURE__*/(function (NbStoreService) { + function EventService(config) { + if ( config === void 0 ) config = {}; + + NbStoreService.call(this, config); + } + + if ( NbStoreService ) EventService.__proto__ = NbStoreService; + EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); + EventService.prototype.constructor = EventService; + + var prototypeAccessors = { $done: { configurable: true } }; + + /** + * logger function for overwrite + */ + EventService.prototype.logger = function logger () {}; + + ////////////////////////// + // PUBLIC METHODS // + ////////////////////////// + + /** + * Register your evt handler, note we don't check the type here, + * we expect you to be sensible and know what you are doing. + * @param {string} evt name of event + * @param {function} callback bind method --> if it's array or not + * @param {object} [context=null] to execute this call in + * @return {number} the size of the store + */ + EventService.prototype.$on = function $on (evt , callback , context) { + var this$1 = this; + if ( context === void 0 ) context = null; + + var type = 'on'; + this.validate(evt, callback); + // first need to check if this evt is in lazy store + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register first then call later + if (lazyStoreContent === false) { + this.logger('($on)', (evt + " callback is not in lazy store")); + // @TODO we need to check if there was other listener to this + // event and are they the same type then we could solve that + // register the different type to the same event name + + return this.addToNormalStore(evt, type, callback, context) + } + this.logger('($on)', (evt + " found in lazy store")); + // this is when they call $trigger before register this callback + var size = 0; + lazyStoreContent.forEach(function (content) { + var payload = content[0]; + var ctx = content[1]; + var t = content[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this$1.logger("($on)", ("call run on " + evt)); + this$1.run(callback, payload, context || ctx); + size += this$1.addToNormalStore(evt, type, callback, context || ctx); + }); + return size; + }; + + /** + * once only registered it once, there is no overwrite option here + * @NOTE change in v1.3.0 $once can add multiple listeners + * but once the event fired, it will remove this event (see $only) + * @param {string} evt name + * @param {function} callback to execute + * @param {object} [context=null] the handler execute in + * @return {boolean} result + */ + EventService.prototype.$once = function $once (evt , callback , context) { + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'once'; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (lazyStoreContent === false) { + this.logger('($once)', (evt + " not in the lazy store")); + // v1.3.0 $once now allow to add multiple listeners + return this.addToNormalStore(evt, type, callback, context) + } else { + // now this is the tricky bit + // there is a potential bug here that cause by the developer + // if they call $trigger first, the lazy won't know it's a once call + // so if in the middle they register any call with the same evt name + // then this $once call will be fucked - add this to the documentation + this.logger('($once)', lazyStoreContent); + var list = Array.from(lazyStoreContent); + // should never have more than 1 + var ref = list[0]; + var payload = ref[0]; + var ctx = ref[1]; + var t = ref[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this.logger('($once)', ("call run for " + evt)); + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); + } + }; + + /** + * This one event can only bind one callbackback + * @param {string} evt event name + * @param {function} callback event handler + * @param {object} [context=null] the context the event handler execute in + * @return {boolean} true bind for first time, false already existed + */ + EventService.prototype.$only = function $only (evt, callback, context) { + var this$1 = this; + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'only'; + var added = false; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (!nStore.has(evt)) { + this.logger("($only)", (evt + " add to store")); + added = this.addToNormalStore(evt, type, callback, context); + } + if (lazyStoreContent !== false) { + // there are data store in lazy store + this.logger('($only)', (evt + " found data in lazy store to execute")); + var list = Array.from(lazyStoreContent); + // $only allow to trigger this multiple time on the single handler + list.forEach( function (l) { + var payload = l[0]; + var ctx = l[1]; + var t = l[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this$1.logger("($only)", ("call run for " + evt)); + this$1.run(callback, payload, context || ctx); + }); + } + return added; + }; + + /** + * $only + $once this is because I found a very subtile bug when we pass a + * resolver, rejecter - and it never fire because that's OLD added in v1.4.0 + * @param {string} evt event name + * @param {function} callback to call later + * @param {object} [context=null] exeucte context + * @return {void} + */ + EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'onlyOnce'; + var added = false; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (!nStore.has(evt)) { + this.logger("($onlyOnce)", (evt + " add to store")); + added = this.addToNormalStore(evt, type, callback, context); + } + if (lazyStoreContent !== false) { + // there are data store in lazy store + this.logger('($onlyOnce)', lazyStoreContent); + var list = Array.from(lazyStoreContent); + // should never have more than 1 + var ref = list[0]; + var payload = ref[0]; + var ctx = ref[1]; + var t = ref[2]; + if (t && t !== 'onlyOnce') { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this.logger("($onlyOnce)", ("call run for " + evt)); + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); + } + return added; + }; + + /** + * This is a shorthand of $off + $on added in V1.5.0 + * @param {string} evt event name + * @param {function} callback to exeucte + * @param {object} [context = null] or pass a string as type + * @param {string} [type=on] what type of method to replace + * @return {} + */ + EventService.prototype.$replace = function $replace (evt, callback, context, type) { + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = 'on'; + + if (this.validateType(type)) { + this.$off(evt); + var method = this['$' + type]; + this.logger("($replace)", evt, callback); + return Reflect.apply(method, this, [evt, callback, context]) + } + throw new Error((type + " is not supported!")) + }; + + /** + * trigger the event + * @param {string} evt name NOT allow array anymore! + * @param {mixed} [payload = []] pass to fn + * @param {object|string} [context = null] overwrite what stored + * @param {string} [type=false] if pass this then we need to add type to store too + * @return {number} if it has been execute how many times + */ + EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { + if ( payload === void 0 ) payload = []; + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = false; + + this.validateEvt(evt); + var found = 0; + // first check the normal store + var nStore = this.normalStore; + this.logger('($trigger)', 'normalStore', nStore); + if (nStore.has(evt)) { + // @1.8.0 to add the suspend queue + var added = this.$queue(evt, payload, context, type); + this.logger('($trigger)', evt, 'found; add to queue: ', added); + if (added === true) { + this.logger('($trigger)', evt, 'not executed. Exit now.'); + return false; // not executed + } + var nSet = Array.from(nStore.get(evt)); + var ctn = nSet.length; + var hasOnce = false; + for (var i=0; i < ctn; ++i) { + ++found; + // this.logger('found', found) + var ref = nSet[i]; + var _ = ref[0]; + var callback = ref[1]; + var ctx = ref[2]; + var type$1 = ref[3]; + this.logger("($trigger)", ("call run for " + evt)); + this.run(callback, payload, context || ctx); + if (type$1 === 'once' || type$1 === 'onlyOnce') { + hasOnce = true; + } + } + if (hasOnce) { + nStore.delete(evt); + } + return found; + } + // now this is not register yet + this.addToLazyStore(evt, payload, context, type); + return found; + }; + + /** + * this is an alias to the $trigger + * @NOTE breaking change in V1.6.0 we swap the parameter around + * @param {string} evt event name + * @param {*} params pass to the callback + * @param {string} type of call + * @param {object} context what context callback execute in + * @return {*} from $trigger + */ + EventService.prototype.$call = function $call (evt, params, type, context) { + if ( type === void 0 ) type = false; + if ( context === void 0 ) context = null; + + var args = [evt, params, context, type]; + return Reflect.apply(this.$trigger, this, args) + }; + + /** + * remove the evt from all the stores + * @param {string} evt name + * @return {boolean} true actually delete something + */ + EventService.prototype.$off = function $off (evt) { + var this$1 = this; + + this.validateEvt(evt); + var stores = [ this.lazyStore, this.normalStore ]; + var found = false; + stores.forEach(function (store) { + if (store.has(evt)) { + found = true; + this$1.logger('($off)', evt); + store.delete(evt); + } + }); + return found; + }; + + /** + * return all the listener from the event + * @param {string} evtName event name + * @param {boolean} [full=false] if true then return the entire content + * @return {array|boolean} listerner(s) or false when not found + */ + EventService.prototype.$get = function $get (evt, full) { + if ( full === void 0 ) full = false; + + this.validateEvt(evt); + var store = this.normalStore; + if (store.has(evt)) { + return Array + .from(store.get(evt)) + .map( function (l) { + if (full) { + return l; + } + var key = l[0]; + var callback = l[1]; + return callback; + }) + } + return false; + }; + + /** + * store the return result from the run + * @param {*} value whatever return from callback + */ + prototypeAccessors.$done.set = function (value) { + this.logger('($done)', 'value: ', value); + if (this.keep) { + this.result.push(value); + } else { + this.result = value; + } + }; + + /** + * @TODO is there any real use with the keep prop? + * getter for $done + * @return {*} whatever last store result + */ + prototypeAccessors.$done.get = function () { + if (this.keep) { + this.logger('(get $done)', this.result); + return this.result[this.result.length - 1] + } + return this.result; + }; + + Object.defineProperties( EventService.prototype, prototypeAccessors ); + + return EventService; + }(NbEventServiceBase)); + + // default + + // this will generate a event emitter and will be use everywhere + // output + function getEventEmitter(debugOn) { + var logger = debugOn ? function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + args.unshift('[NBS]'); + console.log.apply(null, args); + }: undefined; + return new EventService({ logger: logger }) + } + + // main export interface + /** + * When pass a static contract then it return a static interface + * otherwise it will become the async interface + * @param {object} fly the http engine - already init object not the class! + * @param {object} config configuration + * @return {object} jsonqlClient + */ + function jsonqlClient(fly, config) { + var ee = getEventEmitter(config.debugOn); + return jsonqlAsync(ee, config, fly) + } + + // this one will bring the fly.js in + + function full(config) { + if ( config === void 0 ) config = {}; + + return jsonqlClient(new Fly(), config) + } + + return full; + +}))); //# sourceMappingURL=jsonql-client.umd.js.map diff --git a/packages/http-client/dist/jsonql-client.umd.js.map b/packages/http-client/dist/jsonql-client.umd.js.map index cb67906c..4061c1e2 100644 --- a/packages/http-client/dist/jsonql-client.umd.js.map +++ b/packages/http-client/dist/jsonql-client.umd.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client.umd.js","sources":["../node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"w37CAAA"} \ No newline at end of file +{"version":3,"file":"jsonql-client.umd.js","sources":["../node_modules/lodash-es/isArray.js","../node_modules/rollup-plugin-node-globals/src/global.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/lodash-es/_arrayMap.js","../node_modules/lodash-es/_baseSlice.js","../node_modules/lodash-es/_baseFindIndex.js","../node_modules/lodash-es/_baseIsNaN.js","../node_modules/lodash-es/_strictIndexOf.js","../node_modules/lodash-es/_asciiToArray.js","../node_modules/lodash-es/_hasUnicode.js","../node_modules/lodash-es/_unicodeToArray.js","../node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-errors/src/resolver-not-found-error.js","../node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-errors/src/index.js","../node_modules/jsonql-errors/src/client-errors-handler.js","../node_modules/jsonql-utils/src/contract.js","../node_modules/nb-event-service/src/hash-code.js","../src/utils.js","../node_modules/jwt-decode/lib/atob.js","../node_modules/jsonql-params-validator/src/string.js","../node_modules/jsonql-jwt/src/client/decode-token/decode-token.js","../node_modules/jsonql-params-validator/src/number.js","../node_modules/jsonql-params-validator/src/boolean.js","../node_modules/jsonql-params-validator/src/any.js","../node_modules/jsonql-params-validator/src/constants.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/_listCacheClear.js","../node_modules/lodash-es/eq.js","../node_modules/lodash-es/_stackDelete.js","../node_modules/lodash-es/_stackGet.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-params-validator/src/validator.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/negate.js","../node_modules/lodash-es/_baseFindKey.js","../node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-params-validator/src/options/check-options-async.js","../node_modules/jsonql-params-validator/src/options/construct-config.js","../node_modules/jsonql-params-validator/src/options/index.js","../node_modules/jsonql-params-validator/index.js","../node_modules/jsonql-utils/src/timestamp.js","../node_modules/store/plugins/defaults.js","../src/stores/local-store.js","../src/stores/session-store.js","../src/stores/index.js","../node_modules/jsonql-utils/src/params-api.js","../node_modules/jsonql-utils/src/results.js","../src/base/store-cls.js","../src/base/http-cls.js","../src/base/contract-cls.js","../src/base/auth-cls.js","../src/base/base-cls.js","../src/base/index.js","../src/core/methods-generator.js","../src/core/jsonql-api-generator.js","../src/options/base-options.js","../src/options/check-options-async.js","../src/options/index.js","../src/jsonql-async.js","../node_modules/nb-event-service/src/suspend.js","../node_modules/nb-event-service/src/store-service.js","../node_modules/nb-event-service/src/event-service.js","../node_modules/nb-event-service/index.js","../src/ee.js","../index.js","../full.js"],"sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length;\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg];\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @return {*} json object on success\n */\nconst parse = function(n) {\n try {\n return JSON.parse(n)\n } catch(e) {\n return n;\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false;\n /*\n console.info('obj', obj)\n console.error(e)\n throw new Error(e)\n */\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = (n) => {\n if (typeof n === 'string') {\n return parse(n)\n }\n return JSON.parse(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== '';\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n","/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error)\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","/**\n * This is a custom error to throw when could not find the resolver\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class JsonqlResolverNotFoundError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlResolverNotFoundError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlResolverNotFoundError);\n }\n }\n\n static get statusCode() {\n return 404;\n }\n\n static get name() {\n return 'JsonqlResolverNotFoundError';\n }\n}\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError);\n }\n }\n\n static get name() {\n return 'JsonqlEnumError';\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlTypeError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError);\n }\n }\n\n static get name() {\n return 'JsonqlTypeError';\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args)\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError)\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError';\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError';\n }\n}\n","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message)\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// server side\nimport Jsonql406Error from './406-error'\nimport Jsonql500Error from './500-error'\n\nimport JsonqlForbiddenError from './forbidden-error'\nimport JsonqlAuthorisationError from './authorisation-error'\nimport JsonqlContractAuthError from './contract-auth-error'\nimport JsonqlResolverAppError from './resolver-app-error'\nimport JsonqlResolverNotFoundError from './resolver-not-found-error'\n\n// check options error\nimport JsonqlEnumError from './enum-error'\nimport JsonqlTypeError from './type-error'\nimport JsonqlCheckerError from './checker-error'\n// share\nimport JsonqlValidationError from './validation-error'\nimport JsonqlError from './error'\n\nimport JsonqlServerError from './server-error'\n\nexport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlForbiddenError,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n};\n","// this will add directly to the then call in each http call\n\nimport * as errors from './index'\nimport getErrorByStatus from './get-error-by-status'\nimport { NO_ERROR_MSG } from 'jsonql-constants'\nconst { JsonqlError } = errors\n\n/**\n * We can not just check something like result.data what if the result if false?\n * @param {object} obj the result object\n * @param {string} key we want to check if its exist or not\n * @return {boolean} true on found\n */\nconst isObjectHasKey = (obj, key) => {\n const keys = Object.keys(obj)\n return !!keys.filter(k => key === k).length;\n}\n\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nexport default function clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n","// split the contract into the node side and the generic side\nimport { isObjectHasKey } from './generic'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n SOCKET_NAME,\n QUERY_ARG_NAME,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlResolverNotFoundError } from 'jsonql-errors'\n/**\n * Check if the json is a contract file or not\n * @param {object} contract json object\n * @return {boolean} true\n */\nexport function checkIsContract(contract) {\n return isPlainObject(contract)\n && (\n isObjectHasKey(contract, QUERY_NAME)\n || isObjectHasKey(contract, MUTATION_NAME)\n || isObjectHasKey(contract, SOCKET_NAME)\n )\n}\n\n/**\n * Wrapper method that check if it's contract then return the contract or false\n * @param {object} contract the object to check\n * @return {boolean | object} false when it's not\n */\nexport function isContract(contract) {\n return checkIsContract(contract) ? contract : false;\n}\n\n/**\n * Ported from jsonql-params-validator but different\n * if we don't find the socket part then return false\n * @param {object} contract the contract object\n * @return {object|boolean} false on failed\n */\nexport function extractSocketPart(contract) {\n if (isObjectHasKey(contract, 'socket')) {\n return contract.socket;\n }\n return false;\n}\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @param {boolean} [fallback=false] this is a fall back option for old code\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport function groupByNamespace(contract, fallback = false) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n if (fallback) {\n return contract; // just return the whole contract\n }\n throw new JsonqlError(`socket not found in contract!`)\n }\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\n}\n\n/**\n * @NOTE ported from jsonql-ws-client\n * Got to make sure the connection order otherwise\n * it will hang\n * @param {object} nspSet contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspSet, publicNamespace) {\n let names = []; // need to make sure the order!\n for (let namespace in nspSet) {\n if (namespace === publicNamespace) {\n names[1] = namespace;\n } else {\n names[0] = namespace;\n }\n }\n return names;\n}\n\n\n/**\n * Extract the args from the payload\n * @param {object} payload to work with\n * @param {string} type of call\n * @return {array} args\n */\nexport function extractArgsFromPayload(payload, type) {\n switch (type) {\n case QUERY_NAME:\n return payload[QUERY_ARG_NAME];\n case MUTATION_NAME:\n return [\n payload[PAYLOAD_PARAM_NAME],\n payload[CONDITION_PARAM_NAME]\n ];\n default:\n throw new JsonqlError(`Unknown ${type} to extract argument from!`)\n }\n}\n\n/**\n * Like what the name said\n * @param {object} contract the contract json\n * @param {string} type query|mutation\n * @param {string} name of the function\n * @return {object} the params part of the contract\n */\nexport function extractParamsFromContract(contract, type, name) {\n try {\n const result = contract[type][name];\n // debug('extractParamsFromContract', result)\n if (!result) {\n // debug(name, type, contract)\n throw new JsonqlResolverNotFoundError(name, type)\n }\n return result;\n } catch(e) {\n throw new JsonqlResolverNotFoundError(name, e)\n }\n}\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport default function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n","// take only the module part which is what we use here\n// and export it again to use through out the client\n// this way we avoid those that we don't want node.js module got build into the code\nimport { isContract } from 'jsonql-utils/src/contract'\nimport hashCodeFn from 'nb-event-service/src/hash-code'\n/**\n * @param {object} jsonqlInstance the init instance of jsonql client\n * @param {object} contract the static contract\n * @return {object} contract may be from server\n */\nconst getContractFromConfig = function(jsonqlInstance, contract = {}) {\n if (isContract(contract)) {\n return Promise.resolve(contract)\n }\n return jsonqlInstance.getContract()\n}\n// wrapper method to make sure it's a string\nconst hashCode = str => hashCodeFn(str) + ''\n\n// simple util to check if an object has any properties\n// const hasProp = obj => isObject(obj) && Object.keys(obj).length\n\n// export some constants as well\n// since it's only use here there is no point of adding it to the constants module\n// or may be we add it back later\nconst ENDPOINT_TABLE = 'endpoint' // not in use anymore delete later @TODO\nconst USERDATA_TABLE = 'userdata'\nconst CLS_LOCAL_STORE_NAME = 'localStore'\nconst CLS_SESS_STORE_NAME = 'sessionStore'\nconst CLS_CONTRACT_NAME = 'contract'\nconst CLS_PROFILE_IDX = 'prof_idx'\nconst LOG_ERROR_SWITCH = '__error__'\nconst ZERO_IDX = 0\n// export\nexport {\n hashCode,\n getContractFromConfig,\n ENDPOINT_TABLE,\n USERDATA_TABLE,\n CLS_LOCAL_STORE_NAME,\n CLS_SESS_STORE_NAME,\n CLS_CONTRACT_NAME,\n CLS_PROFILE_IDX,\n LOG_ERROR_SWITCH,\n ZERO_IDX\n}\n","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\nfunction polyfill (input) {\n var str = String(input).replace(/=+$/, '');\n if (str.length % 4 == 1) {\n throw new InvalidCharacterError(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = '';\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n return output;\n}\n\n\nmodule.exports = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill;\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false;\n}\n\nexport default checkIsString\n","// when the user is login with the jwt\n// we use call this to decode the token and then add the payload\n// to the resolver so the user can call ResolverName.userdata\n// and get back the payload\nimport jwt_decode from 'jwt-decode'\nimport isString from 'jsonql-params-validator/src/string'\nimport JsonqlError from 'jsonql-errors/src/error'\n\nconst timestamp = function (sec = false) {\n var time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n\n/**\n * We only check the nbf and exp\n * @param {object} token for checking\n * @return {object} token on success\n */\nfunction validate(token) {\n const start = token.iat || timestamp(true)\n // we only check the exp for the time being\n if (token.exp) {\n if (start >= token.exp) {\n const expired = new Date(token.exp).toISOString()\n throw new JsonqlError(`Token has expired on ${expired}`, token)\n }\n }\n return token;\n}\n\n/**\n * The browser client version it has far fewer options and it doesn't verify it\n * because it couldn't this is the job for the server\n * @TODO we need to add some extra proessing here to check for the exp field\n * @param {string} token to decrypted\n * @return {object} decrypted object\n */\nexport default function jwtDecode(token) {\n if (isString(token)) {\n const t = jwt_decode(token)\n return validate(t)\n }\n throw new JsonqlError('Token must be a string!')\n}\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nexport const ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\n","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber;\n case STRING_TYPE:\n return checkIsString;\n case BOOLEAN_TYPE:\n return checkIsBoolean;\n default:\n return checkIsAny;\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false;\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false;\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p;\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length;\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length;\n}\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport filter from 'lodash-es/filter'\n\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true;\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (_value !== undefined) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true;\n }).length)\n }).length;\n }\n }\n return false;\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p;\n let _args = [arg];\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return Reflect.apply(checkIsObject, null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\n\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n checkIsObject,\n combineFn,\n notEmpty\n} from './index'\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params;\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false;\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (arg !== undefined) {\n return arg;\n }\n return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ))\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ))\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ))\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length:\n let ctn = params.length;\n // this happens when we have those array. type\n let _type = [ DEFAULT_TYPE ]\n // we only looking at the first one, this might be a @BUG\n /*\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n } */\n // if we use the params as guide then the rest will get throw out\n // which is not what we want, instead, anything without the param\n // will get a any type and optional flag\n return args.map((arg, i) => {\n let optional = i >= ctn ? true : !!params[i].optional\n let param = params[i] || { type: _type, name: `_${i}` }\n return {\n arg: optional ? getOptionalValue(arg, param) : arg,\n index: i,\n param,\n optional\n }\n })\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n // v1.4.4 this fixed the problem, the root level optional is from the last fn\n if (p.optional === true || p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length;\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport isFunction from 'lodash-es/isFunction'\nimport merge from 'lodash-es/merge'\nimport mapValues from 'lodash-es/mapValues'\n\nimport JsonqlEnumError from 'jsonql-errors/src/enum-error'\nimport JsonqlTypeError from 'jsonql-errors/src/type-error'\nimport JsonqlCheckerError from 'jsonql-errors/src/checker-error'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true;\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // log('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n // log(ENUM_KEY, value[ENUM_KEY])\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n // log(CHECKER_KEY, value[CHECKER_KEY])\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args;\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","/// this is port back from the client to share across all projects\n\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:check-options-async')\n\n/**\n * Quick transform\n * @param {object} config that one\n * @param {object} appProps mutation configuration options\n * @return {object} put that arg into the args\n */\nconst configToArgs = (config, appProps) => {\n return Promise.resolve(\n prepareArgsForValidation(config, appProps)\n )\n}\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return configToArgs(config, appProps)\n .then(args1 => runValidation(args1, cb))\n // next if every thing good then pass to final merging\n .then(args2 => merge({}, args2, constProps))\n}\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\nimport checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n };\n if (optional === true) {\n base[OPTIONAL_KEY] = true;\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv;\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker;\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias;\n }\n return base;\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__';\n\n/**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n checkConfigAsync,\n checkConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nexport const inArray = isInArray;\nexport const isObjectHasKey = isObjectHasKeyFn;\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n","module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n","// sort of persist on the user side\nimport engine from 'store/src/store-engine'\n\nimport localStorage from 'store/storages/localStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// @1.5.0 stop using the expired plugin, and deal with it ourself\n// import expiredPlugin from 'store/plugins/expire'\nimport eventsPlugin from 'store/plugins/events'\nimport compressionPlugin from 'store/plugins/compression'\n\nconst storages = [localStorage, cookieStorage]\nconst plugins = [defaultPlugin, eventsPlugin, compressionPlugin]\n\nconst localStore = engine.createStore(storages, plugins)\n\nexport default localStore\n","// session store with watch\nimport engine from 'store/src/store-engine'\n\nimport sessionStorage from 'store/storages/sessionStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// start using compression in 1.5.0 \nimport compressionPlugin from 'store/plugins/compression'\n// @1.5.0 stop using the expired plugin and deal it ourself\n// import expiredPlugin from 'store/plugins/expire'\n\nconst storages = [sessionStorage, cookieStorage]\nconst plugins = [defaultPlugin, compressionPlugin]\n\nconst sessionStore = engine.createStore(storages, plugins)\n\nexport default sessionStore\n","// export store interface\n// @TODO need to figure out how to make this as a outside dependencies instead of built into it\nimport localStoreEngine from './local-store'\nimport sessionStoreEngine from './session-store'\n\n// export back the raw version for development purposes\nexport const localStore = localStoreEngine\nexport const sessionStore = sessionStoreEngine\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport isString from 'lodash-es/isString'\n\nimport { timestamp } from './timestamp'\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? JSON.parse(payload) : payload;\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName\n * @param {*} payload\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload) {\n return {\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload;\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload;\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getNameFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// break up from node-middleware\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n API_REQUEST_METHODS,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME ,\n QUERY_ARG_NAME,\n DATA_KEY,\n ERROR_KEY,\n INDEX_KEY,\n EXT,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport { isObjectHasKey } from './generic'\nimport { timestamp } from './timestamp'\nimport isArray from 'lodash-es/isArray'\nimport merge from 'lodash-es/merge'\n/**\n * getting what is calling after the above check\n * @param {string} method of call\n * @return {mixed} false on failed\n */\nexport const getCallMethod = method => {\n const [ POST, PUT ] = API_REQUEST_METHODS;\n switch (true) {\n case method === POST:\n return QUERY_NAME;\n case method === PUT:\n return MUTATION_NAME;\n default:\n return false;\n }\n}\n\n/**\n * wrapper method\n * @param {mixed} result of fn return\n * @param {boolean|array} [ts=false] when pass this then we append a new value to the end\n * @return {string} stringify data\n */\nexport const packResult = function(result, ts = false) {\n let payload = { [DATA_KEY]: result }\n if (ts && isArray(ts)) {\n ts.push(timestamp())\n payload[TIMESTAMP_PARAM_NAME] = ts\n }\n return JSON.stringify(payload)\n}\n\n/**\n * Check if the error object contain out custom key\n * @param {*} e object\n * @return {boolean} true\n */\nexport const isJsonqlErrorObj = e => {\n const searchFields = ['detail', 'className']\n const test = !!searchFields.filter(field => isObjectHasKey(e, field)).length\n if (test) {\n return ['className', 'message', 'statusCode']\n .filter(field => isObjectHasKey(e, field))\n .map(field => (\n {\n [field]: typeof e[field] === 'object' ? e[field].toString() : e[field]\n }\n ))\n .reduce(merge, {detail: e.toString()}) // can only get as much as possible\n }\n return false;\n}\n\n/**\n * wrapper method - the output is trying to match up the structure of the Error sub class\n * @param {mixed} detail of fn error\n * @param {string} [className=JsonqlError] the errorName\n * @param {number} [statusCode=500] the original error code\n * @return {string} stringify error\n */\nexport const packError = function(detail, className = 'JsonqlError', statusCode = 0, message = '') {\n let errorObj = { detail, className, statusCode, message }\n // we need to check the detail object to see if it has detail, className and message\n // if it has then we should merge the object instead\n return JSON.stringify({\n [ERROR_KEY]: isJsonqlErrorObj(detail) || errorObj,\n [TIMESTAMP_PARAM_NAME]: timestamp()\n })\n}\n\n// ported from http-client\n\n/**\n * handle the return data\n * @TODO how to handle the return timestamp and calculate the diff?\n * @param {object} result return from server\n * @return {object} strip the data part out, or if the error is presented\n */\nexport const resultHandler = result => (\n (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result\n)\n","// new 1.5.0\n// create a class method to handle all the saving and retriving data\n// using the instanceKey to id the data hence allow to use multiple instance\nimport merge from 'lodash-es/merge'\nimport { localStore, sessionStore } from '../stores'\nimport { CLS_SESS_STORE_NAME, CLS_LOCAL_STORE_NAME, hashCode } from '../utils'\n\n// this becomes the base class instead of the HttpCls\nexport default class StoreClass {\n\n constructor(opts) {\n this.opts = opts\n // make it a string\n this.instanceKey = hashCode(this.opts.hostname)\n // pass this store for use later\n this.localStore = localStore\n this.sessionStore = sessionStore\n /*\n if (this.opts.debugOn) { // reuse this to clear out the data\n this.log('clear all stores')\n localStore.clearAll()\n sessionStore.clearAll()\n\n localStore.set('TEST', Date.now())\n sessionStore.set('TEST', Date.now())\n }\n */\n }\n // store in local storage id by the instanceKey\n // values should be an object so with key so we just merge\n // into the existing store without going through the keys\n __setMethod(storeType, values) {\n let store = this[storeType]\n let data = this.__getMethod(storeType)\n const skey = this.opts.storageKey\n const ikey = this.instanceKey\n store.set(skey, {\n [ikey]: data ? merge({}, data, values) : values\n })\n }\n // return the data id by the instaceKey\n __getMethod(storeType) {\n let store = this[storeType]\n let data = store.get(this.opts.storageKey)\n return data ? data[this.instanceKey] : false\n }\n // remove from local store id by instanceKey\n __delMethod(storeType, key) {\n let data = this.__getMethod(storeType)\n if (data) {\n let store = {}\n for (let k in data) {\n if (k !== key) {\n store[k] = data[k]\n }\n }\n this.__setMethod(storeType, store)\n }\n }\n // clear everything by this instanceKey\n __clearMethod(storeKey) {\n const skey = this.opts.storageKey\n const store = this[storeKey]\n let data = store.get(skey)\n if (data) {\n let _store = {}\n for (let k in data) {\n if (k !== this.instanceKey) {\n _store[k] = data[k]\n }\n }\n store.set(skey, _store)\n }\n }\n // Alias for different store\n set lset(values) {\n return this.__setMethod(CLS_LOCAL_STORE_NAME, values)\n }\n\n get lget() {\n return this.__getMethod(CLS_LOCAL_STORE_NAME)\n }\n\n ldel(key) {\n return this.__delMethod(CLS_LOCAL_STORE_NAME, key)\n }\n\n lclear() {\n return this.__clearMethod(CLS_LOCAL_STORE_NAME)\n }\n\n // store in session store id by the instanceKey\n set sset(values) {\n // this.log('--- sset ---', values)\n return this.__setMethod(CLS_SESS_STORE_NAME, values)\n }\n\n get sget() {\n return this.__getMethod(CLS_SESS_STORE_NAME)\n }\n\n sdel(key) {\n return this.__delMethod(CLS_SESS_STORE_NAME, key)\n }\n\n sclear() {\n return this.__clearMethod(CLS_SESS_STORE_NAME)\n }\n\n\n}\n","// base HttpClass\nimport merge from 'lodash-es/merge'\nimport {\n createQuery,\n createMutation,\n getNameFromPayload\n} from 'jsonql-utils/src/params-api'\nimport { cacheBurst, urlParams } from 'jsonql-utils/src/urls'\nimport { resultHandler } from 'jsonql-utils/src/results'\nimport { isObject, isString } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlServerError,\n JsonqlError,\n clientErrorsHandler\n} from 'jsonql-errors'\nimport {\n API_REQUEST_METHODS,\n DEFAULT_HEADER,\n JSONP_CALLBACK_NAME,\n SHOW_CONTRACT_DESC_PARAM\n} from 'jsonql-constants'\nimport { LOG_ERROR_SWITCH } from '../utils'\n\n// extract the one we need\nconst [ POST, PUT ] = API_REQUEST_METHODS\n\nimport StoreClass from './store-cls'\n\nexport default class HttpClass extends StoreClass {\n /**\n * The opts has been check at the init stage\n * @param {object} opts configuration options\n */\n constructor(opts) {\n super(opts)\n // change the way how we init Fly\n // flyio now become external depedencies and it makes it easier to switch\n // @BUG should we run test to check if we have the windows object?\n // this.log(opts)\n // this.fly = opts.Fly ? new opts.Fly() : new Fly()\n // to a different environment like WeChat mini app\n\n this.extraHeader = {};\n // @1.2.1 for adding query to the call on the fly\n this.extraParams = {};\n // this.log('start up opts', opts);\n this.reqInterceptor()\n this.resInterceptor()\n }\n\n // set headers for that one call\n set headers(header) {\n this.extraHeader = header;\n }\n\n /**\n * Create the reusage request method\n * @param {object} payload jsonql payload\n * @param {object} options extra options add the request\n * @param {object} headers extra headers add to the call\n * @return {object} the fly request instance\n */\n request(payload, options = {}, headers = {}) {\n this.headers = headers;\n let params = merge({}, cacheBurst(), this.extraParams)\n // @TODO need to add a jsonp url and payload\n if (this.opts.enableJsonp) {\n let resolverName = getNameFromPayload(payload)\n params = merge({}, params, {[JSONP_CALLBACK_NAME]: resolverName})\n payload = payload[resolverName]\n }\n // double up the url param and see what happen @TODO remove later\n const reqParams = merge({}, { method: POST, params }, options)\n this.log('request params', reqParams, this.jsonqlEndpoint)\n\n return this.fly.request(this.jsonqlEndpoint, payload, reqParams)\n }\n\n /**\n * This will replace the create baseRequest method\n *\n */\n reqInterceptor() {\n this.fly.interceptors.request.use(\n req => {\n const headers = this.getHeaders()\n this.log('request interceptor call', headers)\n\n for (let key in headers) {\n req.headers[key] = headers[key]\n }\n return req;\n }\n )\n }\n\n // @TODO\n processJsonp(result) {\n return resultHandler(result)\n }\n\n /**\n * This will be replacement of the first then call\n *\n */\n resInterceptor() {\n const self = this;\n const jsonp = self.opts.enableJsonp;\n this.fly.interceptors.response.use(\n res => {\n this.log('response interceptor call', res)\n self.cleanUp()\n // now more processing here\n // there is a problem if we throw the result.error here\n // the original data is lost, so we need to do what we did before\n // deal with that error in the first then instead\n const result = isString(res.data) ? JSON.parse(res.data) : res.data;\n if (jsonp) {\n return self.processJsonp(result)\n }\n return resultHandler(result)\n },\n // this get call when it's not 200\n err => {\n self.cleanUp()\n this.log(LOG_ERROR_SWITCH, err)\n throw new JsonqlServerError('Server side error', err)\n }\n )\n }\n\n /**\n * Get the headers inject into the call\n * @return {object} headers\n */\n getHeaders() {\n if (this.opts.enableAuth) {\n return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader)\n }\n return merge({}, DEFAULT_HEADER, this.extraHeader)\n }\n\n /**\n * Post http call operation to clean up things we need\n */\n cleanUp() {\n this.extraHeader = {}\n this.extraParams = {}\n }\n\n /**\n * GET for contract only\n * @return {promise} resolve the contract\n */\n getRemoteContract() {\n if (this.opts.showContractDesc) {\n this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM)\n }\n return this.request({}, {method: 'GET'}, this.contractHeader)\n .then(clientErrorsHandler)\n .then(result => {\n this.log('get contract result', result)\n // when refresh the window the result is different!\n // @TODO need to check the Koa side about why is that\n // also it should set a flag if we want the description or not\n if (result.cache && result.contract) {\n return result.contract;\n }\n // just the normal result\n return result\n })\n .catch(err => {\n this.log(LOG_ERROR_SWITCH, 'getRemoteContract err', err)\n throw new JsonqlServerError('getRemoteContract', err)\n })\n }\n\n /**\n * POST to server - query\n * @param {object} name of the resolver\n * @param {array} args arguments\n * @return {object} promise resolve to the resolver return\n */\n query(name, args = []) {\n return this.request(createQuery(name, args))\n .then(clientErrorsHandler)\n }\n\n /**\n * PUT to server - mutation\n * @param {string} name of resolver\n * @param {object} payload what it said\n * @param {object} conditions what it said\n * @return {object} promise resolve to the resolver return\n */\n mutation(name, payload = {}, conditions = {}) {\n return this.request(createMutation(name, payload, conditions), {method: PUT})\n .then(clientErrorsHandler)\n }\n\n}\n","// all the contract related methods will be here\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { timestamp } from 'jsonql-utils/src/timestamp'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { ENDPOINT_TABLE, CLS_CONTRACT_NAME } from '../utils'\nimport { localStore } from '../stores'\nimport HttpClass from './http-cls'\n\n// export\nexport default class ContractClass extends HttpClass {\n\n constructor(opts) {\n super(opts)\n }\n\n /**\n * return the contract public api\n * @return {object} contract\n */\n getContract() {\n const contract = this.readContract()\n this.log('getContract first call', contract)\n return contract ? Promise.resolve(contract)\n : this.getRemoteContract().then(this.storeContract.bind(this))\n }\n\n /**\n * We are changing the way how to auth to get the contract.json\n * Instead of in the url, we will be putting that key value in the header\n * @return {object} header\n */\n get contractHeader() {\n let base = {};\n if (this.opts.contractKey !== false) {\n base[this.opts.contractKeyName] = this.opts.contractKey;\n }\n return base;\n }\n\n /**\n * Save the contract to local store\n * @param {object} contract to save\n * @return {object|boolean} false when its not a contract or contract on OK\n */\n storeContract(contract) {\n // first need to check if the contract is a contract\n if (!isContract(contract)) {\n throw new JsonqlValidationError(`Contract is malformed!`)\n }\n this.lset = {[CLS_CONTRACT_NAME]: contract}\n // return it\n this.log('storeContract return result', contract)\n return contract;\n }\n\n /**\n * return the contract from options or localStore\n * @return {object|boolean} false on not found\n */\n readContract() {\n let contract = isContract(this.opts.contract)\n if (contract !== false) {\n return contract;\n }\n let data = this.lget\n if (data) {\n return data[CLS_CONTRACT_NAME]\n }\n return false;\n }\n}\n","// this is the new auth class that integrate with the jsonql-jwt\n// all the auth related methods will be here\nimport { decodeToken } from 'jsonql-jwt/src/client'\nimport { isNumber } from 'jsonql-params-validator'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { CREDENTIAL_STORAGE_KEY, AUTH_HEADER, BEARER } from 'jsonql-constants'\nimport { CLS_PROFILE_IDX, ZERO_IDX, USERDATA_TABLE } from '../utils'\nimport ContractClass from './contract-cls'\n// export\nexport default class AuthClass extends ContractClass {\n\n constructor(opts) {\n super(opts)\n if (opts.enableAuth) {\n this.setDecoder = decodeToken;\n }\n }\n\n /**\n * for overwrite\n * @param {string} token stored token\n * @return {string} token\n */\n decoder(token) {\n return token;\n }\n\n /**\n * set the profile index\n * @param {number} idx\n */\n set profileIndex(idx) {\n const key = CLS_PROFILE_IDX\n if (isNumber(idx)) {\n this[key] = idx;\n if (this.opts.persistToken) {\n this.lset = {[key]: idx}\n }\n return;\n }\n throw new JsonqlValidationError('profileIndex', `Expect idx to be number but got ${typeof idx}`)\n }\n\n /**\n * get the profile index\n * @return {number} idx\n */\n get profileIndex() {\n const key = CLS_PROFILE_IDX\n if (this.opts.persistToken) {\n const data = this.lget;\n if (data[key]) {\n return data[key]\n }\n }\n return this[key] ? this[key] : ZERO_IDX\n }\n\n /**\n * Return the token from session store\n * @param {number} [idx=false] profile index\n * @return {string} token\n */\n rawAuthToken(idx = false) {\n if (idx !== false) {\n this.profileIndex = idx;\n }\n // this should return from the base\n return this.jsonqlToken; // see base-cls\n }\n\n /**\n * Setter to add a decoder when retrieve user token\n * @param {function} d a decoder\n */\n set setDecoder(d) {\n if (typeof d === 'function') {\n this.decoder = d;\n }\n }\n\n /**\n * getter to return the session or local store set method\n * @param {*} data to save\n * @return {object} set method\n */\n set saveProfile(data) {\n if (this.opts.persistToken) {\n // this.log('--- saveProfile lset ---', data)\n this.lset = data\n } else {\n // this.log('--- saveProfile sset ---', data)\n this.sset = data\n }\n }\n\n /**\n * getter to return the session or local store get method\n * @return {object} get method\n */\n get readProfile() {\n return this.opts.persistToken ? this.lget : this.sget\n }\n\n // these were in the base class before but it should be here\n /**\n * save token\n * @param {string} token to store\n * @return {string|boolean} false on failed\n */\n set jsonqlToken(token) {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n // @TODO also have to make sure the token is not already existed!\n let tokens = (data && data[key]) ? data[key] : []\n tokens.push(token)\n this.saveProfile = {[key]: tokens}\n // store the userdata\n this.jsonqlUserdata = this.decoder(token)\n }\n\n /**\n * Jsonql token getter\n * 1.5.1 each token associate with the same profileIndex\n * @return {string|boolean} false when failed\n */\n get jsonqlToken() {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex])\n return data[key][this.profileIndex]\n }\n return false\n }\n\n /**\n * this one will use the sessionStore\n * basically we hook this onto the token store and decode it to store here\n * we only store one decoded user data at a time, but the token can be multiple\n */\n set jsonqlUserdata(userdata) {\n this.sset = {[USERDATA_TABLE]: userdata}\n }\n\n /**\n * this one store in the session store\n * get login userdata decoded jwt\n * 1.5.1 each userdata associate with the same profileIndex\n * @return {object|null}\n */\n get jsonqlUserdata() {\n const data = this.sget\n return data ? data[USERDATA_TABLE] : false\n }\n\n /**\n * Construct the auth header\n * @return {object} header\n */\n getAuthHeader() {\n const token = this.jsonqlToken // only call the getter to get the default one\n return token ? {[this.opts.AUTH_HEADER]: `${BEARER} ${token}`} : {};\n }\n\n /**\n * return all the stored token and decode it\n * @param {number} [idx=false] profile index\n * @return {array|boolean|string} false not found or array\n */\n getProfiles(idx = false) {\n const self = this; // just in case the scope problem\n const data = self.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n if (idx !== false && isNumber(idx)) {\n return data[key][idx] || false\n }\n return data[key].map(self.decoder.bind(self))\n }\n return false\n }\n\n /**\n * call after the login\n * @param {string} token return from server\n * @return {object} decoded token to userdata object\n */\n postLoginAction(token) {\n this.jsonqlToken = token\n return token\n }\n\n /**\n * call after the logout @TODO\n */\n postLogoutAction(...args) {\n console.info(`postLogoutAction`, args)\n }\n}\n","// this the core of the internal storage management\nimport { CREDENTIAL_STORAGE_KEY } from 'jsonql-constants'\n// import { isObject, isArray } from 'jsonql-params-validator'\n// import { JsonqlValidationError } from 'jsonql-errors'\n// import { timestamp } from 'jsonql-utils/src/timestamp'\n// import { inArray } from 'jsonql-utils/src/generic'\nimport { USERDATA_TABLE, LOG_ERROR_SWITCH } from '../utils'\nimport AuthCls from './auth-cls'\n\n// This class will only focus on the storage system\nexport default class JsonqlBaseClient extends AuthCls {\n // change the order of the interface in 1.4.10 to match up the top level\n constructor(fly, opts) {\n // change at 1.4.10 pass it directly without init it\n this.fly = fly;\n super(opts)\n }\n\n /**\n * construct the end point\n * @return {string} the end point to call\n */\n get jsonqlEndpoint() {\n const baseUrl = this.opts.hostname || ''\n return [baseUrl, this.opts.jsonqlPath].join('/')\n }\n\n /**\n * simple log\n */\n log(...args) {\n if (this.opts.debugOn === true) {\n const fns = ['info', 'error']\n const idx = (args[0] === LOG_ERROR_SWITCH) ? 1 : 0\n Reflect.apply(console[fns[idx]], console, args.splice(0, idx))\n }\n }\n\n}\n","// export interface\n// @public\nimport JsonqlBaseClient from './base-cls'\n\nexport default JsonqlBaseClient\n","// breaking out the inner methods generator in here\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { LOGOUT_NAME, LOGIN_NAME, KEY_WORD } from 'jsonql-constants'\nimport { chainFns } from 'jsonql-utils/src/chain-fns'\nimport { injectToFn } from 'jsonql-utils/src/obj-define-props'\n\n/**\n * generate authorisation specific methods\n * @param {object} jsonqlInstance instance of this\n * @param {string} name of method\n * @param {object} opts configuration\n * @param {object} contract to match\n * @return {function} for use\n */\nconst authMethodGenerator = (jsonqlInstance, name, opts, contract) => {\n return (...args) => {\n const params = contract.auth[name].params;\n const values = params.map((p, i) => args[i])\n const header = args[params.length] || {};\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [name, values, header])\n )\n .catch(finalCatch)\n }\n}\n\n/**\n * Break up the different type each - create query methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let query = {}\n for (let queryFn in contract.query) {\n // to keep it clean we use a param to id the auth method\n // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn;\n // generate the query method\n query = injectToFn(query, queryFn, function queryFnHandler(...args) {\n const params = contract.query[queryFn].params;\n const _args = params.map((param, i) => args[i])\n // debug('query', queryFn, _params);\n // @TODO this need to change to a different way to add an extra header\n const header = {}\n // @TODO validate against the type\n return validateAsync(_args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [queryFn, _args, header])\n )\n .catch(finalCatch)\n })\n }\n obj.query = query;\n // create an alias to the helloWorld method\n obj.helloWorld = query.helloWorld;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create mutation methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let mutation = {}\n // process the mutation, the reason the mutation has a fixed number of parameters\n // there is only the payload, and conditions parameters\n // plus a header at the end\n for (let mutationFn in contract.mutation) {\n mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header = {}) {\n const args = [payload, conditions];\n const params = contract.mutation[mutationFn].params;\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .mutation\n .apply(jsonqlInstance, [mutationFn, payload, conditions, header])\n )\n .catch(finalCatch)\n })\n }\n obj.mutation = mutation;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create auth methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createAuthMethods = (obj, jsonqlInstance, ee, config, contract) => {\n if (config.enableAuth && contract.auth) {\n let auth = {} // v1.3.1 add back the auth prop name in contract\n const { loginHandlerName, logoutHandlerName } = config;\n if (contract.auth[loginHandlerName]) {\n // changing to the name the config specify\n auth[loginHandlerName] = function loginHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance))\n .then(token => {\n ee.$trigger(LOGIN_NAME, token)\n return token;\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) {\n auth[logoutHandlerName] = function logoutHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance))\n .then(r => {\n ee.$trigger(LOGOUT_NAME, r)\n return r;\n })\n }\n } else {\n auth[logoutHandlerName] = function logoutHandlerFn() {\n jsonqlInstance.postLogoutAction(KEY_WORD)\n ee.$trigger(LOGOUT_NAME, KEY_WORD)\n }\n }\n obj.auth = auth;\n }\n\n return obj;\n}\n\n/**\n * Here just generate the methods calls\n * @param {object} jsonqlInstance what it said\n * @param {object} ee event emitter\n * @param {object} config configuration\n * @param {object} contract the map\n * @return {object} with mapped methods\n */\nexport function methodsGenerator(jsonqlInstance, ee, config, contract) {\n let obj = {}\n const executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods)\n return executor(obj, jsonqlInstance, ee, config, contract)\n}\n","// Generate the resolver for developer to use\n\n// @TODO when enableAuth we need to add one extra check\n// before the resolver call make it to the core\n// which is checking the login state, if the developer\n// is calling a private method without logging in\n// then we should throw the JsonqlForbiddenError at this point\n// instead of making a round trip to the server\nimport { LOGOUT_NAME, ISSUER_NAME, KEY_WORD } from 'jsonql-constants'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\n\nimport { methodsGenerator } from './methods-generator'\n\n/**\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} config options\n * @param {object} contract the contract\n * @param {object} ee eventEmitter\n * @return {object} constructed functions call\n */\nconst generator = (jsonqlInstance, config, contract, ee) => {\n // V1.3.0 - now everything wrap inside this method\n let client = methodsGenerator(jsonqlInstance, ee, config, contract)\n // create the rest of the methods\n if (config.enableAuth) {\n /**\n * new method to allow retrieve the current login user data\n * @TODO allow to pass an id to switch to different userdata\n * @return {*} userdata\n */\n client.userdata = () => jsonqlInstance.jsonqlUserdata;\n // allow getting the token for valdiate agains the socket\n // if it's not require auth there is no point of calling getToken\n client.getToken = (idx = false) => jsonqlInstance.rawAuthToken(idx);\n // switch profile or read back what is the currenct index\n client.profileIndex = (idx = false) => {\n if (idx === false) {\n return jsonqlInstance.profileIndex\n }\n jsonqlInstance.profileIndex = idx\n }\n // new in 1.5.1 to return different profiles\n client.getProfiles = (idx = false) => jsonqlInstance.getProfiles(idx);\n }\n // this will pass to the ws-client if needed\n // client.eventEmitter = ee;\n // this will require a param\n if (config.exposeContract) {\n // 1.4.0 change from the get (raw) to the getContract cache and raw version\n client.getContract = () => jsonqlInstance.getContract()\n }\n // allow developer to access the store api\n if (config.exposeStore) {\n // @TODO in 1.5.2\n client.tmpSave = data => {}\n client.tmpGet = (key = false) => {}\n client.tmpDel = (key = false) => {}\n\n client.persistSave = data => {}\n client.persistGet = (key = false) => {}\n client.persistDel = (key = false) => {}\n }\n // this is for the ws to use later - but this could be dangerous because it's expose the internal\n client.eventEmitter = ee;\n client.version = '__VERSION__';\n // use this method then we can hook into the debugOn at the same time\n client.log = (...args) => Reflect.apply(jsonqlInstance.log, jsonqlInstance, ['[DEV DEBUG]'].concat(args))\n // output\n return client;\n}\n// export\nexport default generator\n","// all the client configuration options here\nimport {\n JSONQL_PATH,\n CONTENT_TYPE,\n BEARER,\n CLIENT_STORAGE_KEY,\n CLIENT_AUTH_KEY,\n CONTRACT_KEY_NAME,\n AUTH_HEADER,\n ISSUER_NAME,\n LOGOUT_NAME,\n BOOLEAN_TYPE,\n STRING_TYPE,\n NUMBER_TYPE,\n DEFAULT_HEADER\n} from 'jsonql-constants'\nimport { createConfig } from 'jsonql-params-validator'\nexport const constProps = {\n contract: false,\n MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong?\n CONTENT_TYPE,\n BEARER,\n AUTH_HEADER\n}\n\n// grab the localhost name and put into the hostname as default\nconst getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n return null\n }\n}\n\nexport const appProps = {\n\n hostname: createConfig(getHostName(), [STRING_TYPE]), // required the hostname\n jsonqlPath: createConfig(JSONQL_PATH, [STRING_TYPE]), // The path on the server\n\n loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]),\n logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]),\n // add to koa v1.3.0 - this might remove in the future\n enableJsonp: createConfig(false, [BOOLEAN_TYPE]),\n enableAuth: createConfig(false, [BOOLEAN_TYPE]),\n // enable useJwt by default @TODO replace with something else and remove them later\n useJwt: createConfig(true, [BOOLEAN_TYPE]),\n // when true then store infinity or pass a time in seconds then we check against\n // the token date of creation\n persistToken: createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE]),\n // the header\n // v1.2.0 we are using this option during the dev\n // so it won't save anything to the localstorage and fetch a new contract\n // whenever the browser reload\n useLocalstorage: createConfig(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage\n storageKey: createConfig(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage\n authKey: createConfig(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage\n contractExpired: createConfig(0, [NUMBER_TYPE]),// -1 always fetch contract,\n // 0 never expired,\n // > 0 then compare the timestamp with the current one to see if we need to get contract again\n // useful during development\n keepContract: createConfig(true, [BOOLEAN_TYPE]),\n exposeContract: createConfig(false, [BOOLEAN_TYPE]),\n exposeStore: createConfig(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn \n // @1.2.1 new option for the contract-console to fetch the contract with description\n showContractDesc: createConfig(false, [BOOLEAN_TYPE]),\n contractKey: createConfig(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this\n contractKeyName: createConfig(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs\n enableTimeout: createConfig(false, [BOOLEAN_TYPE]), // @TODO\n timeout: createConfig(5000, [NUMBER_TYPE]), // 5 seconds\n returnInstance: createConfig(false, [BOOLEAN_TYPE]),\n allowReturnRawToken: createConfig(false, [BOOLEAN_TYPE]),\n debugOn: createConfig(false, [BOOLEAN_TYPE])\n}\n","// we must ensure the user passing the correct options\n// therefore we need to validate against the properties as well\n\nimport { appProps, constProps } from './base-options'\nimport { checkConfigAsync } from 'jsonql-params-validator'\n\nexport default function checkOptionsAsync(config) {\n let { contract } = config;\n return checkConfigAsync(config, appProps, constProps)\n .then(opts => {\n opts.contract = contract;\n return opts;\n })\n}\n","// export interface\nimport checkOptionsAsyncLocal from './check-options-async'\nimport checkOptionsLocal from './check-options'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport { objHasProp } from 'jsonql-utils/src/obj-define-props'\n/**\n * 1.5.0 overload the orginal functions to pass over the check\n */\nfunction checkOptionsAsync(config) {\n return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsyncLocal(config)\n}\n\n// sync version without needing the promise\nfunction checkOptions(config) {\n return objHasProp(config, CHECKED_KEY) ? config : checkOptionsLocal(config)\n}\n\nexport {\n checkOptionsAsync,\n checkOptions\n}\n","// this is new for the flyio and normalize the name from now on\nimport JsonqlBaseClient from './base'\nimport generator from './core/jsonql-api-generator'\nimport { checkOptionsAsync } from './options'\nimport { getContractFromConfig } from './utils'\n\n/**\n * Main interface for jsonql fetch api\n * @param {object} ee EventEmitter\n * @param {object} config\n * @param {object} fly this is really pain in the backside ... long story\n * @return {object} jsonql client\n */\nexport default function(ee, config = {}, fly) {\n return checkOptionsAsync(config)\n .then(opts => (\n {\n baseClient: new JsonqlBaseClient(fly, opts),\n opts: opts\n }\n ))\n .then( ({baseClient, opts}) => (\n getContractFromConfig(baseClient, opts.contract)\n .then(contract => generator(baseClient, opts, contract, ee))\n )\n )\n}\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n\nexport default class SuspendClass {\n\n constructor() {\n // suspend, release and queue\n this.__suspend__ = null;\n this.queueStore = new Set()\n /*\n this.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n })\n */\n }\n\n /**\n * setter to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n set $suspend(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend__;\n this.__suspend__ = value;\n this.logger('($suspend)', `Change from ${lastValue} --> ${value}`)\n if (lastValue === true && value === false) {\n setTimeout(() => {\n this.release()\n }, 1)\n }\n } else {\n throw new Error(`$suspend only accept Boolean value!`)\n }\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {any} value\n * @return {Boolean} true when added or false when it's not\n */\n $queue(...args) {\n if (this.__suspend__ === true) {\n this.logger('($queue)', 'added to $queue', args)\n // there shouldn't be any duplicate ...\n this.queueStore.add(args)\n }\n return this.__suspend__;\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size;\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n release() {\n let size = this.queueStore.size\n this.logger('(release)', `Release was called ${size}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('queue', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport genHaskKey from './hash-code'\nimport SuspendClass from './suspend'\n\nexport default class NbEventServiceBase extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger;\n }\n this.keep = config.keep;\n // for the $done setter\n this.result = config.keep ? [] : null;\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (typeof e !== 'string') {\n this.logger('(validateEvt)', e)\n throw new Error(`event name must be string type!`)\n }\n })\n return true;\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n return true;\n }\n }\n throw new Error(`callback required to be function type!`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n const types = ['on', 'only', 'once', 'onlyOnce']\n return !!types.filter(t => type === t).length;\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run)', callback, payload, ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName]; // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger('(takeFromStore)', `has ${evt}`, content)\n store.delete(evt)\n return content;\n }\n return false;\n }\n throw new Error(`${storeName} is not supported!`)\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n let fnSet;\n if (store.has(evt)) {\n this.logger('(addToStore)', `${evt} existed`)\n fnSet = store.get(evt)\n } else {\n this.logger('(addToStore)', `create new Set for ${evt}`)\n // this is new\n fnSet = new Set()\n }\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args;\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger('(addToStore)', `insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(l => {\n let [hash,] = l;\n if (hash === args[0]) {\n return true;\n }\n return false;\n }).length;\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true;\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list;\n return type !== t;\n }).length;\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n this.logger('(checkTypeInLazyStore)', store)\n if (store) {\n return !!Array\n .from(store)\n .filter(l => {\n let [,,t] = l;\n return t !== type;\n }).length\n }\n return false;\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger('(addToNormalStore)', evt, type, 'try to add to normal store')\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n this.logger('(addToNormalStore)', `${type} can add to ${evt} normal store`)\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store;\n return size;\n }\n return false;\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store;\n return size;\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg];\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n return genHaskKey(fn.toString()) + '';\n }\n}\n","// The top level\nimport NbStoreService from './store-service'\n// export\nexport default class EventService extends NbStoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on';\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger('($on)', `${evt} callback is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger('($on)', `${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0;\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($on)`, `call run on ${evt}`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n return size;\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n const type = 'once';\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (lazyStoreContent === false) {\n this.logger('($once)', `${evt} not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, type, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger('($once)', `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'only';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($only)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($only)', `${evt} found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( l => {\n const [ payload, ctx, t ] = l;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($only)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n })\n }\n return added;\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD added in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'onlyOnce';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== 'onlyOnce') {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($onlyOnce)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added;\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {}\n */\n $replace(evt, callback, context = null, type = 'on') {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n this.logger(`($replace)`, evt, callback)\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0;\n // first check the normal store\n let nStore = this.normalStore;\n this.logger('($trigger)', 'normalStore', nStore)\n if (nStore.has(evt)) {\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n this.logger('($trigger)', evt, 'found; add to queue: ', added)\n if (added === true) {\n this.logger('($trigger)', evt, 'not executed. Exit now.')\n return false; // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length;\n let hasOnce = false;\n let hasOnly = false;\n for (let i=0; i < ctn; ++i) {\n ++found;\n // this.logger('found', found)\n let [ _, callback, ctx, type ] = nSet[i]\n this.logger(`($trigger)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n if (type === 'once' || type === 'onlyOnce') {\n hasOnce = true;\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found;\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found;\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter around\n * @param {string} evt event name\n * @param {*} params pass to the callback\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, params, type = false, context = null) {\n let args = [evt, params, context, type]\n return Reflect.apply(this.$trigger, this, args)\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n let found = false;\n stores.forEach(store => {\n if (store.has(evt)) {\n found = true;\n this.logger('($off)', evt)\n store.delete(evt)\n }\n })\n return found;\n }\n\n /**\n * return all the listener from the event\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n this.validateEvt(evt)\n let store = this.normalStore;\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l;\n }\n let [key, callback, ] = l;\n return callback;\n })\n }\n return false;\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done)', 'value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value;\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n if (this.keep) {\n this.logger('(get $done)', this.result)\n return this.result[this.result.length - 1]\n }\n return this.result;\n }\n\n\n}\n","// default\nimport NBEventService from './src/event-service'\n\nexport default NBEventService\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// output\nexport default function(debugOn) {\n let logger = debugOn ? (...args) => {\n args.unshift('[NBS]')\n console.log.apply(null, args)\n }: undefined;\n return new NBEventService({ logger })\n}\n","// main export interface\nimport {\n jsonqlAsync,\n ee as getEventEmitter\n} from './src'\n/**\n * When pass a static contract then it return a static interface\n * otherwise it will become the async interface\n * @param {object} fly the http engine - already init object not the class!\n * @param {object} config configuration\n * @return {object} jsonqlClient\n */\nexport default function jsonqlClient(fly, config) {\n const ee = getEventEmitter(config.debugOn)\n return jsonqlAsync(ee, config, fly)\n}\n","// this one will bring the fly.js in\n// also the built jsonql-client.umd.js together\n// init it @TODO placeholder this Fly import and switch using the NODE_ENV\n// because we are going to create one for wechat and one for node\n\nimport Fly from 'flyio/dist/npm/fly'\nimport jsonqlClient from './index'\n\nexport default function(config = {}) {\n return jsonqlClient(new Fly(), config)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/packages/http-client/package.json b/packages/http-client/package.json index 4316a7f1..a18ab2b8 100755 --- a/packages/http-client/package.json +++ b/packages/http-client/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-client", - "version": "1.5.1", + "version": "1.5.2", "description": "jsonql http browser client using Fly.js", "main": "core.js", "module": "index.js", diff --git a/packages/http-client/src/core/methods-generator.js b/packages/http-client/src/core/methods-generator.js index 72ac5cc9..dd6a0df3 100644 --- a/packages/http-client/src/core/methods-generator.js +++ b/packages/http-client/src/core/methods-generator.js @@ -28,7 +28,7 @@ const authMethodGenerator = (jsonqlInstance, name, opts, contract) => { .query .apply(jsonqlInstance, [name, values, header]) ) - // .catch(finalCatch) + .catch(finalCatch) } } @@ -59,7 +59,7 @@ const createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => { .query .apply(jsonqlInstance, [queryFn, _args, header]) ) - // .catch(finalCatch) + .catch(finalCatch) }) } obj.query = query; @@ -91,6 +91,7 @@ const createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => { .mutation .apply(jsonqlInstance, [mutationFn, payload, conditions, header]) ) + .catch(finalCatch) }) } obj.mutation = mutation; diff --git a/packages/http-client/tests/qunit/tests/base-test.js b/packages/http-client/tests/qunit/tests/base-test.js index 4b19b7ae..8f298060 100644 --- a/packages/http-client/tests/qunit/tests/base-test.js +++ b/packages/http-client/tests/qunit/tests/base-test.js @@ -31,7 +31,7 @@ QUnit.test('jsonqlClient should able to connect to server', function(assert) { .catch(err => { console.error(`--- NOT LOGIN ERROR ---`, err) // @NOTE this is a cheat because the finalCatch from jsonql-errors not always able to catch the correct error - assert.equal(err.className, 'JsonqlError', 'Not allow to call private method before login') + assert.equal(err.className, 'JsonqlForbiddenError', 'Not allow to call private method before login') done3() // test the login -- Gitee From c3d67f684277c556a452cd613b8c5143d3f93b70 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 19:08:44 +0800 Subject: [PATCH 7/7] jsonql-client to 1.5.2 --- packages/http-client/core.js | 2 +- packages/http-client/core.js.map | 2 +- .../http-client/dist/jsonql-client.static.js | 9574 +---------------- .../dist/jsonql-client.static.js.map | 2 +- .../http-client/dist/jsonql-client.umd.js | 9559 +--------------- .../http-client/dist/jsonql-client.umd.js.map | 2 +- packages/http-client/static.js | 2 +- packages/http-client/static.js.map | 2 +- 8 files changed, 8 insertions(+), 19137 deletions(-) diff --git a/packages/http-client/core.js b/packages/http-client/core.js index 89827d0c..821c888f 100644 --- a/packages/http-client/core.js +++ b/packages/http-client/core.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClient=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b=Array.isArray,_="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},m="object"==typeof _&&_&&_.Object===Object&&_,j="object"==typeof self&&self&&self.Object===Object&&self,w=m||j||Function("return this")(),S=w.Symbol,O=Object.prototype,k=O.hasOwnProperty,A=O.toString,E=S?S.toStringTag:void 0;var T=Object.prototype.toString;var x="[object Null]",P="[object Undefined]",q=S?S.toStringTag:void 0;function C(t){return null==t?void 0===t?P:x:q&&q in Object(t)?function(t){var e=k.call(t,E),r=t[E];try{t[E]=void 0;var n=!0}catch(t){}var o=A.call(t);return n&&(e?t[E]=r:delete t[E]),o}(t):function(t){return T.call(t)}(t)}function $(t,e){return function(r){return t(e(r))}}var z=$(Object.getPrototypeOf,Object);function N(t){return null!=t&&"object"==typeof t}var M="[object Object]",I=Function.prototype,R=Object.prototype,F=I.toString,J=R.hasOwnProperty,U=F.call(Object);function D(t){if(!N(t)||C(t)!=M)return!1;var e=z(t);if(null===e)return!0;var r=J.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&F.call(r)==U}function H(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&X(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var dt=function(t){return b(t)?t:[t]},vt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},gt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),yt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),bt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),_t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),mt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),xt=Object.freeze({__proto__:null,Jsonql406Error:gt,Jsonql500Error:yt,JsonqlForbiddenError:bt,JsonqlAuthorisationError:_t,JsonqlContractAuthError:mt,JsonqlResolverAppError:jt,JsonqlResolverNotFoundError:wt,JsonqlEnumError:St,JsonqlTypeError:Ot,JsonqlCheckerError:kt,JsonqlValidationError:At,JsonqlError:Et,JsonqlServerError:Tt}),Pt=Et,qt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function Ct(t){if(qt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&xt[o])throw new xt[r](i,a);throw new Pt(i,a)}return t}function $t(t){return!!function(t){return D(t)&&(vt(t,r)||vt(t,n)||vt(t,o))}(t)&&t}function zt(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var Nt=function(t,e){return void 0===e&&(e={}),$t(e)?Promise.resolve(e):t.getContract()},Mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function It(t){this.message=t}It.prototype=new Error,It.prototype.name="InvalidCharacterError";var Rt="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new It("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=Mt.indexOf(n);return a};var Ft=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Rt(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return Rt(e)}};function Jt(t){this.message=t}Jt.prototype=new Error,Jt.prototype.name="InvalidTokenError";var Ut=function(t,e){if("string"!=typeof t)throw new Jt("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(Ft(t.split(".")[r]))}catch(t){throw new Jt("Invalid token specified: "+t.message)}},Dt=Jt;Ut.InvalidTokenError=Dt;var Ht="[object String]";function Lt(t){return"string"==typeof t||!b(t)&&N(t)&&C(t)==Ht}var Bt=function(t){return""!==ht(t)&&Lt(t)},Kt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Gt(t){if(Bt(t))return function(t){var e=t.iat||Kt(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Et("Token has expired on "+r,t)}return t}(Ut(t));throw new Et("Token must be a string!")}var Vt=function(t){return!!b(t)||null!=t&&""!==ht(t)},Wt="[object Number]";function Yt(t){return function(t){return"number"==typeof t||N(t)&&C(t)==Wt}(t)&&t!=+t}var Qt=function(t){return!Lt(t)&&!Yt(parseFloat(t))},Xt=function(t){return null!=t&&"boolean"==typeof t},Zt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==ht(t)&&(!1===e||!0===e&&null!==t)},te=s,ee=f,re=l,ne=p,oe=h,ie=d,ae="continue",ue=function(t){switch(t){case"number":return Qt;case"string":return Bt;case"boolean":return Xt;default:return Zt}},ce=function(t,e){return void 0===e&&(e=""),!!b(t)&&(""===e||""===ht(e)||!(t.filter((function(t){return!ue(e)(t)})).length>0))},se=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},fe=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ue(e)(t)})).length)})).length:e.length>e.filter((function(t){return!ce(r,t)})).length};var le,pe=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[le?a:++n];if(!1===e(o[u],u,o))break}return t};var he="[object Arguments]";function de(t){return N(t)&&C(t)==he}var ve=Object.prototype,ge=ve.hasOwnProperty,ye=ve.propertyIsEnumerable,be=de(function(){return arguments}())?de:function(t){return N(t)&&ge.call(t,"callee")&&!ye.call(t,"callee")};var _e="object"==typeof exports&&exports&&!exports.nodeType&&exports,me=_e&&"object"==typeof module&&module&&!module.nodeType&&module,je=me&&me.exports===_e?w.Buffer:void 0,we=(je?je.isBuffer:void 0)||function(){return!1},Se=9007199254740991,Oe=/^(?:0|[1-9]\d*)$/;function ke(t,e){var r=typeof t;return!!(e=null==e?Se:e)&&("number"==r||"symbol"!=r&&Oe.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=Ae}var Te={};Te["[object Float32Array]"]=Te["[object Float64Array]"]=Te["[object Int8Array]"]=Te["[object Int16Array]"]=Te["[object Int32Array]"]=Te["[object Uint8Array]"]=Te["[object Uint8ClampedArray]"]=Te["[object Uint16Array]"]=Te["[object Uint32Array]"]=!0,Te["[object Arguments]"]=Te["[object Array]"]=Te["[object ArrayBuffer]"]=Te["[object Boolean]"]=Te["[object DataView]"]=Te["[object Date]"]=Te["[object Error]"]=Te["[object Function]"]=Te["[object Map]"]=Te["[object Number]"]=Te["[object Object]"]=Te["[object RegExp]"]=Te["[object Set]"]=Te["[object String]"]=Te["[object WeakMap]"]=!1;var xe,Pe="object"==typeof exports&&exports&&!exports.nodeType&&exports,qe=Pe&&"object"==typeof module&&module&&!module.nodeType&&module,Ce=qe&&qe.exports===Pe&&m.process,$e=function(){try{var t=qe&&qe.require&&qe.require("util").types;return t||Ce&&Ce.binding&&Ce.binding("util")}catch(t){}}(),ze=$e&&$e.isTypedArray,Ne=ze?(xe=ze,function(t){return xe(t)}):function(t){return N(t)&&Ee(t.length)&&!!Te[C(t)]},Me=Object.prototype.hasOwnProperty;function Ie(t,e){var r=b(t),n=!r&&be(t),o=!r&&!n&&we(t),i=!r&&!n&&!o&&Ne(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},tr.prototype.set=function(t,e){var r=this.__data__,n=Xe(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var er,rr=w["__core-js_shared__"],nr=(er=/[^.]+$/.exec(rr&&rr.keys&&rr.keys.IE_PROTO||""))?"Symbol(src)_1."+er:"";var or=Function.prototype.toString;function ir(t){if(null!=t){try{return or.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ar=/^\[object .+?Constructor\]$/,ur=Function.prototype,cr=Object.prototype,sr=ur.toString,fr=cr.hasOwnProperty,lr=RegExp("^"+sr.call(fr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function pr(t){return!(!De(t)||function(t){return!!nr&&nr in t}(t))&&(Ge(t)?lr:ar).test(ir(t))}function hr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return pr(r)?r:void 0}var dr=hr(w,"Map"),vr=hr(Object,"create");var gr="__lodash_hash_undefined__",yr=Object.prototype.hasOwnProperty;var br=Object.prototype.hasOwnProperty;var _r="__lodash_hash_undefined__";function mr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&xr?new Ar:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=se(t))?!fe({arg:r},e):!ue(t)(r))})).length)})).length}return!1},Yn=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Wn,null,a);case"array"===t:return!ce(e.arg);case!1!==(r=se(t)):return!fe(e,r);default:return!ue(t)(e.arg)}},Qn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Xn=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!ce(e))throw new Et("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!ce(t))throw new Et("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Qn(t,a):t,index:r,param:a,optional:i}}));default:throw new Et("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Vt(e)&&!(r.type.length>r.type.filter((function(e){return Yn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Yn(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Zn=function(){try{var t=hr(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function to(t,e,r){"__proto__"==e&&Zn?Zn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function eo(t,e,r){(void 0===r||Qe(t[e],r))&&(void 0!==r||e in t)||to(t,e,r)}var ro="object"==typeof exports&&exports&&!exports.nodeType&&exports,no=ro&&"object"==typeof module&&module&&!module.nodeType&&module,oo=no&&no.exports===ro?w.Buffer:void 0,io=oo?oo.allocUnsafe:void 0;function ao(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new qr(n).set(new qr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var uo=Object.create,co=function(){function t(){}return function(e){if(!De(e))return{};if(uo)return uo(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function so(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var fo=Object.prototype.hasOwnProperty;function lo(t,e,r){var n=t[e];fo.call(t,e)&&Qe(n,r)&&(void 0!==r||e in t)||to(t,e,r)}var po=Object.prototype.hasOwnProperty;function ho(t){if(!De(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Fe(t),r=[];for(var n in t)("constructor"!=n||!e&&po.call(t,n))&&r.push(n);return r}function vo(t){return Ve(t)?Ie(t,!0):ho(t)}function go(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=wo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(jo);function Ao(t,e){return ko(function(t,e,r){return e=mo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=mo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Eo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!De(r))return!1;var n=typeof e;return!!("number"==n?Ve(r)&&ke(e,r.length):"string"==n&&e in r)&&Qe(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=0;e--){var r=qi().key(e);t(Ci(r),r)}},remove:function(t){return qi().removeItem(t)},clearAll:function(){return qi().clear()}};function qi(){return xi.localStorage}function Ci(t){return qi().getItem(t)}var $i=hi.trim,zi={name:"cookieStorage",read:function(t){if(!t||!Ri(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Ni.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Ni.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Mi,remove:Ii,clearAll:function(){Mi((function(t,e){Ii(e)}))}},Ni=hi.Global.document;function Mi(t){for(var e=Ni.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if($i(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Ii(t){t&&Ri(t)&&(Ni.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Ri(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Ni.cookie)}var Fi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Ji=hi.bind,Ui=hi.each,Di=hi.create,Hi=hi.slice,Li=function(){var t=Di(Bi,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Ji(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Ji(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),Ui(r,(function(e,r){t.fire(r,void 0,e)}))}}};var Bi={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Ji(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Hi(arguments,1);Ui(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},Ki=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),Gi=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=Ki.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=Ki.compress(this._serialize(r));t(e,n)}}};var Vi=[Pi,zi],Wi=[Fi,Li,Gi],Yi=Ai.createStore(Vi,Wi),Qi=hi.Global;function Xi(){return Qi.sessionStorage}function Zi(t){return Xi().getItem(t)}var ta=[{name:"sessionStorage",read:Zi,write:function(t,e){return Xi().setItem(t,e)},each:function(t){for(var e=Xi().length-1;e>=0;e--){var r=Xi().key(e);t(Zi(r),r)}},remove:function(t){return Xi().removeItem(t)},clearAll:function(){return Xi().clear()}},zi],ea=[Fi,Gi],ra=Ai.createStore(ta,ea),na=Yi,oa=ra,ia=function(t){var e;return(e={}).args=t,e};function aa(t,e){var r;return(r={})[t]=e,r[u]=[ui()],r}var ua=function(t){return vt(t,"data")&&!vt(t,"error")?t.data:t},ca=function(t){this.opts=t,this.instanceKey=zt(this.opts.hostname)+"",this.localStore=na,this.sessionStore=oa},sa={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};ca.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?To({},o,e):e,r))},ca.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},ca.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},ca.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},sa.lset.set=function(t){return this.__setMethod("localStore",t)},sa.lget.get=function(){return this.__getMethod("localStore")},ca.prototype.ldel=function(t){return this.__delMethod("localStore",t)},ca.prototype.lclear=function(){return this.__clearMethod("localStore")},sa.sset.set=function(t){return this.__setMethod("sessionStore",t)},sa.sget.get=function(){return this.__getMethod("sessionStore")},ca.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},ca.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(ca.prototype,sa);var fa=c[0],la=c[1],pa=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Gt)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(ni(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new At("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&ni(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!$t(t))throw new At("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=$t(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=To({},{_cb:ui()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=To({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=To({},{method:fa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return ua(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=ri(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ua(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new Tt("Server side error",r)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?To({},e,this.getAuthHeader(),this.extraHeader):To({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=To({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(Ct).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new Tt("getRemoteContract",e)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Lt(t)&&b(e)){var n=ia(e);return!0===r?n:aa(t,n)}throw new At("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(Ct)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Lt(t))return aa(t,o);throw new At("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:la}).then(Ct)},Object.defineProperties(r.prototype,n),r}(ca)))),ha=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,dt(t))}),Reflect.apply(t,null,r))}};function da(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function va(t,e,r,n){void 0===n&&(n=!1);var o=da(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var ga=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return oi(r,i).then((function(){return t.query.apply(t,[e,a,u])}))}},ya=function(t,e,r,n,o){var i={},a=function(t){i=va(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return oi(a,i).then((function(){return e.query.apply(e,[t,a,u])}))}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},ba=function(t,e,r,n,o){var i={},a=function(t){i=va(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return oi(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])}))}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},_a=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ga(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ga(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var ma=function(t,e,r,n){var o=function(t,e,r,n){return ha(ya,ba,_a)({},t,e,r,n)}(t,n,e,r);return e.enableAuth&&(o.userdata=function(){return t.jsonqlUserdata},o.getToken=function(e){return void 0===e&&(e=!1),t.rawAuthToken(e)},o.profileIndex=function(e){if(void 0===e&&(e=!1),!1===e)return t.profileIndex;t.profileIndex=e},o.getProfiles=function(e){return void 0===e&&(e=!1),t.getProfiles(e)}),e.exposeContract&&(o.getContract=function(){return t.getContract()}),e.exposeStore&&(o.tmpSave=function(t){},o.tmpGet=function(t){},o.tmpDel=function(t){},o.persistSave=function(t){},o.persistGet=function(t){},o.persistDel=function(t){}),o.eventEmitter=n,o.version="1.5.1",o.log=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return Reflect.apply(t.log,t,["[DEV DEBUG]"].concat(e))},o},ja={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},wa={hostname:ii(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:ii("jsonql",["string"]),loginHandlerName:ii("login",["string"]),logoutHandlerName:ii("logout",["string"]),enableJsonp:ii(!1,["boolean"]),enableAuth:ii(!1,["boolean"]),useJwt:ii(!0,["boolean"]),persistToken:ii(!1,["boolean","number"]),useLocalstorage:ii(!0,["boolean"]),storageKey:ii("jsonqlstore",["string"]),authKey:ii("jsonqlauthkey",["string"]),contractExpired:ii(0,["number"]),keepContract:ii(!0,["boolean"]),exposeContract:ii(!1,["boolean"]),exposeStore:ii(!1,["boolean"]),showContractDesc:ii(!1,["boolean"]),contractKey:ii(!1,["boolean"]),contractKeyName:ii("X-JSONQL-CV-KEY",["string"]),enableTimeout:ii(!1,["boolean"]),timeout:ii(5e3,["number"]),returnInstance:ii(!1,["boolean"]),allowReturnRawToken:ii(!1,["boolean"]),debugOn:ii(!1,["boolean"])};function Sa(t){return da(t,v)?Promise.resolve(t):function(t){var e=t.contract;return ai(t,wa,ja).then((function(t){return t.contract=e,t}))}(t)}var Oa=new WeakMap,ka=new WeakMap,Aa=function(){this.__suspend__=null,this.queueStore=new Set},Ea={$suspend:{configurable:!0},$queues:{configurable:!0}};Ea.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Aa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ea.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Aa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Aa.prototype,Ea);var Ta=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Oa.set(this,t)},r.normalStore.get=function(){return Oa.get(this)},r.lazyStore.set=function(t){ka.set(this,t)},r.lazyStore.get=function(){return ka.get(this)},e.prototype.hashFnToKey=function(t){return zt(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Aa));return function(t,e){var r;return function(t,e,r){return void 0===e&&(e={}),Sa(e).then((function(t){return{baseClient:new pa(r,t),opts:t}})).then((function(e){var r=e.baseClient,n=e.opts;return Nt(r,n.contract).then((function(e){return ma(r,n,e,t)}))}))}((r=e.debugOn,new Ta({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),e,t)}})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClient=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b=Array.isArray,_="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},m="object"==typeof _&&_&&_.Object===Object&&_,w="object"==typeof self&&self&&self.Object===Object&&self,j=m||w||Function("return this")(),S=j.Symbol,O=Object.prototype,k=O.hasOwnProperty,A=O.toString,E=S?S.toStringTag:void 0;var T=Object.prototype.toString;var x="[object Null]",P="[object Undefined]",q=S?S.toStringTag:void 0;function C(t){return null==t?void 0===t?P:x:q&&q in Object(t)?function(t){var e=k.call(t,E),r=t[E];try{t[E]=void 0;var n=!0}catch(t){}var o=A.call(t);return n&&(e?t[E]=r:delete t[E]),o}(t):function(t){return T.call(t)}(t)}function $(t,e){return function(r){return t(e(r))}}var z=$(Object.getPrototypeOf,Object);function N(t){return null!=t&&"object"==typeof t}var M="[object Object]",I=Function.prototype,R=Object.prototype,F=I.toString,J=R.hasOwnProperty,U=F.call(Object);function D(t){if(!N(t)||C(t)!=M)return!1;var e=z(t);if(null===e)return!0;var r=J.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&F.call(r)==U}function H(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&X(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var dt=function(t){return b(t)?t:[t]},vt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},gt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),yt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),bt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),_t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),mt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),xt=Object.freeze({__proto__:null,Jsonql406Error:gt,Jsonql500Error:yt,JsonqlForbiddenError:bt,JsonqlAuthorisationError:_t,JsonqlContractAuthError:mt,JsonqlResolverAppError:wt,JsonqlResolverNotFoundError:jt,JsonqlEnumError:St,JsonqlTypeError:Ot,JsonqlCheckerError:kt,JsonqlValidationError:At,JsonqlError:Et,JsonqlServerError:Tt}),Pt=Et,qt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function Ct(t){if(qt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&xt[o])throw new xt[r](i,a);throw new Pt(i,a)}return t}function $t(t){if(Array.isArray(t))throw new At("",t);var e=t.message||y,r=t.detail||t;switch(!0){case t instanceof gt:throw new gt(e,r);case t instanceof yt:throw new yt(e,r);case t instanceof bt:throw new bt(e,r);case t instanceof _t:throw new _t(e,r);case t instanceof mt:throw new mt(e,r);case t instanceof wt:throw new wt(e,r);case t instanceof jt:throw new jt(e,r);case t instanceof St:throw new St(e,r);case t instanceof Ot:throw new Ot(e,r);case t instanceof kt:throw new kt(e,r);case t instanceof At:throw new At(e,r);case t instanceof Tt:throw new Tt(e,r);default:throw new Et(e,r)}}function zt(t){return!!function(t){return D(t)&&(vt(t,r)||vt(t,n)||vt(t,o))}(t)&&t}function Nt(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var Mt=function(t,e){return void 0===e&&(e={}),zt(e)?Promise.resolve(e):t.getContract()},It="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function Rt(t){this.message=t}Rt.prototype=new Error,Rt.prototype.name="InvalidCharacterError";var Ft="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new Rt("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=It.indexOf(n);return a};var Jt=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Ft(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return Ft(e)}};function Ut(t){this.message=t}Ut.prototype=new Error,Ut.prototype.name="InvalidTokenError";var Dt=function(t,e){if("string"!=typeof t)throw new Ut("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(Jt(t.split(".")[r]))}catch(t){throw new Ut("Invalid token specified: "+t.message)}},Ht=Ut;Dt.InvalidTokenError=Ht;var Lt="[object String]";function Bt(t){return"string"==typeof t||!b(t)&&N(t)&&C(t)==Lt}var Kt=function(t){return""!==ht(t)&&Bt(t)},Gt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Vt(t){if(Kt(t))return function(t){var e=t.iat||Gt(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Et("Token has expired on "+r,t)}return t}(Dt(t));throw new Et("Token must be a string!")}var Wt=function(t){return!!b(t)||null!=t&&""!==ht(t)},Yt="[object Number]";function Qt(t){return function(t){return"number"==typeof t||N(t)&&C(t)==Yt}(t)&&t!=+t}var Xt=function(t){return!Bt(t)&&!Qt(parseFloat(t))},Zt=function(t){return null!=t&&"boolean"==typeof t},te=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==ht(t)&&(!1===e||!0===e&&null!==t)},ee=s,re=f,ne=l,oe=p,ie=h,ae=d,ue="continue",ce=function(t){switch(t){case"number":return Xt;case"string":return Kt;case"boolean":return Zt;default:return te}},se=function(t,e){return void 0===e&&(e=""),!!b(t)&&(""===e||""===ht(e)||!(t.filter((function(t){return!ce(e)(t)})).length>0))},fe=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},le=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ce(e)(t)})).length)})).length:e.length>e.filter((function(t){return!se(r,t)})).length};var pe,he=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[pe?a:++n];if(!1===e(o[u],u,o))break}return t};var de="[object Arguments]";function ve(t){return N(t)&&C(t)==de}var ge=Object.prototype,ye=ge.hasOwnProperty,be=ge.propertyIsEnumerable,_e=ve(function(){return arguments}())?ve:function(t){return N(t)&&ye.call(t,"callee")&&!be.call(t,"callee")};var me="object"==typeof exports&&exports&&!exports.nodeType&&exports,we=me&&"object"==typeof module&&module&&!module.nodeType&&module,je=we&&we.exports===me?j.Buffer:void 0,Se=(je?je.isBuffer:void 0)||function(){return!1},Oe=9007199254740991,ke=/^(?:0|[1-9]\d*)$/;function Ae(t,e){var r=typeof t;return!!(e=null==e?Oe:e)&&("number"==r||"symbol"!=r&&ke.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=Ee}var xe={};xe["[object Float32Array]"]=xe["[object Float64Array]"]=xe["[object Int8Array]"]=xe["[object Int16Array]"]=xe["[object Int32Array]"]=xe["[object Uint8Array]"]=xe["[object Uint8ClampedArray]"]=xe["[object Uint16Array]"]=xe["[object Uint32Array]"]=!0,xe["[object Arguments]"]=xe["[object Array]"]=xe["[object ArrayBuffer]"]=xe["[object Boolean]"]=xe["[object DataView]"]=xe["[object Date]"]=xe["[object Error]"]=xe["[object Function]"]=xe["[object Map]"]=xe["[object Number]"]=xe["[object Object]"]=xe["[object RegExp]"]=xe["[object Set]"]=xe["[object String]"]=xe["[object WeakMap]"]=!1;var Pe,qe="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ce=qe&&"object"==typeof module&&module&&!module.nodeType&&module,$e=Ce&&Ce.exports===qe&&m.process,ze=function(){try{var t=Ce&&Ce.require&&Ce.require("util").types;return t||$e&&$e.binding&&$e.binding("util")}catch(t){}}(),Ne=ze&&ze.isTypedArray,Me=Ne?(Pe=Ne,function(t){return Pe(t)}):function(t){return N(t)&&Te(t.length)&&!!xe[C(t)]},Ie=Object.prototype.hasOwnProperty;function Re(t,e){var r=b(t),n=!r&&_e(t),o=!r&&!n&&Se(t),i=!r&&!n&&!o&&Me(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},er.prototype.set=function(t,e){var r=this.__data__,n=Ze(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var rr,nr=j["__core-js_shared__"],or=(rr=/[^.]+$/.exec(nr&&nr.keys&&nr.keys.IE_PROTO||""))?"Symbol(src)_1."+rr:"";var ir=Function.prototype.toString;function ar(t){if(null!=t){try{return ir.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ur=/^\[object .+?Constructor\]$/,cr=Function.prototype,sr=Object.prototype,fr=cr.toString,lr=sr.hasOwnProperty,pr=RegExp("^"+fr.call(lr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function hr(t){return!(!He(t)||function(t){return!!or&&or in t}(t))&&(Ve(t)?pr:ur).test(ar(t))}function dr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return hr(r)?r:void 0}var vr=dr(j,"Map"),gr=dr(Object,"create");var yr="__lodash_hash_undefined__",br=Object.prototype.hasOwnProperty;var _r=Object.prototype.hasOwnProperty;var mr="__lodash_hash_undefined__";function wr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&Pr?new Er:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=fe(t))?!le({arg:r},e):!ce(t)(r))})).length)})).length}return!1},Qn=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Yn,null,a);case"array"===t:return!se(e.arg);case!1!==(r=fe(t)):return!le(e,r);default:return!ce(t)(e.arg)}},Xn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Zn=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!se(e))throw new Et("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!se(t))throw new Et("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Xn(t,a):t,index:r,param:a,optional:i}}));default:throw new Et("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Wt(e)&&!(r.type.length>r.type.filter((function(e){return Qn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Qn(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},to=function(){try{var t=dr(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function eo(t,e,r){"__proto__"==e&&to?to(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function ro(t,e,r){(void 0===r||Xe(t[e],r))&&(void 0!==r||e in t)||eo(t,e,r)}var no="object"==typeof exports&&exports&&!exports.nodeType&&exports,oo=no&&"object"==typeof module&&module&&!module.nodeType&&module,io=oo&&oo.exports===no?j.Buffer:void 0,ao=io?io.allocUnsafe:void 0;function uo(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new Cr(n).set(new Cr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var co=Object.create,so=function(){function t(){}return function(e){if(!He(e))return{};if(co)return co(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function fo(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var lo=Object.prototype.hasOwnProperty;function po(t,e,r){var n=t[e];lo.call(t,e)&&Xe(n,r)&&(void 0!==r||e in t)||eo(t,e,r)}var ho=Object.prototype.hasOwnProperty;function vo(t){if(!He(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Je(t),r=[];for(var n in t)("constructor"!=n||!e&&ho.call(t,n))&&r.push(n);return r}function go(t){return We(t)?Re(t,!0):vo(t)}function yo(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=So)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(jo);function Eo(t,e){return Ao(function(t,e,r){return e=wo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=wo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=To.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!He(r))return!1;var n=typeof e;return!!("number"==n?We(r)&&Ae(e,r.length):"string"==n&&e in r)&&Xe(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=0;e--){var r=Ci().key(e);t($i(r),r)}},remove:function(t){return Ci().removeItem(t)},clearAll:function(){return Ci().clear()}};function Ci(){return Pi.localStorage}function $i(t){return Ci().getItem(t)}var zi=di.trim,Ni={name:"cookieStorage",read:function(t){if(!t||!Fi(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Mi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Mi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Ii,remove:Ri,clearAll:function(){Ii((function(t,e){Ri(e)}))}},Mi=di.Global.document;function Ii(t){for(var e=Mi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(zi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Ri(t){t&&Fi(t)&&(Mi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Fi(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Mi.cookie)}var Ji=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Ui=di.bind,Di=di.each,Hi=di.create,Li=di.slice,Bi=function(){var t=Hi(Ki,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Ui(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Ui(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),Di(r,(function(e,r){t.fire(r,void 0,e)}))}}};var Ki={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Ui(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Li(arguments,1);Di(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},Gi=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),Vi=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=Gi.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=Gi.compress(this._serialize(r));t(e,n)}}};var Wi=[qi,Ni],Yi=[Ji,Bi,Vi],Qi=Ei.createStore(Wi,Yi),Xi=di.Global;function Zi(){return Xi.sessionStorage}function ta(t){return Zi().getItem(t)}var ea=[{name:"sessionStorage",read:ta,write:function(t,e){return Zi().setItem(t,e)},each:function(t){for(var e=Zi().length-1;e>=0;e--){var r=Zi().key(e);t(ta(r),r)}},remove:function(t){return Zi().removeItem(t)},clearAll:function(){return Zi().clear()}},Ni],ra=[Ji,Vi],na=Ei.createStore(ea,ra),oa=Qi,ia=na,aa=function(t){var e;return(e={}).args=t,e};function ua(t,e){var r;return(r={})[t]=e,r[u]=[ci()],r}var ca=function(t){return vt(t,"data")&&!vt(t,"error")?t.data:t},sa=function(t){this.opts=t,this.instanceKey=Nt(this.opts.hostname)+"",this.localStore=oa,this.sessionStore=ia},fa={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};sa.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?xo({},o,e):e,r))},sa.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},sa.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},sa.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},fa.lset.set=function(t){return this.__setMethod("localStore",t)},fa.lget.get=function(){return this.__getMethod("localStore")},sa.prototype.ldel=function(t){return this.__delMethod("localStore",t)},sa.prototype.lclear=function(){return this.__clearMethod("localStore")},fa.sset.set=function(t){return this.__setMethod("sessionStore",t)},fa.sget.get=function(){return this.__getMethod("sessionStore")},sa.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},sa.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(sa.prototype,fa);var la=c[0],pa=c[1],ha=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Vt)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(oi(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new At("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&oi(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!zt(t))throw new At("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=zt(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=xo({},{_cb:ci()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=xo({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=xo({},{method:la,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return ca(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=ni(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ca(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new Tt("Server side error",r)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?xo({},e,this.getAuthHeader(),this.extraHeader):xo({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=xo({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(Ct).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new Tt("getRemoteContract",e)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Bt(t)&&b(e)){var n=aa(e);return!0===r?n:ua(t,n)}throw new At("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(Ct)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Bt(t))return ua(t,o);throw new At("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:pa}).then(Ct)},Object.defineProperties(r.prototype,n),r}(sa)))),da=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,dt(t))}),Reflect.apply(t,null,r))}};function va(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function ga(t,e,r,n){void 0===n&&(n=!1);var o=va(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var ya=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return ii(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch($t)}},ba=function(t,e,r,n,o){var i={},a=function(t){i=ga(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return ii(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch($t)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},_a=function(t,e,r,n,o){var i={},a=function(t){i=ga(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return ii(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch($t)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},ma=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ya(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=ya(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var wa=function(t,e,r,n){var o=function(t,e,r,n){return da(ba,_a,ma)({},t,e,r,n)}(t,n,e,r);return e.enableAuth&&(o.userdata=function(){return t.jsonqlUserdata},o.getToken=function(e){return void 0===e&&(e=!1),t.rawAuthToken(e)},o.profileIndex=function(e){if(void 0===e&&(e=!1),!1===e)return t.profileIndex;t.profileIndex=e},o.getProfiles=function(e){return void 0===e&&(e=!1),t.getProfiles(e)}),e.exposeContract&&(o.getContract=function(){return t.getContract()}),e.exposeStore&&(o.tmpSave=function(t){},o.tmpGet=function(t){},o.tmpDel=function(t){},o.persistSave=function(t){},o.persistGet=function(t){},o.persistDel=function(t){}),o.eventEmitter=n,o.version="1.5.2",o.log=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return Reflect.apply(t.log,t,["[DEV DEBUG]"].concat(e))},o},ja={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Sa={hostname:ai(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:ai("jsonql",["string"]),loginHandlerName:ai("login",["string"]),logoutHandlerName:ai("logout",["string"]),enableJsonp:ai(!1,["boolean"]),enableAuth:ai(!1,["boolean"]),useJwt:ai(!0,["boolean"]),persistToken:ai(!1,["boolean","number"]),useLocalstorage:ai(!0,["boolean"]),storageKey:ai("jsonqlstore",["string"]),authKey:ai("jsonqlauthkey",["string"]),contractExpired:ai(0,["number"]),keepContract:ai(!0,["boolean"]),exposeContract:ai(!1,["boolean"]),exposeStore:ai(!1,["boolean"]),showContractDesc:ai(!1,["boolean"]),contractKey:ai(!1,["boolean"]),contractKeyName:ai("X-JSONQL-CV-KEY",["string"]),enableTimeout:ai(!1,["boolean"]),timeout:ai(5e3,["number"]),returnInstance:ai(!1,["boolean"]),allowReturnRawToken:ai(!1,["boolean"]),debugOn:ai(!1,["boolean"])};function Oa(t){return va(t,v)?Promise.resolve(t):function(t){var e=t.contract;return ui(t,Sa,ja).then((function(t){return t.contract=e,t}))}(t)}var ka=new WeakMap,Aa=new WeakMap,Ea=function(){this.__suspend__=null,this.queueStore=new Set},Ta={$suspend:{configurable:!0},$queues:{configurable:!0}};Ta.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Ea.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ta.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Ea.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Ea.prototype,Ta);var xa=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){ka.set(this,t)},r.normalStore.get=function(){return ka.get(this)},r.lazyStore.set=function(t){Aa.set(this,t)},r.lazyStore.get=function(){return Aa.get(this)},e.prototype.hashFnToKey=function(t){return Nt(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Ea));return function(t,e){var r;return function(t,e,r){return void 0===e&&(e={}),Oa(e).then((function(t){return{baseClient:new ha(r,t),opts:t}})).then((function(e){var r=e.baseClient,n=e.opts;return Mt(r,n.contract).then((function(e){return wa(r,n,e,t)}))}))}((r=e.debugOn,new xa({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),e,t)}})); //# sourceMappingURL=core.js.map diff --git a/packages/http-client/core.js.map b/packages/http-client/core.js.map index 134a4298..f2826e84 100644 --- a/packages/http-client/core.js.map +++ b/packages/http-client/core.js.map @@ -1 +1 @@ -{"version":3,"file":"core.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"i0vCAAA"} \ No newline at end of file +{"version":3,"file":"core.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"k5wCAAA"} \ No newline at end of file diff --git a/packages/http-client/dist/jsonql-client.static.js b/packages/http-client/dist/jsonql-client.static.js index 9aa41f4a..dacebcea 100644 --- a/packages/http-client/dist/jsonql-client.static.js +++ b/packages/http-client/dist/jsonql-client.static.js @@ -1,9574 +1,2 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = global || self, global.jsonqlClientStatic = factory()); -}(this, (function () { 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var fly = createCommonjsModule(function (module, exports) { - (function webpackUniversalModuleDefinition(root, factory) { - { module.exports = factory(); } - })(commonjsGlobal, function() { - return /******/ (function(modules) { // webpackBootstrap - /******/ // The module cache - /******/ var installedModules = {}; - /******/ - /******/ // The require function - /******/ function __webpack_require__(moduleId) { - /******/ - /******/ // Check if module is in cache - /******/ if(installedModules[moduleId]) { - /******/ return installedModules[moduleId].exports; - /******/ } - /******/ // Create a new module (and put it into the cache) - /******/ var module = installedModules[moduleId] = { - /******/ i: moduleId, - /******/ l: false, - /******/ exports: {} - /******/ }; - /******/ - /******/ // Execute the module function - /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - /******/ - /******/ // Flag the module as loaded - /******/ module.l = true; - /******/ - /******/ // Return the exports of the module - /******/ return module.exports; - /******/ } - /******/ - /******/ - /******/ // expose the modules object (__webpack_modules__) - /******/ __webpack_require__.m = modules; - /******/ - /******/ // expose the module cache - /******/ __webpack_require__.c = installedModules; - /******/ - /******/ // identity function for calling harmony imports with the correct context - /******/ __webpack_require__.i = function(value) { return value; }; - /******/ - /******/ // define getter function for harmony exports - /******/ __webpack_require__.d = function(exports, name, getter) { - /******/ if(!__webpack_require__.o(exports, name)) { - /******/ Object.defineProperty(exports, name, { - /******/ configurable: false, - /******/ enumerable: true, - /******/ get: getter - /******/ }); - /******/ } - /******/ }; - /******/ - /******/ // getDefaultExport function for compatibility with non-harmony modules - /******/ __webpack_require__.n = function(module) { - /******/ var getter = module && module.__esModule ? - /******/ function getDefault() { return module['default']; } : - /******/ function getModuleExports() { return module; }; - /******/ __webpack_require__.d(getter, 'a', getter); - /******/ return getter; - /******/ }; - /******/ - /******/ // Object.prototype.hasOwnProperty.call - /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; - /******/ - /******/ // __webpack_public_path__ - /******/ __webpack_require__.p = ""; - /******/ - /******/ // Load entry module and return exports - /******/ return __webpack_require__(__webpack_require__.s = 2); - /******/ }) - /************************************************************************/ - /******/ ([ - /* 0 */ - /***/ (function(module, exports, __webpack_require__) { - - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - module.exports = { - type: function type(ob) { - return Object.prototype.toString.call(ob).slice(8, -1).toLowerCase(); - }, - isObject: function isObject(ob, real) { - if (real) { - return this.type(ob) === "object"; - } else { - return ob && (typeof ob === 'undefined' ? 'undefined' : _typeof(ob)) === 'object'; - } - }, - isFormData: function isFormData(val) { - return typeof FormData !== 'undefined' && val instanceof FormData; - }, - trim: function trim(str) { - return str.replace(/(^\s*)|(\s*$)/g, ''); - }, - encode: function encode(val) { - return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); - }, - formatParams: function formatParams(data) { - var str = ""; - var first = true; - var that = this; - if (!this.isObject(data)) { - return data; - } - - function _encode(sub, path) { - var encode = that.encode; - var type = that.type(sub); - if (type == "array") { - sub.forEach(function (e, i) { - if (!that.isObject(e)) { i = ""; } - _encode(e, path + ('%5B' + i + '%5D')); - }); - } else if (type == "object") { - for (var key in sub) { - if (path) { - _encode(sub[key], path + "%5B" + encode(key) + "%5D"); - } else { - _encode(sub[key], encode(key)); - } - } - } else { - if (!first) { - str += "&"; - } - first = false; - str += path + "=" + encode(sub); - } - } - - _encode(data, ""); - return str; - }, - - // Do not overwrite existing attributes - merge: function merge(a, b) { - for (var key in b) { - if (!a.hasOwnProperty(key)) { - a[key] = b[key]; - } else if (this.isObject(b[key], 1) && this.isObject(a[key], 1)) { - this.merge(a[key], b[key]); - } - } - return a; - } - }; - - /***/ }), - /* 1 */, - /* 2 */ - /***/ (function(module, exports, __webpack_require__) { - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - var utils = __webpack_require__(0); - var isBrowser = typeof document !== "undefined"; - - var Fly = function () { - function Fly(engine) { - _classCallCheck(this, Fly); - - this.engine = engine || XMLHttpRequest; - - this.default = this; //For typeScript - - /** - * Add lock/unlock API for interceptor. - * - * Once an request/response interceptor is locked, the incoming request/response - * will be added to a queue before they enter the interceptor, they will not be - * continued until the interceptor is unlocked. - * - * @param [interceptor] either is interceptors.request or interceptors.response - */ - function wrap(interceptor) { - var resolve = void 0; - var reject = void 0; - - function _clear() { - interceptor.p = resolve = reject = null; - } - - utils.merge(interceptor, { - lock: function lock() { - if (!resolve) { - interceptor.p = new Promise(function (_resolve, _reject) { - resolve = _resolve; - reject = _reject; - }); - } - }, - unlock: function unlock() { - if (resolve) { - resolve(); - _clear(); - } - }, - clear: function clear() { - if (reject) { - reject("cancel"); - _clear(); - } - } - }); - } - - var interceptors = this.interceptors = { - response: { - use: function use(handler, onerror) { - this.handler = handler; - this.onerror = onerror; - } - }, - request: { - use: function use(handler) { - this.handler = handler; - } - } - }; - - var irq = interceptors.request; - var irp = interceptors.response; - wrap(irp); - wrap(irq); - - this.config = { - method: "GET", - baseURL: "", - headers: {}, - timeout: 0, - params: {}, // Default Url params - parseJson: true, // Convert response data to JSON object automatically. - withCredentials: false - }; - } - - _createClass(Fly, [{ - key: "request", - value: function request(url, data, options) { - var _this = this; - - var engine = new this.engine(); - var contentType = "Content-Type"; - var contentTypeLowerCase = contentType.toLowerCase(); - var interceptors = this.interceptors; - var requestInterceptor = interceptors.request; - var responseInterceptor = interceptors.response; - var requestInterceptorHandler = requestInterceptor.handler; - var promise = new Promise(function (resolve, reject) { - if (utils.isObject(url)) { - options = url; - url = options.url; - } - options = options || {}; - options.headers = options.headers || {}; - - function isPromise(p) { - // some polyfill implementation of Promise may be not standard, - // so, we test by duck-typing - return p && p.then && p.catch; - } - - /** - * If the request/response interceptor has been locked, - * the new request/response will enter a queue. otherwise, it will be performed directly. - * @param [promise] if the promise exist, means the interceptor is locked. - * @param [callback] - */ - function enqueueIfLocked(promise, callback) { - if (promise) { - promise.then(function () { - callback(); - }); - } else { - callback(); - } - } - - // make the http request - function makeRequest(options) { - data = options.body; - // Normalize the request url - url = utils.trim(options.url); - var baseUrl = utils.trim(options.baseURL || ""); - if (!url && isBrowser && !baseUrl) { url = location.href; } - if (url.indexOf("http") !== 0) { - var isAbsolute = url[0] === "/"; - if (!baseUrl && isBrowser) { - var arr = location.pathname.split("/"); - arr.pop(); - baseUrl = location.protocol + "//" + location.host + (isAbsolute ? "" : arr.join("/")); - } - if (baseUrl[baseUrl.length - 1] !== "/") { - baseUrl += "/"; - } - url = baseUrl + (isAbsolute ? url.substr(1) : url); - if (isBrowser) { - - // Normalize the url which contains the ".." or ".", such as - // "http://xx.com/aa/bb/../../xx" to "http://xx.com/xx" . - var t = document.createElement("a"); - t.href = url; - url = t.href; - } - } - - var responseType = utils.trim(options.responseType || ""); - var needQuery = ["GET", "HEAD", "DELETE", "OPTION"].indexOf(options.method) !== -1; - var dataType = utils.type(data); - var params = options.params || {}; - - // merge url params when the method is "GET" (data is object) - if (needQuery && dataType === "object") { - params = utils.merge(data, params); - } - // encode params to String - params = utils.formatParams(params); - - // save url params - var _params = []; - if (params) { - _params.push(params); - } - // Add data to url params when the method is "GET" (data is String) - if (needQuery && data && dataType === "string") { - _params.push(data); - } - - // make the final url - if (_params.length > 0) { - url += (url.indexOf("?") === -1 ? "?" : "&") + _params.join("&"); - } - - engine.open(options.method, url); - - // try catch for ie >=9 - try { - engine.withCredentials = !!options.withCredentials; - engine.timeout = options.timeout || 0; - if (responseType !== "stream") { - engine.responseType = responseType; - } - } catch (e) {} - - var customContentType = options.headers[contentType] || options.headers[contentTypeLowerCase]; - - // default content type - var _contentType = "application/x-www-form-urlencoded"; - // If the request data is json object, transforming it to json string, - // and set request content-type to "json". In browser, the data will - // be sent as RequestBody instead of FormData - if (utils.trim((customContentType || "").toLowerCase()) === _contentType) { - data = utils.formatParams(data); - } else if (!utils.isFormData(data) && ["object", "array"].indexOf(utils.type(data)) !== -1) { - _contentType = 'application/json;charset=utf-8'; - data = JSON.stringify(data); - } - //If user doesn't set content-type, set default. - if (!(customContentType || needQuery)) { - options.headers[contentType] = _contentType; - } - - for (var k in options.headers) { - if (k === contentType && utils.isFormData(data)) { - // Delete the content-type, Let the browser set it - delete options.headers[k]; - } else { - try { - // In browser environment, some header fields are readonly, - // write will cause the exception . - engine.setRequestHeader(k, options.headers[k]); - } catch (e) {} - } - } - - function onresult(handler, data, type) { - enqueueIfLocked(responseInterceptor.p, function () { - if (handler) { - //如果失败,添加请求信息 - if (type) { - data.request = options; - } - var ret = handler.call(responseInterceptor, data, Promise); - data = ret === undefined ? data : ret; - } - if (!isPromise(data)) { - data = Promise[type === 0 ? "resolve" : "reject"](data); - } - data.then(function (d) { - resolve(d); - }).catch(function (e) { - reject(e); - }); - }); - } - - function onerror(e) { - e.engine = engine; - onresult(responseInterceptor.onerror, e, -1); - } - - function Err(msg, status) { - this.message = msg; - this.status = status; - } - - engine.onload = function () { - try { - // The xhr of IE9 has not response field - var response = engine.response || engine.responseText; - if (response && options.parseJson && (engine.getResponseHeader(contentType) || "").indexOf("json") !== -1 - // Some third engine implementation may transform the response text to json object automatically, - // so we should test the type of response before transforming it - && !utils.isObject(response)) { - response = JSON.parse(response); - } - - var headers = engine.responseHeaders; - // In browser - if (!headers) { - headers = {}; - var items = (engine.getAllResponseHeaders() || "").split("\r\n"); - items.pop(); - items.forEach(function (e) { - if (!e) { return; } - var key = e.split(":")[0]; - headers[key] = engine.getResponseHeader(key); - }); - } - var status = engine.status; - var statusText = engine.statusText; - var _data = { data: response, headers: headers, status: status, statusText: statusText }; - // The _response filed of engine is set in adapter which be called in engine-wrapper.js - utils.merge(_data, engine._response); - if (status >= 200 && status < 300 || status === 304) { - _data.engine = engine; - _data.request = options; - onresult(responseInterceptor.handler, _data, 0); - } else { - var e = new Err(statusText, status); - e.response = _data; - onerror(e); - } - } catch (e) { - onerror(new Err(e.msg, engine.status)); - } - }; - - engine.onerror = function (e) { - onerror(new Err(e.msg || "Network Error", 0)); - }; - - engine.ontimeout = function () { - onerror(new Err("timeout [ " + engine.timeout + "ms ]", 1)); - }; - engine._options = options; - setTimeout(function () { - engine.send(needQuery ? null : data); - }, 0); - } - - enqueueIfLocked(requestInterceptor.p, function () { - utils.merge(options, JSON.parse(JSON.stringify(_this.config))); - var headers = options.headers; - headers[contentType] = headers[contentType] || headers[contentTypeLowerCase] || ""; - delete headers[contentTypeLowerCase]; - options.body = data || options.body; - url = utils.trim(url || ""); - options.method = options.method.toUpperCase(); - options.url = url; - var ret = options; - if (requestInterceptorHandler) { - ret = requestInterceptorHandler.call(requestInterceptor, options, Promise) || options; - } - if (!isPromise(ret)) { - ret = Promise.resolve(ret); - } - ret.then(function (d) { - //if options continue - if (d === options) { - makeRequest(d); - } else { - resolve(d); - } - }, function (err) { - reject(err); - }); - }); - }); - promise.engine = engine; - return promise; - } - }, { - key: "all", - value: function all(promises) { - return Promise.all(promises); - } - }, { - key: "spread", - value: function spread(callback) { - return function (arr) { - return callback.apply(null, arr); - }; - } - }]); - - return Fly; - }(); - - //For typeScript - - - Fly.default = Fly; - - ["get", "post", "put", "patch", "head", "delete"].forEach(function (e) { - Fly.prototype[e] = function (url, data, option) { - return this.request(url, data, utils.merge({ method: e }, option)); - }; - }); - ["lock", "unlock", "clear"].forEach(function (e) { - Fly.prototype[e] = function () { - this.interceptors.request[e](); - }; - }); - module.exports = Fly; - - /***/ }) - /******/ ]); - }); - }); - - var Fly = unwrapExports(fly); - - // the core stuff to id if it's calling with jsonql - var DATA_KEY = 'data'; - var ERROR_KEY = 'error'; - - var JSONQL_PATH = 'jsonql'; - // according to the json query spec - var CONTENT_TYPE = 'application/vnd.api+json'; - var CHARSET = 'charset=utf-8'; - var DEFAULT_HEADER = { - 'Accept': CONTENT_TYPE, - 'Content-Type': [ CONTENT_TYPE, CHARSET ].join(';') - }; - - // export const INDEX = 'index'; use INDEX_KEY instead - var DEFAULT_TYPE = 'any'; - - // @TODO remove this is not in use - // export const CLIENT_CONFIG_FILE = '.clients.json'; - // export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js'; - // type of resolvers - var QUERY_NAME = 'query'; - var MUTATION_NAME = 'mutation'; - var SOCKET_NAME = 'socket'; - // for calling the mutation - var PAYLOAD_PARAM_NAME = 'payload'; // @TODO shortern them - var CONDITION_PARAM_NAME = 'condition'; - var QUERY_ARG_NAME = 'args'; - var TIMESTAMP_PARAM_NAME = 'TS'; - // new jsonp - var JSONP_CALLBACK_NAME = 'jsonqlJsonpCallback'; - - // methods allow - var API_REQUEST_METHODS = ['POST', 'PUT']; - // for contract-cli - var KEY_WORD = 'continue'; - - var TYPE_KEY = 'type'; - var OPTIONAL_KEY = 'optional'; - var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word - var ARGS_KEY = 'args'; - var CHECKER_KEY = 'checker'; - var ALIAS_KEY = 'alias'; - var CHECKED_KEY = '__checked__'; - var LOGIN_NAME = 'login'; - var ISSUER_NAME = LOGIN_NAME; // legacy issue need to replace them later - var LOGOUT_NAME = 'logout'; - - var AUTH_HEADER = 'Authorization'; - var BEARER = 'Bearer'; - - // for client use @TODO need to clean this up some of them are not in use - var CREDENTIAL_STORAGE_KEY = 'jsonqlcredential'; - var CLIENT_STORAGE_KEY = 'jsonqlstore'; - var CLIENT_AUTH_KEY = 'jsonqlauthkey'; - // contract key - var CONTRACT_KEY_NAME = 'X-JSONQL-CV-KEY'; - var SHOW_CONTRACT_DESC_PARAM = {desc: 'y'}; - - var OR_SEPERATOR = '|'; - - var STRING_TYPE = 'string'; - var BOOLEAN_TYPE = 'boolean'; - var ARRAY_TYPE = 'array'; - var OBJECT_TYPE = 'object'; - - var NUMBER_TYPE = 'number'; - var ARRAY_TYPE_LFT = 'array.<'; - var ARRAY_TYPE_RGT = '>'; - - var NO_ERROR_MSG = 'No message'; - var NO_STATUS_CODE = -1; - var ON_RESULT_PROP_NAME = 'onResult'; - var ON_ERROR_PROP_NAME = 'onError'; - var HSA_ALGO = 'HS256'; - - /** - * 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; - - 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$1 = root.Symbol; - - /** 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$1 ? Symbol$1.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$1 ? Symbol$1.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); - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** Built-in value references. */ - var getPrototype = overArg(Object.getPrototypeOf, Object); - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @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 objectTag = '[object Object]'; - - /** Used for built-in method references. */ - var funcProto = Function.prototype, - objectProto$2 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty$1.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; - } - - /** - * 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; - } - - /** `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$1 ? Symbol$1.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(''); - } - - // bunch of generic helpers - - /** - * DIY in Array - * @param {array} arr to check from - * @param {*} value to check against - * @return {boolean} true on found - */ - var inArray = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; - - // quick and dirty to turn non array to array - var toArray = function (arg) { return isArray(arg) ? arg : [arg]; }; - - /** - * @param {object} obj for search - * @param {string} key target - * @return {boolean} true on success - */ - var isObjectHasKey = function(obj, key) { - try { - var keys = Object.keys(obj); - return inArray(keys, key) - } catch(e) { - // @BUG when the obj is not an OBJECT we got some weird output - return false; - /* - console.info('obj', obj) - console.error(e) - throw new Error(e) - */ - } - }; - - /** - * create a event name - * @param {string[]} args - * @return {string} event name for use - */ - var createEvt = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return args.join('_'); - }; - - /** - * This is a custom error to throw when server throw a 406 - * 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 Jsonql406Error = /*@__PURE__*/(function (Error) { - function Jsonql406Error() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - // We can't access the static name from an instance - // but we can do it like this - this.className = Jsonql406Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql406Error); - } - } - - if ( Error ) Jsonql406Error.__proto__ = Error; - Jsonql406Error.prototype = Object.create( Error && Error.prototype ); - Jsonql406Error.prototype.constructor = Jsonql406Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 406; - }; - - staticAccessors.name.get = function () { - return 'Jsonql406Error'; - }; - - Object.defineProperties( Jsonql406Error, staticAccessors ); - - return Jsonql406Error; - }(Error)); - - /** - * This is a custom error to throw when server throw a 500 - * 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 Jsonql500Error = /*@__PURE__*/(function (Error) { - function Jsonql500Error() { - 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 = Jsonql500Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql500Error); - } - } - - if ( Error ) Jsonql500Error.__proto__ = Error; - Jsonql500Error.prototype = Object.create( Error && Error.prototype ); - Jsonql500Error.prototype.constructor = Jsonql500Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'Jsonql500Error'; - }; - - Object.defineProperties( Jsonql500Error, staticAccessors ); - - return Jsonql500Error; - }(Error)); - - /** - * this is the 403 Forbidden error - * that means this user is not login - * use the 401 for try to login and failed - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlForbiddenError = /*@__PURE__*/(function (Error) { - function JsonqlForbiddenError() { - 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 = JsonqlForbiddenError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlForbiddenError); - } - } - - if ( Error ) JsonqlForbiddenError.__proto__ = Error; - JsonqlForbiddenError.prototype = Object.create( Error && Error.prototype ); - JsonqlForbiddenError.prototype.constructor = JsonqlForbiddenError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 403; - }; - - staticAccessors.name.get = function () { - return 'JsonqlForbiddenError'; - }; - - Object.defineProperties( JsonqlForbiddenError, staticAccessors ); - - return JsonqlForbiddenError; - }(Error)); - - /** - * This is a custom error to throw when pass credential but fail - * 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 JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { - function JsonqlAuthorisationError() { - 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 = JsonqlAuthorisationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlAuthorisationError); - } - } - - if ( Error ) JsonqlAuthorisationError.__proto__ = Error; - JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); - JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlAuthorisationError'; - }; - - Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); - - return JsonqlAuthorisationError; - }(Error)); - - /** - * This is a custom error when not supply the credential and try to get contract - * 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 JsonqlContractAuthError = /*@__PURE__*/(function (Error) { - function JsonqlContractAuthError() { - 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 = JsonqlContractAuthError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlContractAuthError); - } - } - - if ( Error ) JsonqlContractAuthError.__proto__ = Error; - JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); - JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlContractAuthError'; - }; - - Object.defineProperties( JsonqlContractAuthError, staticAccessors ); - - return JsonqlContractAuthError; - }(Error)); - - /** - * This is a custom error to throw when the resolver throw error and capture inside the middleware - * 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 JsonqlResolverAppError = /*@__PURE__*/(function (Error) { - function JsonqlResolverAppError() { - 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 = JsonqlResolverAppError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverAppError); - } - } - - if ( Error ) JsonqlResolverAppError.__proto__ = Error; - JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverAppError'; - }; - - Object.defineProperties( JsonqlResolverAppError, staticAccessors ); - - return JsonqlResolverAppError; - }(Error)); - - /** - * This is a custom error to throw when could not find the resolver - * 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 JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { - function JsonqlResolverNotFoundError() { - 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 = JsonqlResolverNotFoundError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverNotFoundError); - } - } - - if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; - JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 404; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverNotFoundError'; - }; - - Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); - - return JsonqlResolverNotFoundError; - }(Error)); - - // this get throw from within the checkOptions when run through the enum failed - var JsonqlEnumError = /*@__PURE__*/(function (Error) { - function JsonqlEnumError() { - 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 = JsonqlEnumError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlEnumError); - } - } - - if ( Error ) JsonqlEnumError.__proto__ = Error; - JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); - JsonqlEnumError.prototype.constructor = JsonqlEnumError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlEnumError'; - }; - - Object.defineProperties( JsonqlEnumError, staticAccessors ); - - return JsonqlEnumError; - }(Error)); - - // this will throw from inside the checkOptions - var JsonqlTypeError = /*@__PURE__*/(function (Error) { - function JsonqlTypeError() { - 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 = JsonqlTypeError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlTypeError); - } - } - - if ( Error ) JsonqlTypeError.__proto__ = Error; - JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); - JsonqlTypeError.prototype.constructor = JsonqlTypeError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlTypeError'; - }; - - Object.defineProperties( JsonqlTypeError, staticAccessors ); - - return JsonqlTypeError; - }(Error)); - - // allow supply a custom checker function - // if that failed then we throw this error - var JsonqlCheckerError = /*@__PURE__*/(function (Error) { - function JsonqlCheckerError() { - 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 = JsonqlCheckerError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlCheckerError); - } - } - - if ( Error ) JsonqlCheckerError.__proto__ = Error; - JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); - JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlCheckerError'; - }; - - Object.defineProperties( JsonqlCheckerError, staticAccessors ); - - return JsonqlCheckerError; - }(Error)); - - // custom validation error class - // when validaton failed - var JsonqlValidationError = /*@__PURE__*/(function (Error) { - function JsonqlValidationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlValidationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlValidationError); - } - } - - if ( Error ) JsonqlValidationError.__proto__ = Error; - JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); - JsonqlValidationError.prototype.constructor = JsonqlValidationError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlValidationError'; - }; - - Object.defineProperties( JsonqlValidationError, staticAccessors ); - - return JsonqlValidationError; - }(Error)); - - /** - * This is a custom error to throw whenever a error happen inside the jsonql - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlError = /*@__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)); - - // this is from an example from Koa team to use for internal middleware ctx.throw - // but after the test the res.body part is unable to extract the required data - // I keep this one here for future reference - - var JsonqlServerError = /*@__PURE__*/(function (Error) { - function JsonqlServerError(statusCode, message) { - Error.call(this, message); - this.statusCode = statusCode; - this.className = JsonqlServerError.name; - } - - if ( Error ) JsonqlServerError.__proto__ = Error; - JsonqlServerError.prototype = Object.create( Error && Error.prototype ); - JsonqlServerError.prototype.constructor = JsonqlServerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlServerError'; - }; - - Object.defineProperties( JsonqlServerError, staticAccessors ); - - return JsonqlServerError; - }(Error)); - - // server side - - var errors = /*#__PURE__*/Object.freeze({ - __proto__: null, - Jsonql406Error: Jsonql406Error, - Jsonql500Error: Jsonql500Error, - JsonqlForbiddenError: JsonqlForbiddenError, - JsonqlAuthorisationError: JsonqlAuthorisationError, - JsonqlContractAuthError: JsonqlContractAuthError, - JsonqlResolverAppError: JsonqlResolverAppError, - JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, - JsonqlEnumError: JsonqlEnumError, - JsonqlTypeError: JsonqlTypeError, - JsonqlCheckerError: JsonqlCheckerError, - JsonqlValidationError: JsonqlValidationError, - JsonqlError: JsonqlError, - JsonqlServerError: JsonqlServerError - }); - - // this will add directly to the then call in each http call - var JsonqlError$1 = JsonqlError; - - /** - * We can not just check something like result.data what if the result if false? - * @param {object} obj the result object - * @param {string} key we want to check if its exist or not - * @return {boolean} true on found - */ - var isObjectHasKey$1 = function (obj, key) { - var keys = Object.keys(obj); - return !!keys.filter(function (k) { return key === k; }).length; - }; - - /** - * It will ONLY have our own jsonql specific implement check - * @param {object} result the server return result - * @return {object} this will just throw error - */ - function clientErrorsHandler(result) { - if (isObjectHasKey$1(result, 'error')) { - var error = result.error; - var className = error.className; - var name = error.name; - var errorName = className || name; - // just throw the whole thing back - var msg = error.message || NO_ERROR_MSG; - var detail = error.detail || error; - if (errorName && errors[errorName]) { - throw new errors[className](msg, detail) - } - throw new JsonqlError$1(msg, detail) - } - // pass through to the next - return result; - } - - /** - * this will put into generator call at the very end and catch - * the error throw from inside then throw again - * this is necessary because we split calls inside and the throw - * will not reach the actual client unless we do it this way - * @param {object} e Error - * @return {void} just throw - */ - function finalCatch(e) { - // this is a hack to get around the validateAsync not actually throw error - // instead it just rejected it with the array of failed parameters - if (Array.isArray(e)) { - // if we want the message then I will have to create yet another function - // to wrap this function to provide the name prop - throw new JsonqlValidationError('', e) - } - var msg = e.message || NO_ERROR_MSG; - var detail = e.detail || e; - // @BUG the instance of not always work for some reason! - // need to figure out a better way to find out the type of the error - switch (true) { - case e instanceof Jsonql406Error: - throw new Jsonql406Error(msg, detail) - case e instanceof Jsonql500Error: - throw new Jsonql500Error(msg, detail) - case e instanceof JsonqlForbiddenError: - throw new JsonqlForbiddenError(msg, detail) - case e instanceof JsonqlAuthorisationError: - throw new JsonqlAuthorisationError(msg, detail) - case e instanceof JsonqlContractAuthError: - throw new JsonqlContractAuthError(msg, detail) - case e instanceof JsonqlResolverAppError: - throw new JsonqlResolverAppError(msg, detail) - case e instanceof JsonqlResolverNotFoundError: - throw new JsonqlResolverNotFoundError(msg, detail) - case e instanceof JsonqlEnumError: - throw new JsonqlEnumError(msg, detail) - case e instanceof JsonqlTypeError: - throw new JsonqlTypeError(msg, detail) - case e instanceof JsonqlCheckerError: - throw new JsonqlCheckerError(msg, detail) - case e instanceof JsonqlValidationError: - throw new JsonqlValidationError(msg, detail) - case e instanceof JsonqlServerError: - throw new JsonqlServerError(msg, detail) - default: - throw new JsonqlError(msg, detail) - } - } - - /** - * Check several parameter that there is something in the param - * @param {*} param input - * @return {boolean} - */ - var isNotEmpty = function (a) { - if (isArray(a)) { - return true; - } - return a !== undefined && a !== null && trim(a) !== ''; - }; - - /** `Object#toString` result references. */ - var numberTag = '[object Number]'; - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - /** `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); - } - - // validator numbers - /** - * @2015-05-04 found a problem if the value is a number like string - * it will pass, so add a chck if it's string before we pass to next - * @param {number} value expected value - * @return {boolean} true if OK - */ - var checkIsNumber = function(value) { - return isString(value) ? false : !isNaN( parseFloat(value) ) - }; - - // validate string type - /** - * @param {string} value expected value - * @return {boolean} true if OK - */ - var checkIsString = function(value) { - return (trim(value) !== '') ? isString(value) : false; - }; - - // check for boolean - - /** - * @param {boolean} value expected - * @return {boolean} true if OK - */ - var checkIsBoolean = function(value) { - return value !== null && value !== undefined && typeof value === 'boolean' - }; - - // validate any thing only check if there is something - - /** - * @param {*} value the value - * @param {boolean} [checkNull=true] strict check if there is null value - * @return {boolean} true is OK - */ - var checkIsAny = function(value, checkNull) { - if ( checkNull === void 0 ) checkNull = true; - - if (value !== undefined && value !== '' && trim(value) !== '') { - if (checkNull === false || (checkNull === true && value !== null)) { - return true; - } - } - return false; - }; - - // Good practice rule - No magic number - - var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; - var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; - var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; - // @TODO the jsdoc return array. and we should also allow array syntax - var DEFAULT_TYPE$1 = DEFAULT_TYPE; - var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; - var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; - - var TYPE_KEY$1 = TYPE_KEY; - var OPTIONAL_KEY$1 = OPTIONAL_KEY; - var ENUM_KEY$1 = ENUM_KEY; - var ARGS_KEY$1 = ARGS_KEY; - var CHECKER_KEY$1 = CHECKER_KEY; - var ALIAS_KEY$1 = ALIAS_KEY; - - var ARRAY_TYPE$1 = ARRAY_TYPE; - var OBJECT_TYPE$1 = OBJECT_TYPE; - var STRING_TYPE$1 = STRING_TYPE; - var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; - var NUMBER_TYPE$1 = NUMBER_TYPE; - var KEY_WORD$1 = KEY_WORD; - var OR_SEPERATOR$1 = OR_SEPERATOR; - - // not actually in use - // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; - - // primitive types - - /** - * this is a wrapper method to call different one based on their type - * @param {string} type to check - * @return {function} a function to handle the type - */ - var combineFn = function(type) { - switch (type) { - case NUMBER_TYPE$1: - return checkIsNumber; - case STRING_TYPE$1: - return checkIsString; - case BOOLEAN_TYPE$1: - return checkIsBoolean; - default: - return checkIsAny; - } - }; - - // validate array type - - /** - * @param {array} value expected - * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well - * @return {boolean} true if OK - */ - var checkIsArray = function(value, type) { - if ( type === void 0 ) type=''; - - if (isArray(value)) { - if (type === '' || trim(type)==='') { - return true; - } - // we test it in reverse - // @TODO if the type is an array (OR) then what? - // we need to take into account this could be an array - var c = value.filter(function (v) { return !combineFn(type)(v); }); - return !(c.length > 0) - } - return false; - }; - - /** - * check if it matches the array. pattern - * @param {string} type - * @return {boolean|array} false means NO, always return array - */ - var isArrayLike = function(type) { - // @TODO could that have something like array<> instead of array.<>? missing the dot? - // because type script is Array without the dot - if (type.indexOf(ARRAY_TYPE_LFT$1) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { - var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); - if (_type.indexOf(OR_SEPERATOR$1)) { - return _type.split(OR_SEPERATOR$1) - } - return [_type] - } - return false; - }; - - /** - * we might encounter something like array. then we need to take it apart - * @param {object} p the prepared object for processing - * @param {string|array} type the type came from - * @return {boolean} for the filter to operate on - */ - var arrayTypeHandler = function(p, type) { - var arg = p.arg; - // need a special case to handle the OR type - // we need to test the args instead of the type(s) - if (type.length > 1) { - return !arg.filter(function (v) { return ( - !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) - ); }).length; - } - // type is array so this will be or! - return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length; - }; - - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]'; - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** Used for built-in method references. */ - var objectProto$3 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - - /** Built-in value references. */ - var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER$1 = 9007199254740991; - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; - } - - /** `Object#toString` result references. */ - var argsTag$1 = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - mapTag = '[object Map]', - numberTag$1 = '[object Number]', - objectTag$1 = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag$1 = '[object String]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag$1] = - typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag$1] = - typedArrayTags[weakMapTag] = false; - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - - /** Detect free variable `exports`. */ - var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports$1 && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - - /** Used for built-in method references. */ - var objectProto$4 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$3 = objectProto$4.hasOwnProperty; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$3.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$5 = Object.prototype; - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; - - return value === proto; - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeKeys = overArg(Object.keys, Object); - - /** Used for built-in method references. */ - var objectProto$6 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$4 = objectProto$6.hasOwnProperty; - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$4.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** `Object#toString` result references. */ - var asyncTag = '[object AsyncFunction]', - funcTag$1 = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike$1(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype; - - /** Built-in value references. */ - var splice = arrayProto.splice; - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** Used for built-in method references. */ - var funcProto$1 = Function.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$1 = funcProto$1.toString; - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString$1.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used for built-in method references. */ - var funcProto$2 = Function.prototype, - objectProto$7 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$2 = funcProto$2.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$5 = objectProto$7.hasOwnProperty; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString$2.call(hasOwnProperty$5).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /* Built-in method references that are verified to be native. */ - var Map$1 = getNative(root, 'Map'); - - /* Built-in method references that are verified to be native. */ - var nativeCreate = getNative(Object, 'create'); - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used for built-in method references. */ - var objectProto$8 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$6 = objectProto$8.hasOwnProperty; - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty$6.call(data, key) ? data[key] : undefined; - } - - /** Used for built-in method references. */ - var objectProto$9 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$7 = objectProto$9.hasOwnProperty; - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key); - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; - return this; - } - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map$1 || ListCache), - 'string': new Hash - }; - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; - - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED$2); - return this; - } - - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } - - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } - - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } - - /** Built-in value references. */ - var Uint8Array$1 = root.Uint8Array; - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$1 = 1, - COMPARE_UNORDERED_FLAG$1 = 2; - - /** `Object#toString` result references. */ - var boolTag$1 = '[object Boolean]', - dateTag$1 = '[object Date]', - errorTag$1 = '[object Error]', - mapTag$1 = '[object Map]', - numberTag$2 = '[object Number]', - regexpTag$1 = '[object RegExp]', - setTag$1 = '[object Set]', - stringTag$2 = '[object String]', - symbolTag$1 = '[object Symbol]'; - - var arrayBufferTag$1 = '[object ArrayBuffer]', - dataViewTag$1 = '[object DataView]'; - - /** Used to convert symbols to primitives and strings. */ - var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined, - symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag$1: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag$1: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array$1(object), new Uint8Array$1(other))) { - return false; - } - return true; - - case boolTag$1: - case dateTag$1: - case numberTag$2: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag$1: - return object.name == other.name && object.message == other.message; - - case regexpTag$1: - case stringTag$2: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag$1: - var convert = mapToArray; - - case setTag$1: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG$1; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag$1: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** Used for built-in method references. */ - var objectProto$a = Object.prototype; - - /** Built-in value references. */ - var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable$1.call(object, symbol); - }); - }; - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$2 = 1; - - /** Used for built-in method references. */ - var objectProto$b = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$8 = objectProto$b.hasOwnProperty; - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) { - return false; - } - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'); - - /* Built-in method references that are verified to be native. */ - var Promise$1 = getNative(root, 'Promise'); - - /* Built-in method references that are verified to be native. */ - var Set$1 = getNative(root, 'Set'); - - /* Built-in method references that are verified to be native. */ - var WeakMap$1 = getNative(root, 'WeakMap'); - - /** `Object#toString` result references. */ - var mapTag$2 = '[object Map]', - objectTag$2 = '[object Object]', - promiseTag = '[object Promise]', - setTag$2 = '[object Set]', - weakMapTag$1 = '[object WeakMap]'; - - var dataViewTag$2 = '[object DataView]'; - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map$1), - promiseCtorString = toSource(Promise$1), - setCtorString = toSource(Set$1), - weakMapCtorString = toSource(WeakMap$1); - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$2) || - (Map$1 && getTag(new Map$1) != mapTag$2) || - (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || - (Set$1 && getTag(new Set$1) != setTag$2) || - (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag$2 ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag$2; - case mapCtorString: return mapTag$2; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag$2; - case weakMapCtorString: return weakMapTag$1; - } - } - return result; - }; - } - - var getTag$1 = getTag; - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$3 = 1; - - /** `Object#toString` result references. */ - var argsTag$2 = '[object Arguments]', - arrayTag$1 = '[object Array]', - objectTag$3 = '[object Object]'; - - /** Used for built-in method references. */ - var objectProto$c = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$9 = objectProto$c.hasOwnProperty; - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag$1 : getTag$1(object), - othTag = othIsArr ? arrayTag$1 : getTag$1(other); - - objTag = objTag == argsTag$2 ? objectTag$3 : objTag; - othTag = othTag == argsTag$2 ? objectTag$3 : othTag; - - var objIsObj = objTag == objectTag$3, - othIsObj = othTag == objectTag$3, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { - var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$4 = 1, - COMPARE_UNORDERED_FLAG$2 = 2; - - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } - - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - - /** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } - - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } - - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /** Error message constants. */ - var FUNC_ERROR_TEXT = 'Expected a function'; - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** Used to match property names within property paths. */ - var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** Used as references for various `Number` constants. */ - var INFINITY$1 = 1 / 0; - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; - } - - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$5 = 1, - COMPARE_UNORDERED_FLAG$3 = 2; - - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); - }; - } - - /** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ - function identity(value) { - return value; - } - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - - /** - * Creates a function that returns the value at `path` of a given object. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - * @example - * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; - * - * _.map(objects, _.property('a.b')); - * // => [2, 1] - * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] - */ - function property(path) { - return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); - } - - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } - - // validate object type - /** - * @TODO if provide with the keys then we need to check if the key:value type as well - * @param {object} value expected - * @param {array} [keys=null] if it has the keys array to compare as well - * @return {boolean} true if OK - */ - var checkIsObject = function(value, keys) { - if ( keys === void 0 ) keys=null; - - if (isPlainObject(value)) { - if (!keys) { - return true; - } - if (checkIsArray(keys)) { - // please note we DON'T care if some is optional - // plese refer to the contract.json for the keys - return !keys.filter(function (key) { - var _value = value[key.name]; - return !(key.type.length > key.type.filter(function (type) { - var tmp; - if (_value !== undefined) { - if ((tmp = isArrayLike(type)) !== false) { - return !arrayTypeHandler({arg: _value}, tmp) - // return tmp.filter(t => !checkIsArray(_value, t)).length; - // @TODO there might be an object within an object with keys as well :S - } - return !combineFn(type)(_value) - } - return true; - }).length) - }).length; - } - } - return false; - }; - - /** - * fold this into it's own function to handler different object type - * @param {object} p the prepared object for process - * @return {boolean} - */ - var objectTypeHandler = function(p) { - var arg = p.arg; - var param = p.param; - var _args = [arg]; - if (Array.isArray(param.keys) && param.keys.length) { - _args.push(param.keys); - } - // just simple check - return Reflect.apply(checkIsObject, null, _args) - }; - - // move the index.js code here that make more sense to find where things are - // import debug from 'debug' - // const debugFn = debug('jsonql-params-validator:validator') - // also export this for use in other places - - /** - * We need to handle those optional parameter without a default value - * @param {object} params from contract.json - * @return {boolean} for filter operation false is actually OK - */ - var optionalHandler = function( params ) { - var arg = params.arg; - var param = params.param; - if (isNotEmpty(arg)) { - // debug('call optional handler', arg, params); - // loop through the type in param - return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } - ).length) - } - return false; - }; - - /** - * actually picking the validator - * @param {*} type for checking - * @param {*} value for checking - * @return {boolean} true on OK - */ - var validateHandler = function(type, value) { - var tmp; - switch (true) { - case type === OBJECT_TYPE$1: - // debugFn('call OBJECT_TYPE') - return !objectTypeHandler(value) - case type === ARRAY_TYPE$1: - // debugFn('call ARRAY_TYPE') - return !checkIsArray(value.arg) - // @TODO when the type is not present, it always fall through here - // so we need to find a way to actually pre-check the type first - // AKA check the contract.json map before running here - case (tmp = isArrayLike(type)) !== false: - // debugFn('call ARRAY_LIKE: %O', value) - return !arrayTypeHandler(value, tmp) - default: - return !combineFn(type)(value.arg) - } - }; - - /** - * it get too longer to fit in one line so break it out from the fn below - * @param {*} arg value - * @param {object} param config - * @return {*} value or apply default value - */ - var getOptionalValue = function(arg, param) { - if (arg !== undefined) { - return arg; - } - return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null) - }; - - /** - * padding the arguments with defaultValue if the arguments did not provide the value - * this will be the name export - * @param {array} args normalized arguments - * @param {array} params from contract.json - * @return {array} merge the two together - */ - var normalizeArgs = function(args, params) { - // first we should check if this call require a validation at all - // there will be situation where the function doesn't need args and params - if (!checkIsArray(params)) { - // debugFn('params value', params) - throw new JsonqlError(PARAMS_NOT_ARRAY_ERR) - } - if (params.length === 0) { - return []; - } - if (!checkIsArray(args)) { - throw new JsonqlError(ARGS_NOT_ARRAY_ERR) - } - // debugFn(args, params); - // fall through switch - switch(true) { - case args.length == params.length: // standard - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, - param: params[i] - } - ); }) - case params[0].variable === true: // using spread syntax - var type = params[0].type; - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, // keep the index for reference - param: params[i] || { type: type, name: '_' } - } - ); }) - // with optional defaultValue parameters - case args.length < params.length: - return params.map(function (param, i) { return ( - { - param: param, - index: i, - arg: getOptionalValue(args[i], param), - optional: param.optional || false - } - ); }) - // this one pass more than it should have anything after the args.length will be cast as any type - case args.length > params.length: - var ctn = params.length; - // this happens when we have those array. type - var _type = [ DEFAULT_TYPE$1 ]; - // we only looking at the first one, this might be a @BUG - /* - if ((tmp = isArrayLike(params[0].type[0])) !== false) { - _type = tmp; - } */ - // if we use the params as guide then the rest will get throw out - // which is not what we want, instead, anything without the param - // will get a any type and optional flag - return args.map(function (arg, i) { - var optional = i >= ctn ? true : !!params[i].optional; - var param = params[i] || { type: _type, name: ("_" + i) }; - return { - arg: optional ? getOptionalValue(arg, param) : arg, - index: i, - param: param, - optional: optional - } - }) - // @TODO find out if there is more cases not cover - default: // this should never happen - // debugFn('args', args) - // debugFn('params', params) - // this is unknown therefore we just throw it! - throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) - } - }; - - // what we want is after the validaton we also get the normalized result - // which is with the optional property if the argument didn't provide it - /** - * process the array of params back to their arguments - * @param {array} result the params result - * @return {array} arguments - */ - var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; - - /** - * validator main interface - * @param {array} args the arguments pass to the method call - * @param {array} params from the contract for that method - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {array} empty array on success, or failed parameter and reasons - */ - var validateSync = function(args, params, withResult) { - var obj; - - if ( withResult === void 0 ) withResult = false; - var cleanArgs = normalizeArgs(args, params); - var checkResult = cleanArgs.filter(function (p) { - // v1.4.4 this fixed the problem, the root level optional is from the last fn - if (p.optional === true || p.param.optional === true) { - return optionalHandler(p) - } - // because array of types means OR so if one pass means pass - return !(p.param.type.length > p.param.type.filter( - function (type) { return validateHandler(type, p); } - ).length) - }); - // using the same convention we been using all this time - return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) - }; - - /** - * A wrapper method that return promise - * @param {array} args arguments - * @param {array} params from contract.json - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {object} promise.then or catch - */ - var validateAsync = function(args, params, withResult) { - if ( withResult === void 0 ) withResult = false; - - return new Promise(function (resolver, rejecter) { - var result = validateSync(args, params, withResult); - if (withResult) { - return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) - : resolver(result[DATA_KEY]) - } - // the different is just in the then or catch phrase - return result.length ? rejecter(result) : resolver([]) - }) - }; - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** Detect free variable `exports`. */ - var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; - - /** Built-in value references. */ - var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, - allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** Built-in value references. */ - var objectCreate = Object.create; - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike$1(value); - } - - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; - } - - /** Used for built-in method references. */ - var objectProto$d = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$a = objectProto$d.hasOwnProperty; - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$a.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$e = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$b = objectProto$e.hasOwnProperty; - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty$b.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn(object) { - return isArrayLike$1(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } - - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeMax = Math.max; - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ - function constant(value) { - return function() { - return value; - }; - } - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeNow = Date.now; - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike$1(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - - /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; - } - - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; - } - - /** Error message constants. */ - var FUNC_ERROR_TEXT$1 = 'Expected a function'; - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT$1); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols$1 = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = baseIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } - - /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ - function omitBy(object, predicate) { - return pickBy(object, negate(baseIteratee(predicate))); - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } - - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ - function findKey(object, predicate) { - return baseFindKey(object, baseIteratee(predicate), baseForOwn); - } - - /** - * @param {array} arr Array for check - * @param {*} value target - * @return {boolean} true on successs - */ - var isInArray = function(arr, value) { - return !!arr.filter(function (a) { return a === value; }).length; - }; - - var isObjectHasKey$2 = function(obj, key) { - var keys = Object.keys(obj); - return isInArray(keys, key) - }; - - // just not to make my head hurt - var isEmpty = function (value) { return !isNotEmpty(value); }; - - /** - * Map the alias to their key then grab their value over - * @param {object} config the user supplied config - * @param {object} appProps the default option map - * @return {object} the config keys replaced with the appProps key by the ALIAS - */ - function mapAliasConfigKeys(config, appProps) { - // need to do two steps - // 1. take key with alias key - var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$1]; } ); - if (isEqual(aliasMap, {})) { - return config; - } - return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) - } - - /** - * We only want to run the valdiation against the config (user supplied) value - * but keep the defaultOptions untouch - * @param {object} config configuraton supplied by user - * @param {object} appProps the default options map - * @return {object} the pristine values that will add back to the final output - */ - function preservePristineValues(config, appProps) { - // @BUG this will filter out those that is alias key - // we need to first map the alias keys back to their full key - var _config = mapAliasConfigKeys(config, appProps); - // take the default value out - var pristineValues = mapValues( - omitBy(appProps, function (value, key) { return isObjectHasKey$2(_config, key); }), - function (value) { return value.args; } - ); - // for testing the value - var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !isObjectHasKey$2(_config, key); }); - // output - return { - pristineValues: pristineValues, - checkAgainstAppProps: checkAgainstAppProps, - config: _config // passing this correct values back - } - } - - /** - * This will take the value that is ONLY need to check - * @param {object} config that one - * @param {object} props map for creating checking - * @return {object} put that arg into the args - */ - function processConfigAction(config, props) { - // debugFn('processConfigAction', props) - // v.1.2.0 add checking if its mark optional and the value is empty then pass - return mapValues(props, function (value, key) { - var obj, obj$1; - - return ( - config[key] === undefined || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) - ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) - : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) - ); - } - ) - } - - /** - * Quick transform - * @TODO we should only validate those that is pass from the config - * and pass through those values that is from the defaultOptions - * @param {object} opts that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ - function prepareArgsForValidation(opts, appProps) { - var ref = preservePristineValues(opts, appProps); - var config = ref.config; - var pristineValues = ref.pristineValues; - var checkAgainstAppProps = ref.checkAgainstAppProps; - // output - return [ - processConfigAction(config, checkAgainstAppProps), - pristineValues - ] - } - - // breaking the whole thing up to see what cause the multiple calls issue - - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:options:validation') - - /** - * just make sure it returns an array to use - * @param {*} arg input - * @return {array} output - */ - var toArray$1 = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; - - /** - * DIY in array - * @param {array} arr to check against - * @param {*} value to check - * @return {boolean} true on OK - */ - var inArray$1 = function (arr, value) { return ( - !!arr.filter(function (v) { return v === value; }).length - ); }; - - /** - * break out to make the code easier to read - * @param {object} value to process - * @param {function} cb the validateSync - * @return {array} empty on success - */ - function validateHandler$1(value, cb) { - var obj; - - // cb is the validateSync methods - var args = [ - [ value[ARGS_KEY$1] ], - [( obj = {}, obj[TYPE_KEY$1] = toArray$1(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] - ]; - // debugFn('validateHandler', args) - return Reflect.apply(cb, null, args) - } - - /** - * Check against the enum value if it's provided - * @param {*} value to check - * @param {*} enumv to check against if it's not false - * @return {boolean} true on OK - */ - var enumHandler = function (value, enumv) { - if (checkIsArray(enumv)) { - return inArray$1(enumv, value) - } - return true; - }; - - /** - * Allow passing a function to check the value - * There might be a problem here if the function is incorrect - * and that will makes it hard to debug what is going on inside - * @TODO there could be a few feature add to this one under different circumstance - * @param {*} value to check - * @param {function} checker for checking - */ - var checkerHandler = function (value, checker) { - try { - return isFunction(checker) ? checker.apply(null, [value]) : false; - } catch (e) { - return false; - } - }; - - /** - * Taken out from the runValidaton this only validate the required values - * @param {array} args from the config2argsAction - * @param {function} cb validateSync - * @return {array} of configuration values - */ - function runValidationAction(cb) { - return function (value, key) { - // debugFn('runValidationAction', key, value) - if (value[KEY_WORD$1]) { - return value[ARGS_KEY$1] - } - var check = validateHandler$1(value, cb); - if (check.length) { - // log('runValidationAction', key, value) - throw new JsonqlTypeError(key, check) - } - if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { - // log(ENUM_KEY, value[ENUM_KEY]) - throw new JsonqlEnumError(key) - } - if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { - // log(CHECKER_KEY, value[CHECKER_KEY]) - throw new JsonqlCheckerError(key) - } - return value[ARGS_KEY$1] - } - } - - /** - * @param {object} args from the config2argsAction - * @param {function} cb validateSync - * @return {object} of configuration values - */ - function runValidation(args, cb) { - var argsForValidate = args[0]; - var pristineValues = args[1]; - // turn the thing into an array and see what happen here - // debugFn('_args', argsForValidate) - var result = mapValues(argsForValidate, runValidationAction(cb)); - return merge(result, pristineValues) - } - - // this is port back from the client to share across all projects - - /** - * @param {object} config user provide configuration option - * @param {object} appProps mutation configuration options - * @param {object} constProps the immutable configuration options - * @param {function} cb the validateSync method - * @return {object} Promise resolve merge config object - */ - function checkOptionsSync(config, appProps, constProps, cb) { - if ( config === void 0 ) config = {}; - - return merge( - runValidation( - prepareArgsForValidation(config, appProps), - cb - ), - constProps - ) - } - - // create function to construct the config entry so we don't need to keep building object - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:construct-config'); - /** - * @param {*} args value - * @param {string} type for value - * @param {boolean} [optional=false] - * @param {boolean|array} [enumv=false] - * @param {boolean|function} [checker=false] - * @return {object} config entry - */ - function constructConfig(args, type, optional, enumv, checker, alias) { - if ( optional === void 0 ) optional=false; - if ( enumv === void 0 ) enumv=false; - if ( checker === void 0 ) checker=false; - if ( alias === void 0 ) alias=false; - - var base = {}; - base[ARGS_KEY] = args; - base[TYPE_KEY] = type; - if (optional === true) { - base[OPTIONAL_KEY] = true; - } - if (checkIsArray(enumv)) { - base[ENUM_KEY] = enumv; - } - if (isFunction(checker)) { - base[CHECKER_KEY] = checker; - } - if (isString(alias)) { - base[ALIAS_KEY] = alias; - } - return base; - } - - // export also create wrapper methods - - /** - * This has a different interface - * @param {*} value to supply - * @param {string|array} type for checking - * @param {object} params to map against the config check - * @param {array} params.enumv NOT enum - * @param {boolean} params.optional false then nothing - * @param {function} params.checker need more work on this one later - * @param {string} params.alias mostly for cmd - */ - var createConfig = function (value, type, params) { - if ( params === void 0 ) params = {}; - - // Note the enumv not ENUM - // const { enumv, optional, checker, alias } = params; - // let args = [value, type, optional, enumv, checker, alias]; - var o = params[OPTIONAL_KEY]; - var e = params[ENUM_KEY]; - var c = params[CHECKER_KEY]; - var a = params[ALIAS_KEY]; - return constructConfig.apply(null, [value, type, o, e, c, a]) - }; - - // copy of above but it's sync - var checkConfig = function(validateSync) { - return function(config, appProps, constantProps) { - if ( constantProps === void 0 ) constantProps = {}; - - return checkOptionsSync(config, appProps, constantProps, validateSync) - } - }; - - // export - var isString$1 = checkIsString; - var isNumber$1 = checkIsNumber; - var validateAsync$1 = validateAsync; - - var createConfig$1 = createConfig; - var checkConfig$1 = checkConfig(validateSync); - - /** - * using just the map reduce to chain multiple functions together - * @param {function} mainFn the init function - * @param {array} moreFns as many as you want to take the last value and return a new one - * @return {function} accept value for the mainFn - */ - var chainFns = function (mainFn) { - var moreFns = [], len = arguments.length - 1; - while ( len-- > 0 ) moreFns[ len ] = arguments[ len + 1 ]; - - return ( - function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return ( - moreFns.reduce(function (value, nextFn) { return ( - // change here to check if the return value is array then we spread it - Reflect.apply(nextFn, null, toArray(value)) - ); }, Reflect.apply(mainFn, null, args)) - ); - } - ); - }; - - /** - * check if the object has name property - * @param {object} obj the object to check - * @param {string} name the prop name - * @return {*} the value or undefined - */ - function objHasProp(obj, name) { - var prop = Object.getOwnPropertyDescriptor(obj, name); - return prop !== undefined && prop.value ? prop.value : prop; - } - - /** - * 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 {string} name the name of the object to get inject also for checking - * @param {object} data to inject into the function static interface - * @param {boolean} [overwrite=false] if we want to overwrite the existing data - * @return {function} added property resolver - */ - function injectToFn(resolver, name, data, overwrite) { - if ( overwrite === void 0 ) overwrite = false; - - var check = objHasProp(resolver, name); - if (overwrite === false && check !== undefined) { - // console.info(`NOT INJECTED`) - return resolver; - } - /* this will throw error! - if (overwrite === true && check !== undefined) { - delete resolver[name] // delete this property - } - */ - // console.info(`INJECTED`) - Object.defineProperty(resolver, name, { - value: data, - writable: overwrite // if its set to true then we should able to overwrite it - }); - - return resolver; - } - - // breaking out the inner methods generator in here - - /** - * generate authorisation specific methods - * @param {object} jsonqlInstance instance of this - * @param {string} name of method - * @param {object} opts configuration - * @param {object} contract to match - * @return {function} for use - */ - var authMethodGenerator = function (jsonqlInstance, name, opts, contract) { - return function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var params = contract.auth[name].params; - var values = params.map(function (p, i) { return args[i]; }); - var header = args[params.length] || {}; - return validateAsync$1(args, params) - .then(function () { return jsonqlInstance - .query - .apply(jsonqlInstance, [name, values, header]); } - ) - .catch(finalCatch) - } - }; - - /** - * Break up the different type each - create query methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createQueryMethods = function (obj, jsonqlInstance, ee, config, contract) { - var query = {}; - var loop = function ( queryFn ) { - // to keep it clean we use a param to id the auth method - // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; - // generate the query method - query = injectToFn(query, queryFn, function queryFnHandler() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var params = contract.query[queryFn].params; - var _args = params.map(function (param, i) { return args[i]; }); - // debug('query', queryFn, _params); - // @TODO this need to change to a different way to add an extra header - var header = {}; - // @TODO validate against the type - return validateAsync$1(_args, params) - .then(function () { return jsonqlInstance - .query - .apply(jsonqlInstance, [queryFn, _args, header]); } - ) - .catch(finalCatch) - }); - }; - - for (var queryFn in contract.query) loop( queryFn ); - obj.query = query; - // create an alias to the helloWorld method - obj.helloWorld = query.helloWorld; - return [ obj, jsonqlInstance, ee, config, contract ] - }; - - /** - * create mutation methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createMutationMethods = function (obj, jsonqlInstance, ee, config, contract) { - var mutation = {}; - // process the mutation, the reason the mutation has a fixed number of parameters - // there is only the payload, and conditions parameters - // plus a header at the end - var loop = function ( mutationFn ) { - mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header) { - if ( header === void 0 ) header = {}; - - var args = [payload, conditions]; - var params = contract.mutation[mutationFn].params; - return validateAsync$1(args, params) - .then(function () { return jsonqlInstance - .mutation - .apply(jsonqlInstance, [mutationFn, payload, conditions, header]); } - ) - .catch(finalCatch) - }); - }; - - for (var mutationFn in contract.mutation) loop( mutationFn ); - obj.mutation = mutation; - return [ obj, jsonqlInstance, ee, config, contract ] - }; - - /** - * create auth methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createAuthMethods = function (obj, jsonqlInstance, ee, config, contract) { - if (config.enableAuth && contract.auth) { - var auth = {}; // v1.3.1 add back the auth prop name in contract - var loginHandlerName = config.loginHandlerName; - var logoutHandlerName = config.logoutHandlerName; - if (contract.auth[loginHandlerName]) { - // changing to the name the config specify - auth[loginHandlerName] = function loginHandlerFn() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract); - return fn.apply(null, args) - .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance)) - .then(function (token) { - ee.$trigger(LOGIN_NAME, token); - return token; - }) - }; - } - // @TODO allow to logout one particular profile or all of them - if (contract.auth[logoutHandlerName]) { - auth[logoutHandlerName] = function logoutHandlerFn() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract); - return fn.apply(null, args) - .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance)) - .then(function (r) { - ee.$trigger(LOGOUT_NAME, r); - return r; - }) - }; - } else { - auth[logoutHandlerName] = function logoutHandlerFn() { - jsonqlInstance.postLogoutAction(KEY_WORD); - ee.$trigger(LOGOUT_NAME, KEY_WORD); - }; - } - obj.auth = auth; - } - - return obj; - }; - - /** - * Here just generate the methods calls - * @param {object} jsonqlInstance what it said - * @param {object} ee event emitter - * @param {object} config configuration - * @param {object} contract the map - * @return {object} with mapped methods - */ - function methodsGenerator(jsonqlInstance, ee, config, contract) { - var obj = {}; - var executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods); - return executor(obj, jsonqlInstance, ee, config, contract) - } - - // This generator will use the old style - - /** - * Group all the same methods together - * @param {object} ee event emitters - * @param {string} type query, mutation or auth - * @param {string} resolverName use as the guide - * @param {array} args from the call - * @return {function} the handler itself - */ - var handler = function (ee, type) { - // we don't run validate here because we want until the contract is ready - return function (resolverName) { - var args = [], len = arguments.length - 1; - while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; - - return ( - new Promise(function (resolver, rejecter) { - // this are the callbacks - ee.$only(createEvt(type, resolverName, ON_RESULT_PROP_NAME), resolver); - ee.$only(createEvt(type, resolverName, ON_ERROR_PROP_NAME), rejecter); - // this is the main call - ee.$trigger(type, { resolverName: resolverName, args: args }); - }) - ); - } - }; - - /** - * @param {object} ee eventEmitter - * @param {object} contract the map - * @param {object} config configuration - */ - var validateRegisteredEvents = function (ee, contract, config) { - var storedEvt = ee.$queues; - var debug = config.debugOn; - if (debug) { - console.info('(validateRegisteredEvents)', 'storedEvt', storedEvt); - } - storedEvt.forEach(function (args) { - var type = args[0]; - var payload = args[1]; - var resolverName = payload.resolverName; - if (debug) { - console.info('(validateRegisteredEvents)', type, resolverName); - } - if (!contract[type][resolverName]) { - throw new Error((type + "." + resolverName + " not existed in contract!")) - } - }); - }; - - /** - * set up all the event handlers once the contract is ready - * @param {object} jsonqlInstance what the name said - * @param {object} ee event emitter - * @param {object} config the configuration - * @param {object} contract the map - * @return {void} nothing - */ - function setupEventHandlers(jsonqlInstance, ee, config, contract) { - var methods = methodsGenerator(jsonqlInstance, ee, config, contract); - validateRegisteredEvents(ee, contract, config); - // create handler - var loop = function ( type ) { - // setup event listeners - only one listener per type - ee.$only(type, function(ref) { - var resolverName = ref.resolverName; - var args = ref.args; - - if (methods[type][resolverName]) { - Reflect.apply(methods[type][resolverName], null, args) - .then(function (result) { - ee.$trigger(createEvt(type, resolverName, ON_RESULT_PROP_NAME), result); - }) - .catch(function (err) { - ee.$trigger(createEvt(type, resolverName, ON_ERROR_PROP_NAME), err); - }); - } else { - console.error((resolverName + " is not defined in the contract!")); - } - }); - }; - - for (var type in methods) loop( type ); - // all done now release the queue if any - setTimeout(function () { - ee.$suspend = false; - }, 1); - } - - /** - * @param {object} jsonqlInstance jsonql class instance - * @param {object} config options - * @param {object} contractPromise an unresolve promise - * @param {object} ee eventEmitter - * @return {object} constructed functions call - */ - var generator = function (jsonqlInstance, config, contractPromise, ee) { - ee.$suspend = true; // hold all the calls - // wait for the promise to resolve - contractPromise.then(function (contract) { - setupEventHandlers(jsonqlInstance, ee, config, contract); - }); - // construct the api - var obj = { - query: handler(ee, 'query'), - mutation: handler(ee, 'mutation'), - auth: handler(ee, 'auth') - }; - // allow getting the token for valdiate agains the socket - obj.getToken = function () { return jsonqlInstance.rawAuthToken; }; - // this will pass to the ws-client if needed - // obj.eventEmitter = ee; - // this will require a param - if (config.exposeContract) { - obj.getContract = function () { return jsonqlInstance.get(); }; - } - if (config.enableAuth) { - obj.userdata = function () { return jsonqlInstance.userdata; }; - } - obj.version = '1.5.1'; - // output - return obj; - }; - - // split the contract into the node side and the generic side - /** - * Check if the json is a contract file or not - * @param {object} contract json object - * @return {boolean} true - */ - function checkIsContract(contract) { - return isPlainObject(contract) - && ( - isObjectHasKey(contract, QUERY_NAME) - || isObjectHasKey(contract, MUTATION_NAME) - || isObjectHasKey(contract, SOCKET_NAME) - ) - } - - /** - * Wrapper method that check if it's contract then return the contract or false - * @param {object} contract the object to check - * @return {boolean | object} false when it's not - */ - function isContract(contract) { - return checkIsContract(contract) ? contract : false; - } - - /** - * generate a 32bit hash based on the function.toString() - * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery - * @param {string} s the converted to string function - * @return {string} the hashed function string - */ - function hashCode(s) { - return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) - } - - // take only the module part which is what we use here - /** - * @param {object} jsonqlInstance the init instance of jsonql client - * @param {object} contract the static contract - * @return {object} contract may be from server - */ - var getContractFromConfig = function(jsonqlInstance, contract) { - if ( contract === void 0 ) contract = {}; - - if (isContract(contract)) { - return Promise.resolve(contract) - } - return jsonqlInstance.getContract() - }; - // wrapper method to make sure it's a string - var hashCode$1 = function (str) { return hashCode(str) + ''; }; - var USERDATA_TABLE = 'userdata'; - var CLS_LOCAL_STORE_NAME = 'localStore'; - var CLS_SESS_STORE_NAME = 'sessionStore'; - var CLS_CONTRACT_NAME = 'contract'; - var CLS_PROFILE_IDX = 'prof_idx'; - var LOG_ERROR_SWITCH = '__error__'; - var ZERO_IDX = 0; - - /** - * The code was extracted from: - * https://github.com/davidchambers/Base64.js - */ - - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - - function InvalidCharacterError(message) { - this.message = message; - } - - InvalidCharacterError.prototype = new Error(); - InvalidCharacterError.prototype.name = 'InvalidCharacterError'; - - function polyfill (input) { - var str = String(input).replace(/=+$/, ''); - if (str.length % 4 == 1) { - throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); - } - for ( - // initialize result and counters - var bc = 0, bs, buffer, idx = 0, output = ''; - // get next character - buffer = str.charAt(idx++); - // character found in table? initialize bit storage and add its ascii value; - ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, - // and if not first of each 4 characters, - // convert the first 8 bits to one ascii character - bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 - ) { - // try to find character in table (0-63, not found => -1) - buffer = chars.indexOf(buffer); - } - return output; - } - - - var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; - - function b64DecodeUnicode(str) { - return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { - var code = p.charCodeAt(0).toString(16).toUpperCase(); - if (code.length < 2) { - code = '0' + code; - } - return '%' + code; - })); - } - - var base64_url_decode = function(str) { - var output = str.replace(/-/g, "+").replace(/_/g, "/"); - switch (output.length % 4) { - case 0: - break; - case 2: - output += "=="; - break; - case 3: - output += "="; - break; - default: - throw "Illegal base64url string!"; - } - - try{ - return b64DecodeUnicode(output); - } catch (err) { - return atob(output); - } - }; - - function InvalidTokenError(message) { - this.message = message; - } - - InvalidTokenError.prototype = new Error(); - InvalidTokenError.prototype.name = 'InvalidTokenError'; - - var lib = function (token,options) { - if (typeof token !== 'string') { - throw new InvalidTokenError('Invalid token specified'); - } - - options = options || {}; - var pos = options.header === true ? 0 : 1; - try { - return JSON.parse(base64_url_decode(token.split('.')[pos])); - } catch (e) { - throw new InvalidTokenError('Invalid token specified: ' + e.message); - } - }; - - var InvalidTokenError_1 = InvalidTokenError; - lib.InvalidTokenError = InvalidTokenError_1; - - // when the user is login with the jwt - - 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 = lib(token); - return validate(t) - } - throw new JsonqlError('Token must be a string!') - } - - var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; - - var appProps = { - algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), - expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), - notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), - audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), - subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), - issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), - noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), - header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), - keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), - mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) - }; - - /** - * @param {boolean} sec return in second or not - * @return {number} timestamp - */ - var timestamp$1 = function (sec) { - if ( sec === void 0 ) sec = false; - - var time = Date.now(); - return sec ? Math.floor( time / 1000 ) : time; - }; - - var assign = make_assign(); - var create = make_create(); - var trim$1 = make_trim(); - var Global = (typeof window !== 'undefined' ? window : commonjsGlobal); - - var util = { - assign: assign, - create: create, - trim: trim$1, - bind: bind, - slice: slice, - each: each, - map: map, - pluck: pluck, - isList: isList, - isFunction: isFunction$1, - isObject: isObject$1, - Global: Global - }; - - function make_assign() { - if (Object.assign) { - return Object.assign - } else { - return function shimAssign(obj, props1, props2, etc) { - var arguments$1 = arguments; - - for (var i = 1; i < arguments.length; i++) { - each(Object(arguments$1[i]), function(val, key) { - obj[key] = val; - }); - } - return obj - } - } - } - - function make_create() { - if (Object.create) { - return function create(obj, assignProps1, assignProps2, etc) { - var assignArgsList = slice(arguments, 1); - return assign.apply(this, [Object.create(obj)].concat(assignArgsList)) - } - } else { - function F() {} // eslint-disable-line no-inner-declarations - return function create(obj, assignProps1, assignProps2, etc) { - var assignArgsList = slice(arguments, 1); - F.prototype = obj; - return assign.apply(this, [new F()].concat(assignArgsList)) - } - } - } - - function make_trim() { - if (String.prototype.trim) { - return function trim(str) { - return String.prototype.trim.call(str) - } - } else { - return function trim(str) { - return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '') - } - } - } - - function bind(obj, fn) { - return function() { - return fn.apply(obj, Array.prototype.slice.call(arguments, 0)) - } - } - - function slice(arr, index) { - return Array.prototype.slice.call(arr, index || 0) - } - - function each(obj, fn) { - pluck(obj, function(val, key) { - fn(val, key); - return false - }); - } - - function map(obj, fn) { - var res = (isList(obj) ? [] : {}); - pluck(obj, function(v, k) { - res[k] = fn(v, k); - return false - }); - return res - } - - function pluck(obj, fn) { - if (isList(obj)) { - for (var i=0; i= 0; i--) { - var key = localStorage().key(i); - fn(read(key), key); - } - } - - function remove(key) { - return localStorage().removeItem(key) - } - - function clearAll() { - return localStorage().clear() - } - - // cookieStorage is useful Safari private browser mode, where localStorage - // doesn't work but cookies do. This implementation is adopted from - // https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage - - - var Global$2 = util.Global; - var trim$2 = util.trim; - - var cookieStorage = { - name: 'cookieStorage', - read: read$1, - write: write$1, - each: each$3, - remove: remove$1, - clearAll: clearAll$1, - }; - - var doc = Global$2.document; - - function read$1(key) { - if (!key || !_has(key)) { return null } - var regexpStr = "(?:^|.*;\\s*)" + - escape(key).replace(/[\-\.\+\*]/g, "\\$&") + - "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"; - return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")) - } - - function each$3(callback) { - var cookies = doc.cookie.split(/; ?/g); - for (var i = cookies.length - 1; i >= 0; i--) { - if (!trim$2(cookies[i])) { - continue - } - var kvp = cookies[i].split('='); - var key = unescape(kvp[0]); - var val = unescape(kvp[1]); - callback(val, key); - } - } - - function write$1(key, data) { - if(!key) { return } - doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; - } - - function remove$1(key) { - if (!key || !_has(key)) { - return - } - doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; - } - - function clearAll$1() { - each$3(function(_, key) { - remove$1(key); - }); - } - - function _has(key) { - return (new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie) - } - - var defaults = defaultsPlugin; - - function defaultsPlugin() { - var defaultValues = {}; - - return { - defaults: defaults, - get: get - } - - function defaults(_, values) { - defaultValues = values; - } - - function get(super_fn, key) { - var val = super_fn(); - return (val !== undefined ? val : defaultValues[key]) - } - } - - var bind$2 = util.bind; - var each$4 = util.each; - var create$2 = util.create; - var slice$2 = util.slice; - - var events = eventsPlugin; - - function eventsPlugin() { - var pubsub = _newPubSub(); - - return { - watch: watch, - unwatch: unwatch, - once: once, - - set: set, - remove: remove, - clearAll: clearAll - } - - // new pubsub functions - function watch(_, key, listener) { - return pubsub.on(key, bind$2(this, listener)) - } - function unwatch(_, subId) { - pubsub.off(subId); - } - function once(_, key, listener) { - pubsub.once(key, bind$2(this, listener)); - } - - // overwrite function to fire when appropriate - function set(super_fn, key, val) { - var oldVal = this.get(key); - super_fn(); - pubsub.fire(key, val, oldVal); - } - function remove(super_fn, key) { - var oldVal = this.get(key); - super_fn(); - pubsub.fire(key, undefined, oldVal); - } - function clearAll(super_fn) { - var oldVals = {}; - this.each(function(val, key) { - oldVals[key] = val; - }); - super_fn(); - each$4(oldVals, function(oldVal, key) { - pubsub.fire(key, undefined, oldVal); - }); - } - } - - - function _newPubSub() { - return create$2(_pubSubBase, { - _id: 0, - _subSignals: {}, - _subCallbacks: {} - }) - } - - var _pubSubBase = { - _id: null, - _subCallbacks: null, - _subSignals: null, - on: function(signal, callback) { - if (!this._subCallbacks[signal]) { - this._subCallbacks[signal] = {}; - } - this._id += 1; - this._subCallbacks[signal][this._id] = callback; - this._subSignals[this._id] = signal; - return this._id - }, - off: function(subId) { - var signal = this._subSignals[subId]; - delete this._subCallbacks[signal][subId]; - delete this._subSignals[subId]; - }, - once: function(signal, callback) { - var subId = this.on(signal, bind$2(this, function() { - callback.apply(this, arguments); - this.off(subId); - })); - }, - fire: function(signal) { - var args = slice$2(arguments, 1); - each$4(this._subCallbacks[signal], function(callback) { - callback.apply(this, args); - }); - } - }; - - var lzString = createCommonjsModule(function (module) { - /* eslint-disable */ - // Copyright (c) 2013 Pieroxy - // This work is free. You can redistribute it and/or modify it - // under the terms of the WTFPL, Version 2 - // For more information see LICENSE.txt or http://www.wtfpl.net/ - // - // For more information, the home page: - // http://pieroxy.net/blog/pages/lz-string/testing.html - // - // LZ-based compression algorithm, version 1.4.4 - var LZString = (function() { - - // private property - var f = String.fromCharCode; - var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; - var baseReverseDic = {}; - - function getBaseValue(alphabet, character) { - if (!baseReverseDic[alphabet]) { - baseReverseDic[alphabet] = {}; - for (var i=0 ; i>> 8; - buf[i*2+1] = current_value % 256; - } - return buf; - }, - - //decompress from uint8array (UCS-2 big endian format) - decompressFromUint8Array:function (compressed) { - if (compressed===null || compressed===undefined){ - return LZString.decompress(compressed); - } else { - var buf=new Array(compressed.length/2); // 2 bytes per character - for (var i=0, TotalLen=buf.length; i> 1; - } - } else { - value = 1; - for (i=0 ; i> 1; - } - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - delete context_dictionaryToCreate[context_w]; - } else { - value = context_dictionary[context_w]; - for (i=0 ; i> 1; - } - - - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - // Add wc to the dictionary. - context_dictionary[context_wc] = context_dictSize++; - context_w = String(context_c); - } - } - - // Output the code for w. - if (context_w !== "") { - if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) { - if (context_w.charCodeAt(0)<256) { - for (i=0 ; i> 1; - } - } else { - value = 1; - for (i=0 ; i> 1; - } - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - delete context_dictionaryToCreate[context_w]; - } else { - value = context_dictionary[context_w]; - for (i=0 ; i> 1; - } - - - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - } - - // Mark the end of the stream - value = 2; - for (i=0 ; i> 1; - } - - // Flush the last char - while (true) { - context_data_val = (context_data_val << 1); - if (context_data_position == bitsPerChar-1) { - context_data.push(getCharFromInt(context_data_val)); - break; - } - else { context_data_position++; } - } - return context_data.join(''); - }, - - decompress: function (compressed) { - if (compressed == null) { return ""; } - if (compressed == "") { return null; } - return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); }); - }, - - _decompress: function (length, resetValue, getNextValue) { - var dictionary = [], - next, - enlargeIn = 4, - dictSize = 4, - numBits = 3, - entry = "", - result = [], - i, - w, - bits, resb, maxpower, power, - c, - data = {val:getNextValue(0), position:resetValue, index:1}; - - for (i = 0; i < 3; i += 1) { - dictionary[i] = i; - } - - bits = 0; - maxpower = Math.pow(2,2); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - switch (next = bits) { - case 0: - bits = 0; - maxpower = Math.pow(2,8); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - c = f(bits); - break; - case 1: - bits = 0; - maxpower = Math.pow(2,16); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - c = f(bits); - break; - case 2: - return ""; - } - dictionary[3] = c; - w = c; - result.push(c); - while (true) { - if (data.index > length) { - return ""; - } - - bits = 0; - maxpower = Math.pow(2,numBits); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - switch (c = bits) { - case 0: - bits = 0; - maxpower = Math.pow(2,8); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - dictionary[dictSize++] = f(bits); - c = dictSize-1; - enlargeIn--; - break; - case 1: - bits = 0; - maxpower = Math.pow(2,16); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - dictionary[dictSize++] = f(bits); - c = dictSize-1; - enlargeIn--; - break; - case 2: - return result.join(''); - } - - if (enlargeIn == 0) { - enlargeIn = Math.pow(2, numBits); - numBits++; - } - - if (dictionary[c]) { - entry = dictionary[c]; - } else { - if (c === dictSize) { - entry = w + w.charAt(0); - } else { - return null; - } - } - result.push(entry); - - // Add w+entry[0] to the dictionary. - dictionary[dictSize++] = w + entry.charAt(0); - enlargeIn--; - - w = entry; - - if (enlargeIn == 0) { - enlargeIn = Math.pow(2, numBits); - numBits++; - } - - } - } - }; - return LZString; - })(); - - if( module != null ) { - module.exports = LZString; - } - }); - - var compression = compressionPlugin; - - function compressionPlugin() { - return { - get: get, - set: set, - } - - function get(super_fn, key) { - var val = super_fn(key); - if (!val) { return val } - var decompressed = lzString.decompress(val); - // fallback to existing values that are not compressed - return (decompressed == null) ? val : this._deserialize(decompressed) - } - - function set(super_fn, key, val) { - var compressed = lzString.compress(this._serialize(val)); - super_fn(key, compressed); - } - } - - // sort of persist on the user side - - var storages = [localStorage_1, cookieStorage]; - var plugins = [defaults, events, compression]; - - var localStore = storeEngine.createStore(storages, plugins); - - var Global$3 = util.Global; - - var sessionStorage_1 = { - name: 'sessionStorage', - read: read$2, - write: write$2, - each: each$5, - remove: remove$2, - clearAll: clearAll$2 - }; - - function sessionStorage() { - return Global$3.sessionStorage - } - - function read$2(key) { - return sessionStorage().getItem(key) - } - - function write$2(key, data) { - return sessionStorage().setItem(key, data) - } - - function each$5(fn) { - for (var i = sessionStorage().length - 1; i >= 0; i--) { - var key = sessionStorage().key(i); - fn(read$2(key), key); - } - } - - function remove$2(key) { - return sessionStorage().removeItem(key) - } - - function clearAll$2() { - return sessionStorage().clear() - } - - // session store with watch - // @1.5.0 stop using the expired plugin and deal it ourself - // import expiredPlugin from 'store/plugins/expire' - - var storages$1 = [sessionStorage_1, cookieStorage]; - var plugins$1 = [defaults, compression]; - - var sessionStore = storeEngine.createStore(storages$1, plugins$1); - - // export store interface - - // export back the raw version for development purposes - var localStore$1 = localStore; - var sessionStore$1 = sessionStore; - - // ported from jsonql-params-validator - - /** - * @param {*} args arguments to send - *@return {object} formatted payload - */ - var formatPayload = function (args) { - var obj; - - return ( - ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) - ); - }; - - /** - * Get name from the payload (ported back from jsonql-koa) - * @param {*} payload to extract from - * @return {string} name - */ - function getNameFromPayload(payload) { - return Object.keys(payload)[0] - } - - /** - * wrapper method to add the timestamp as well - * @param {string} resolverName - * @param {*} payload - * @return {object} delierable - */ - function createDeliverable(resolverName, payload) { - var obj; - - return ( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME] = [ timestamp$1() ], obj ) - } - - /** - * @param {string} resolverName name of function - * @param {array} [args=[]] from the ...args - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createQuery(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - - if (isString(resolverName) && isArray(args)) { - var payload = formatPayload(args); - if (jsonp === true) { - return payload; - } - return createDeliverable(resolverName, payload) - } - throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) - } - - /** - * @param {string} resolverName name of function - * @param {*} payload to send - * @param {object} [condition={}] for what - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createMutation(resolverName, payload, condition, jsonp) { - if ( condition === void 0 ) condition = {}; - if ( jsonp === void 0 ) jsonp = false; - - var _payload = {}; - _payload[PAYLOAD_PARAM_NAME] = payload; - _payload[CONDITION_PARAM_NAME] = condition; - if (jsonp === true) { - return _payload; - } - if (isString(resolverName)) { - return createDeliverable(resolverName, _payload) - } - throw new JsonqlValidationError("[createMutation] expect resolverName to be string!", { resolverName: resolverName, payload: payload, condition: condition }) - } - - /** - * @return {object} _cb as key with timestamp - */ - var cacheBurst = function () { return ({ _cb: timestamp$1() }); }; - - // break up from node-middleware - - // ported from http-client - - /** - * handle the return data - * @TODO how to handle the return timestamp and calculate the diff? - * @param {object} result return from server - * @return {object} strip the data part out, or if the error is presented - */ - var resultHandler = function (result) { return ( - (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result - ); }; - - // new 1.5.0 - - // this becomes the base class instead of the HttpCls - var StoreClass = function StoreClass(opts) { - this.opts = opts; - // make it a string - this.instanceKey = hashCode$1(this.opts.hostname); - // pass this store for use later - this.localStore = localStore$1; - this.sessionStore = sessionStore$1; - /* - if (this.opts.debugOn) { // reuse this to clear out the data - this.log('clear all stores') - localStore.clearAll() - sessionStore.clearAll() - - localStore.set('TEST', Date.now()) - sessionStore.set('TEST', Date.now()) - } - */ - }; - - var prototypeAccessors = { lset: { configurable: true },lget: { configurable: true },sset: { configurable: true },sget: { configurable: true } }; - // store in local storage id by the instanceKey - // values should be an object so with key so we just merge - // into the existing store without going through the keys - StoreClass.prototype.__setMethod = function __setMethod (storeType, values) { - var obj; - - var store = this[storeType]; - var data = this.__getMethod(storeType); - var skey = this.opts.storageKey; - var ikey = this.instanceKey; - store.set(skey, ( obj = {}, obj[ikey] = data ? merge({}, data, values) : values, obj )); - }; - // return the data id by the instaceKey - StoreClass.prototype.__getMethod = function __getMethod (storeType) { - var store = this[storeType]; - var data = store.get(this.opts.storageKey); - return data ? data[this.instanceKey] : false - }; - // remove from local store id by instanceKey - StoreClass.prototype.__delMethod = function __delMethod (storeType, key) { - var data = this.__getMethod(storeType); - if (data) { - var store = {}; - for (var k in data) { - if (k !== key) { - store[k] = data[k]; - } - } - this.__setMethod(storeType, store); - } - }; - // clear everything by this instanceKey - StoreClass.prototype.__clearMethod = function __clearMethod (storeKey) { - var skey = this.opts.storageKey; - var store = this[storeKey]; - var data = store.get(skey); - if (data) { - var _store = {}; - for (var k in data) { - if (k !== this.instanceKey) { - _store[k] = data[k]; - } - } - store.set(skey, _store); - } - }; - // Alias for different store - prototypeAccessors.lset.set = function (values) { - return this.__setMethod(CLS_LOCAL_STORE_NAME, values) - }; - - prototypeAccessors.lget.get = function () { - return this.__getMethod(CLS_LOCAL_STORE_NAME) - }; - - StoreClass.prototype.ldel = function ldel (key) { - return this.__delMethod(CLS_LOCAL_STORE_NAME, key) - }; - - StoreClass.prototype.lclear = function lclear () { - return this.__clearMethod(CLS_LOCAL_STORE_NAME) - }; - - // store in session store id by the instanceKey - prototypeAccessors.sset.set = function (values) { - // this.log('--- sset ---', values) - return this.__setMethod(CLS_SESS_STORE_NAME, values) - }; - - prototypeAccessors.sget.get = function () { - return this.__getMethod(CLS_SESS_STORE_NAME) - }; - - StoreClass.prototype.sdel = function sdel (key) { - return this.__delMethod(CLS_SESS_STORE_NAME, key) - }; - - StoreClass.prototype.sclear = function sclear () { - return this.__clearMethod(CLS_SESS_STORE_NAME) - }; - - Object.defineProperties( StoreClass.prototype, prototypeAccessors ); - - // base HttpClass - - // extract the one we need - var POST = API_REQUEST_METHODS[0]; - var PUT = API_REQUEST_METHODS[1]; - - var HttpClass = /*@__PURE__*/(function (StoreClass) { - function HttpClass(opts) { - StoreClass.call(this, opts); - // change the way how we init Fly - // flyio now become external depedencies and it makes it easier to switch - // @BUG should we run test to check if we have the windows object? - // this.log(opts) - // this.fly = opts.Fly ? new opts.Fly() : new Fly() - // to a different environment like WeChat mini app - - this.extraHeader = {}; - // @1.2.1 for adding query to the call on the fly - this.extraParams = {}; - // this.log('start up opts', opts); - this.reqInterceptor(); - this.resInterceptor(); - } - - if ( StoreClass ) HttpClass.__proto__ = StoreClass; - HttpClass.prototype = Object.create( StoreClass && StoreClass.prototype ); - HttpClass.prototype.constructor = HttpClass; - - var prototypeAccessors = { headers: { configurable: true } }; - - // set headers for that one call - prototypeAccessors.headers.set = function (header) { - this.extraHeader = header; - }; - - /** - * Create the reusage request method - * @param {object} payload jsonql payload - * @param {object} options extra options add the request - * @param {object} headers extra headers add to the call - * @return {object} the fly request instance - */ - HttpClass.prototype.request = function request (payload, options, headers) { - var obj; - - if ( options === void 0 ) options = {}; - if ( headers === void 0 ) headers = {}; - this.headers = headers; - var params = merge({}, cacheBurst(), this.extraParams); - // @TODO need to add a jsonp url and payload - if (this.opts.enableJsonp) { - var resolverName = getNameFromPayload(payload); - params = merge({}, params, ( obj = {}, obj[JSONP_CALLBACK_NAME] = resolverName, obj )); - payload = payload[resolverName]; - } - // double up the url param and see what happen @TODO remove later - var reqParams = merge({}, { method: POST, params: params }, options); - this.log('request params', reqParams, this.jsonqlEndpoint); - - return this.fly.request(this.jsonqlEndpoint, payload, reqParams) - }; - - /** - * This will replace the create baseRequest method - * - */ - HttpClass.prototype.reqInterceptor = function reqInterceptor () { - var this$1 = this; - - this.fly.interceptors.request.use( - function (req) { - var headers = this$1.getHeaders(); - this$1.log('request interceptor call', headers); - - for (var key in headers) { - req.headers[key] = headers[key]; - } - return req; - } - ); - }; - - // @TODO - HttpClass.prototype.processJsonp = function processJsonp (result) { - return resultHandler(result) - }; - - /** - * This will be replacement of the first then call - * - */ - HttpClass.prototype.resInterceptor = function resInterceptor () { - var this$1 = this; - - var self = this; - var jsonp = self.opts.enableJsonp; - this.fly.interceptors.response.use( - function (res) { - this$1.log('response interceptor call', res); - self.cleanUp(); - // now more processing here - // there is a problem if we throw the result.error here - // the original data is lost, so we need to do what we did before - // deal with that error in the first then instead - var result = isString$1(res.data) ? JSON.parse(res.data) : res.data; - if (jsonp) { - return self.processJsonp(result) - } - return resultHandler(result) - }, - // this get call when it's not 200 - function (err) { - self.cleanUp(); - this$1.log(LOG_ERROR_SWITCH, err); - throw new JsonqlServerError('Server side error', err) - } - ); - }; - - /** - * Get the headers inject into the call - * @return {object} headers - */ - HttpClass.prototype.getHeaders = function getHeaders () { - if (this.opts.enableAuth) { - return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader) - } - return merge({}, DEFAULT_HEADER, this.extraHeader) - }; - - /** - * Post http call operation to clean up things we need - */ - HttpClass.prototype.cleanUp = function cleanUp () { - this.extraHeader = {}; - this.extraParams = {}; - }; - - /** - * GET for contract only - * @return {promise} resolve the contract - */ - HttpClass.prototype.getRemoteContract = function getRemoteContract () { - var this$1 = this; - - if (this.opts.showContractDesc) { - this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM); - } - return this.request({}, {method: 'GET'}, this.contractHeader) - .then(clientErrorsHandler) - .then(function (result) { - this$1.log('get contract result', result); - // when refresh the window the result is different! - // @TODO need to check the Koa side about why is that - // also it should set a flag if we want the description or not - if (result.cache && result.contract) { - return result.contract; - } - // just the normal result - return result - }) - .catch(function (err) { - this$1.log(LOG_ERROR_SWITCH, 'getRemoteContract err', err); - throw new JsonqlServerError('getRemoteContract', err) - }) - }; - - /** - * POST to server - query - * @param {object} name of the resolver - * @param {array} args arguments - * @return {object} promise resolve to the resolver return - */ - HttpClass.prototype.query = function query (name, args) { - if ( args === void 0 ) args = []; - - return this.request(createQuery(name, args)) - .then(clientErrorsHandler) - }; - - /** - * PUT to server - mutation - * @param {string} name of resolver - * @param {object} payload what it said - * @param {object} conditions what it said - * @return {object} promise resolve to the resolver return - */ - HttpClass.prototype.mutation = function mutation (name, payload, conditions) { - if ( payload === void 0 ) payload = {}; - if ( conditions === void 0 ) conditions = {}; - - return this.request(createMutation(name, payload, conditions), {method: PUT}) - .then(clientErrorsHandler) - }; - - Object.defineProperties( HttpClass.prototype, prototypeAccessors ); - - return HttpClass; - }(StoreClass)); - - // all the contract related methods will be here - - // export - var ContractClass = /*@__PURE__*/(function (HttpClass) { - function ContractClass(opts) { - HttpClass.call(this, opts); - } - - if ( HttpClass ) ContractClass.__proto__ = HttpClass; - ContractClass.prototype = Object.create( HttpClass && HttpClass.prototype ); - ContractClass.prototype.constructor = ContractClass; - - var prototypeAccessors = { contractHeader: { configurable: true } }; - - /** - * return the contract public api - * @return {object} contract - */ - ContractClass.prototype.getContract = function getContract () { - var contract = this.readContract(); - this.log('getContract first call', contract); - return contract ? Promise.resolve(contract) - : this.getRemoteContract().then(this.storeContract.bind(this)) - }; - - /** - * We are changing the way how to auth to get the contract.json - * Instead of in the url, we will be putting that key value in the header - * @return {object} header - */ - prototypeAccessors.contractHeader.get = function () { - var base = {}; - if (this.opts.contractKey !== false) { - base[this.opts.contractKeyName] = this.opts.contractKey; - } - return base; - }; - - /** - * Save the contract to local store - * @param {object} contract to save - * @return {object|boolean} false when its not a contract or contract on OK - */ - ContractClass.prototype.storeContract = function storeContract (contract) { - var obj; - - // first need to check if the contract is a contract - if (!isContract(contract)) { - throw new JsonqlValidationError("Contract is malformed!") - } - this.lset = ( obj = {}, obj[CLS_CONTRACT_NAME] = contract, obj ); - // return it - this.log('storeContract return result', contract); - return contract; - }; - - /** - * return the contract from options or localStore - * @return {object|boolean} false on not found - */ - ContractClass.prototype.readContract = function readContract () { - var contract = isContract(this.opts.contract); - if (contract !== false) { - return contract; - } - var data = this.lget; - if (data) { - return data[CLS_CONTRACT_NAME] - } - return false; - }; - - Object.defineProperties( ContractClass.prototype, prototypeAccessors ); - - return ContractClass; - }(HttpClass)); - - // this is the new auth class that integrate with the jsonql-jwt - // export - var AuthClass = /*@__PURE__*/(function (ContractClass) { - function AuthClass(opts) { - ContractClass.call(this, opts); - if (opts.enableAuth) { - this.setDecoder = jwtDecode; - } - } - - if ( ContractClass ) AuthClass.__proto__ = ContractClass; - AuthClass.prototype = Object.create( ContractClass && ContractClass.prototype ); - AuthClass.prototype.constructor = AuthClass; - - var prototypeAccessors = { profileIndex: { configurable: true },setDecoder: { configurable: true },saveProfile: { configurable: true },readProfile: { configurable: true },jsonqlToken: { configurable: true },jsonqlUserdata: { configurable: true } }; - - /** - * for overwrite - * @param {string} token stored token - * @return {string} token - */ - AuthClass.prototype.decoder = function decoder (token) { - return token; - }; - - /** - * set the profile index - * @param {number} idx - */ - prototypeAccessors.profileIndex.set = function (idx) { - var obj; - - var key = CLS_PROFILE_IDX; - if (isNumber$1(idx)) { - this[key] = idx; - if (this.opts.persistToken) { - this.lset = ( obj = {}, obj[key] = idx, obj ); - } - return; - } - throw new JsonqlValidationError('profileIndex', ("Expect idx to be number but got " + (typeof idx))) - }; - - /** - * get the profile index - * @return {number} idx - */ - prototypeAccessors.profileIndex.get = function () { - var key = CLS_PROFILE_IDX; - if (this.opts.persistToken) { - var data = this.lget; - if (data[key]) { - return data[key] - } - } - return this[key] ? this[key] : ZERO_IDX - }; - - /** - * Return the token from session store - * @param {number} [idx=false] profile index - * @return {string} token - */ - AuthClass.prototype.rawAuthToken = function rawAuthToken (idx) { - if ( idx === void 0 ) idx = false; - - if (idx !== false) { - this.profileIndex = idx; - } - // this should return from the base - return this.jsonqlToken; // see base-cls - }; - - /** - * Setter to add a decoder when retrieve user token - * @param {function} d a decoder - */ - prototypeAccessors.setDecoder.set = function (d) { - if (typeof d === 'function') { - this.decoder = d; - } - }; - - /** - * getter to return the session or local store set method - * @param {*} data to save - * @return {object} set method - */ - prototypeAccessors.saveProfile.set = function (data) { - if (this.opts.persistToken) { - // this.log('--- saveProfile lset ---', data) - this.lset = data; - } else { - // this.log('--- saveProfile sset ---', data) - this.sset = data; - } - }; - - /** - * getter to return the session or local store get method - * @return {object} get method - */ - prototypeAccessors.readProfile.get = function () { - return this.opts.persistToken ? this.lget : this.sget - }; - - // these were in the base class before but it should be here - /** - * save token - * @param {string} token to store - * @return {string|boolean} false on failed - */ - prototypeAccessors.jsonqlToken.set = function (token) { - var obj; - - var data = this.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - // @TODO also have to make sure the token is not already existed! - var tokens = (data && data[key]) ? data[key] : []; - tokens.push(token); - this.saveProfile = ( obj = {}, obj[key] = tokens, obj ); - // store the userdata - this.jsonqlUserdata = this.decoder(token); - }; - - /** - * Jsonql token getter - * 1.5.1 each token associate with the same profileIndex - * @return {string|boolean} false when failed - */ - prototypeAccessors.jsonqlToken.get = function () { - var data = this.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - if (data && data[key]) { - this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex]); - return data[key][this.profileIndex] - } - return false - }; - - /** - * this one will use the sessionStore - * basically we hook this onto the token store and decode it to store here - * we only store one decoded user data at a time, but the token can be multiple - */ - prototypeAccessors.jsonqlUserdata.set = function (userdata) { - var obj; - - this.sset = ( obj = {}, obj[USERDATA_TABLE] = userdata, obj ); - }; - - /** - * this one store in the session store - * get login userdata decoded jwt - * 1.5.1 each userdata associate with the same profileIndex - * @return {object|null} - */ - prototypeAccessors.jsonqlUserdata.get = function () { - var data = this.sget; - return data ? data[USERDATA_TABLE] : false - }; - - /** - * Construct the auth header - * @return {object} header - */ - AuthClass.prototype.getAuthHeader = function getAuthHeader () { - var obj; - - var token = this.jsonqlToken; // only call the getter to get the default one - return token ? ( obj = {}, obj[this.opts.AUTH_HEADER] = (BEARER + " " + token), obj ) : {}; - }; - - /** - * return all the stored token and decode it - * @param {number} [idx=false] profile index - * @return {array|boolean|string} false not found or array - */ - AuthClass.prototype.getProfiles = function getProfiles (idx) { - if ( idx === void 0 ) idx = false; - - var self = this; // just in case the scope problem - var data = self.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - if (data && data[key]) { - if (idx !== false && isNumber$1(idx)) { - return data[key][idx] || false - } - return data[key].map(self.decoder.bind(self)) - } - return false - }; - - /** - * call after the login - * @param {string} token return from server - * @return {object} decoded token to userdata object - */ - AuthClass.prototype.postLoginAction = function postLoginAction (token) { - this.jsonqlToken = token; - return token - }; - - /** - * call after the logout @TODO - */ - AuthClass.prototype.postLogoutAction = function postLogoutAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - console.info("postLogoutAction", args); - }; - - Object.defineProperties( AuthClass.prototype, prototypeAccessors ); - - return AuthClass; - }(ContractClass)); - - // this the core of the internal storage management - - // This class will only focus on the storage system - var JsonqlBaseClient = /*@__PURE__*/(function (AuthCls) { - function JsonqlBaseClient(fly, opts) { - // change at 1.4.10 pass it directly without init it - this.fly = fly; - AuthCls.call(this, opts); - } - - if ( AuthCls ) JsonqlBaseClient.__proto__ = AuthCls; - JsonqlBaseClient.prototype = Object.create( AuthCls && AuthCls.prototype ); - JsonqlBaseClient.prototype.constructor = JsonqlBaseClient; - - var prototypeAccessors = { jsonqlEndpoint: { configurable: true } }; - - /** - * construct the end point - * @return {string} the end point to call - */ - prototypeAccessors.jsonqlEndpoint.get = function () { - var baseUrl = this.opts.hostname || ''; - return [baseUrl, this.opts.jsonqlPath].join('/') - }; - - /** - * simple log - */ - JsonqlBaseClient.prototype.log = function log () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - if (this.opts.debugOn === true) { - var fns = ['info', 'error']; - var idx = (args[0] === LOG_ERROR_SWITCH) ? 1 : 0; - Reflect.apply(console[fns[idx]], console, args.splice(0, idx)); - } - }; - - Object.defineProperties( JsonqlBaseClient.prototype, prototypeAccessors ); - - return JsonqlBaseClient; - }(AuthClass)); - - // export interface - - // all the client configuration options here - var constProps = { - contract: false, - MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong? - CONTENT_TYPE: CONTENT_TYPE, - BEARER: BEARER, - AUTH_HEADER: AUTH_HEADER - }; - - // grab the localhost name and put into the hostname as default - var getHostName = function () { - try { - return [window.location.protocol, window.location.host].join('//') - } catch(e) { - return null - } - }; - - var appProps$1 = { - - hostname: createConfig$1(getHostName(), [STRING_TYPE]), // required the hostname - jsonqlPath: createConfig$1(JSONQL_PATH, [STRING_TYPE]), // The path on the server - - loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), - logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), - // add to koa v1.3.0 - this might remove in the future - enableJsonp: createConfig$1(false, [BOOLEAN_TYPE]), - enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), - // enable useJwt by default @TODO replace with something else and remove them later - useJwt: createConfig$1(true, [BOOLEAN_TYPE]), - // when true then store infinity or pass a time in seconds then we check against - // the token date of creation - persistToken: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE]), - // the header - // v1.2.0 we are using this option during the dev - // so it won't save anything to the localstorage and fetch a new contract - // whenever the browser reload - useLocalstorage: createConfig$1(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage - storageKey: createConfig$1(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage - authKey: createConfig$1(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage - contractExpired: createConfig$1(0, [NUMBER_TYPE]),// -1 always fetch contract, - // 0 never expired, - // > 0 then compare the timestamp with the current one to see if we need to get contract again - // useful during development - keepContract: createConfig$1(true, [BOOLEAN_TYPE]), - exposeContract: createConfig$1(false, [BOOLEAN_TYPE]), - exposeStore: createConfig$1(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn - // @1.2.1 new option for the contract-console to fetch the contract with description - showContractDesc: createConfig$1(false, [BOOLEAN_TYPE]), - contractKey: createConfig$1(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this - contractKeyName: createConfig$1(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs - enableTimeout: createConfig$1(false, [BOOLEAN_TYPE]), // @TODO - timeout: createConfig$1(5000, [NUMBER_TYPE]), // 5 seconds - returnInstance: createConfig$1(false, [BOOLEAN_TYPE]), - allowReturnRawToken: createConfig$1(false, [BOOLEAN_TYPE]), - debugOn: createConfig$1(false, [BOOLEAN_TYPE]) - }; - - // This is for the sync version therefore we don't need to care about the contract options - - function checkOptions(config) { - return checkConfig$1(config, appProps$1, constProps) - } - - // export interface - - // sync version without needing the promise - function checkOptions$1(config) { - return objHasProp(config, CHECKED_KEY) ? config : checkOptions(config) - } - - var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); - var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); - - // making all the functionality on it's own - // import { WatchClass } from './watch' - - var SuspendClass = function SuspendClass() { - // suspend, release and queue - this.__suspend__ = null; - this.queueStore = new Set(); - /* - this.watch('suspend', function(value, prop, oldValue) { - this.logger(`${prop} set from ${oldValue} to ${value}`) - // it means it set the suspend = true then release it - if (oldValue === true && value === false) { - // we want this happen after the return happens - setTimeout(() => { - this.release() - }, 1) - } - return value; // we need to return the value to store it - }) - */ - }; - - var prototypeAccessors$1 = { $suspend: { configurable: true },$queues: { configurable: true } }; - - /** - * setter to set the suspend and check if it's boolean value - * @param {boolean} value to trigger - */ - prototypeAccessors$1.$suspend.set = function (value) { - var this$1 = this; - - if (typeof value === 'boolean') { - var lastValue = this.__suspend__; - this.__suspend__ = value; - this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); - if (lastValue === true && value === false) { - setTimeout(function () { - this$1.release(); - }, 1); - } - } else { - throw new Error("$suspend only accept Boolean value!") - } - }; - - /** - * queuing call up when it's in suspend mode - * @param {any} value - * @return {Boolean} true when added or false when it's not - */ - SuspendClass.prototype.$queue = function $queue () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - if (this.__suspend__ === true) { - this.logger('($queue)', 'added to $queue', args); - // there shouldn't be any duplicate ... - this.queueStore.add(args); - } - return this.__suspend__; - }; - - /** - * a getter to get all the store queue - * @return {array} Set turn into Array before return - */ - prototypeAccessors$1.$queues.get = function () { - var size = this.queueStore.size; - this.logger('($queues)', ("size: " + size)); - if (size > 0) { - return Array.from(this.queueStore) - } - return [] - }; - - /** - * Release the queue - * @return {int} size if any - */ - SuspendClass.prototype.release = function release () { - var this$1 = this; - - var size = this.queueStore.size; - this.logger('(release)', ("Release was called " + size)); - if (size > 0) { - var queue = Array.from(this.queueStore); - this.queueStore.clear(); - this.logger('queue', queue); - queue.forEach(function (args) { - this$1.logger(args); - Reflect.apply(this$1.$trigger, this$1, args); - }); - this.logger(("Release size " + (this.queueStore.size))); - } - }; - - Object.defineProperties( SuspendClass.prototype, prototypeAccessors$1 ); - - // break up the main file because its getting way too long - - var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { - function NbEventServiceBase(config) { - if ( config === void 0 ) config = {}; - - SuspendClass.call(this); - if (config.logger && typeof config.logger === 'function') { - this.logger = config.logger; - } - this.keep = config.keep; - // for the $done setter - this.result = config.keep ? [] : null; - // we need to init the store first otherwise it could be a lot of checking later - this.normalStore = new Map(); - this.lazyStore = new Map(); - } - - if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; - NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); - NbEventServiceBase.prototype.constructor = NbEventServiceBase; - - var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; - - /** - * validate the event name(s) - * @param {string[]} evt event name - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validateEvt = function validateEvt () { - var this$1 = this; - var evt = [], len = arguments.length; - while ( len-- ) evt[ len ] = arguments[ len ]; - - evt.forEach(function (e) { - if (typeof e !== 'string') { - this$1.logger('(validateEvt)', e); - throw new Error("event name must be string type!") - } - }); - return true; - }; - - /** - * Simple quick check on the two main parameters - * @param {string} evt event name - * @param {function} callback function to call - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validate = function validate (evt, callback) { - if (this.validateEvt(evt)) { - if (typeof callback === 'function') { - return true; - } - } - throw new Error("callback required to be function type!") - }; - - /** - * Check if this type is correct or not added in V1.5.0 - * @param {string} type for checking - * @return {boolean} true on OK - */ - NbEventServiceBase.prototype.validateType = function validateType (type) { - var types = ['on', 'only', 'once', 'onlyOnce']; - return !!types.filter(function (t) { return type === t; }).length; - }; - - /** - * Run the callback - * @param {function} callback function to execute - * @param {array} payload for callback - * @param {object} ctx context or null - * @return {void} the result store in $done - */ - NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { - this.logger('(run)', callback, payload, ctx); - this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); - }; - - /** - * Take the content out and remove it from store id by the name - * @param {string} evt event name - * @param {string} [storeName = lazyStore] name of store - * @return {object|boolean} content or false on not found - */ - NbEventServiceBase.prototype.takeFromStore = function takeFromStore (evt, storeName) { - if ( storeName === void 0 ) storeName = 'lazyStore'; - - var store = this[storeName]; // it could be empty at this point - if (store) { - this.logger('(takeFromStore)', storeName, store); - if (store.has(evt)) { - var content = store.get(evt); - this.logger('(takeFromStore)', ("has " + evt), content); - store.delete(evt); - return content; - } - return false; - } - throw new Error((storeName + " is not supported!")) - }; - - /** - * The add to store step is similar so make it generic for resuse - * @param {object} store which store to use - * @param {string} evt event name - * @param {spread} args because the lazy store and normal store store different things - * @return {array} store and the size of the store - */ - NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { - var args = [], len = arguments.length - 2; - while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; - - var fnSet; - if (store.has(evt)) { - this.logger('(addToStore)', (evt + " existed")); - fnSet = store.get(evt); - } else { - this.logger('(addToStore)', ("create new Set for " + evt)); - // this is new - fnSet = new Set(); - } - // lazy only store 2 items - this is not the case in V1.6.0 anymore - // we need to check the first parameter is string or not - if (args.length > 2) { - if (Array.isArray(args[0])) { // lazy store - // check if this type of this event already register in the lazy store - var t = args[2]; - if (!this.checkTypeInLazyStore(evt, t)) { - fnSet.add(args); - } - } else { - if (!this.checkContentExist(args, fnSet)) { - this.logger('(addToStore)', "insert new", args); - fnSet.add(args); - } - } - } else { // add straight to lazy store - fnSet.add(args); - } - store.set(evt, fnSet); - return [store, fnSet.size] - }; - - /** - * @param {array} args for compare - * @param {object} fnSet A Set to search from - * @return {boolean} true on exist - */ - NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { - var list = Array.from(fnSet); - return !!list.filter(function (l) { - var hash = l[0]; - if (hash === args[0]) { - return true; - } - return false; - }).length; - }; - - /** - * get the existing type to make sure no mix type add to the same store - * @param {string} evtName event name - * @param {string} type the type to check - * @return {boolean} true you can add, false then you can't add this type - */ - NbEventServiceBase.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { - this.validateEvt(evtName, type); - var all = this.$get(evtName, true); - if (all === false) { - // pristine it means you can add - return true; - } - // it should only have ONE type in ONE event store - return !all.filter(function (list) { - var t = list[3]; - return type !== t; - }).length; - }; - - /** - * This is checking just the lazy store because the structure is different - * therefore we need to use a new method to check it - */ - NbEventServiceBase.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { - this.validateEvt(evtName, type); - var store = this.lazyStore.get(evtName); - this.logger('(checkTypeInLazyStore)', store); - if (store) { - return !!Array - .from(store) - .filter(function (l) { - var t = l[2]; - return t !== type; - }).length - } - return false; - }; - - /** - * wrapper to re-use the addToStore, - * V1.3.0 add extra check to see if this type can add to this evt - * @param {string} evt event name - * @param {string} type on or once - * @param {function} callback function - * @param {object} context the context the function execute in or null - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { - if ( context === void 0 ) context = null; - - this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); - // @TODO we need to check the existing store for the type first! - if (this.checkTypeInStore(evt, type)) { - this.logger('(addToNormalStore)', (type + " can add to " + evt + " normal store")); - var key = this.hashFnToKey(callback); - var args = [this.normalStore, evt, key, callback, context, type]; - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.normalStore = _store; - return size; - } - return false; - }; - - /** - * Add to lazy store this get calls when the callback is not register yet - * so we only get a payload object or even nothing - * @param {string} evt event name - * @param {array} payload of arguments or empty if there is none - * @param {object} [context=null] the context the callback execute in - * @param {string} [type=false] register a type so no other type can add to this evt - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - // this is add in V1.6.0 - // when there is type then we will need to check if this already added in lazy store - // and no other type can add to this lazy store - var args = [this.lazyStore, evt, this.toArray(payload), context]; - if (type) { - args.push(type); - } - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.lazyStore = _store; - return size; - }; - - /** - * make sure we store the argument correctly - * @param {*} arg could be array - * @return {array} make sured - */ - NbEventServiceBase.prototype.toArray = function toArray (arg) { - return Array.isArray(arg) ? arg : [arg]; - }; - - /** - * setter to store the Set in private - * @param {object} obj a Set - */ - prototypeAccessors.normalStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); - }; - - /** - * @return {object} Set object - */ - prototypeAccessors.normalStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) - }; - - /** - * setter to store the Set in lazy store - * @param {object} obj a Set - */ - prototypeAccessors.lazyStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); - }; - - /** - * @return {object} the lazy store Set - */ - prototypeAccessors.lazyStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) - }; - - /** - * generate a hashKey to identify the function call - * The build-in store some how could store the same values! - * @param {function} fn the converted to string function - * @return {string} hashKey - */ - NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { - return hashCode(fn.toString()) + ''; - }; - - Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); - - return NbEventServiceBase; - }(SuspendClass)); - - // The top level - // export - var EventService = /*@__PURE__*/(function (NbStoreService) { - function EventService(config) { - if ( config === void 0 ) config = {}; - - NbStoreService.call(this, config); - } - - if ( NbStoreService ) EventService.__proto__ = NbStoreService; - EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); - EventService.prototype.constructor = EventService; - - var prototypeAccessors = { $done: { configurable: true } }; - - /** - * logger function for overwrite - */ - EventService.prototype.logger = function logger () {}; - - ////////////////////////// - // PUBLIC METHODS // - ////////////////////////// - - /** - * Register your evt handler, note we don't check the type here, - * we expect you to be sensible and know what you are doing. - * @param {string} evt name of event - * @param {function} callback bind method --> if it's array or not - * @param {object} [context=null] to execute this call in - * @return {number} the size of the store - */ - EventService.prototype.$on = function $on (evt , callback , context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - var type = 'on'; - this.validate(evt, callback); - // first need to check if this evt is in lazy store - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register first then call later - if (lazyStoreContent === false) { - this.logger('($on)', (evt + " callback is not in lazy store")); - // @TODO we need to check if there was other listener to this - // event and are they the same type then we could solve that - // register the different type to the same event name - - return this.addToNormalStore(evt, type, callback, context) - } - this.logger('($on)', (evt + " found in lazy store")); - // this is when they call $trigger before register this callback - var size = 0; - lazyStoreContent.forEach(function (content) { - var payload = content[0]; - var ctx = content[1]; - var t = content[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.logger("($on)", ("call run on " + evt)); - this$1.run(callback, payload, context || ctx); - size += this$1.addToNormalStore(evt, type, callback, context || ctx); - }); - return size; - }; - - /** - * once only registered it once, there is no overwrite option here - * @NOTE change in v1.3.0 $once can add multiple listeners - * but once the event fired, it will remove this event (see $only) - * @param {string} evt name - * @param {function} callback to execute - * @param {object} [context=null] the handler execute in - * @return {boolean} result - */ - EventService.prototype.$once = function $once (evt , callback , context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'once'; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (lazyStoreContent === false) { - this.logger('($once)', (evt + " not in the lazy store")); - // v1.3.0 $once now allow to add multiple listeners - return this.addToNormalStore(evt, type, callback, context) - } else { - // now this is the tricky bit - // there is a potential bug here that cause by the developer - // if they call $trigger first, the lazy won't know it's a once call - // so if in the middle they register any call with the same evt name - // then this $once call will be fucked - add this to the documentation - this.logger('($once)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.logger('($once)', ("call run for " + evt)); - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - }; - - /** - * This one event can only bind one callbackback - * @param {string} evt event name - * @param {function} callback event handler - * @param {object} [context=null] the context the event handler execute in - * @return {boolean} true bind for first time, false already existed - */ - EventService.prototype.$only = function $only (evt, callback, context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'only'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($only)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($only)', (evt + " found data in lazy store to execute")); - var list = Array.from(lazyStoreContent); - // $only allow to trigger this multiple time on the single handler - list.forEach( function (l) { - var payload = l[0]; - var ctx = l[1]; - var t = l[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.logger("($only)", ("call run for " + evt)); - this$1.run(callback, payload, context || ctx); - }); - } - return added; - }; - - /** - * $only + $once this is because I found a very subtile bug when we pass a - * resolver, rejecter - and it never fire because that's OLD added in v1.4.0 - * @param {string} evt event name - * @param {function} callback to call later - * @param {object} [context=null] exeucte context - * @return {void} - */ - EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'onlyOnce'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($onlyOnce)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($onlyOnce)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== 'onlyOnce') { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.logger("($onlyOnce)", ("call run for " + evt)); - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - return added; - }; - - /** - * This is a shorthand of $off + $on added in V1.5.0 - * @param {string} evt event name - * @param {function} callback to exeucte - * @param {object} [context = null] or pass a string as type - * @param {string} [type=on] what type of method to replace - * @return {} - */ - EventService.prototype.$replace = function $replace (evt, callback, context, type) { - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = 'on'; - - if (this.validateType(type)) { - this.$off(evt); - var method = this['$' + type]; - this.logger("($replace)", evt, callback); - return Reflect.apply(method, this, [evt, callback, context]) - } - throw new Error((type + " is not supported!")) - }; - - /** - * trigger the event - * @param {string} evt name NOT allow array anymore! - * @param {mixed} [payload = []] pass to fn - * @param {object|string} [context = null] overwrite what stored - * @param {string} [type=false] if pass this then we need to add type to store too - * @return {number} if it has been execute how many times - */ - EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - this.validateEvt(evt); - var found = 0; - // first check the normal store - var nStore = this.normalStore; - this.logger('($trigger)', 'normalStore', nStore); - if (nStore.has(evt)) { - // @1.8.0 to add the suspend queue - var added = this.$queue(evt, payload, context, type); - this.logger('($trigger)', evt, 'found; add to queue: ', added); - if (added === true) { - this.logger('($trigger)', evt, 'not executed. Exit now.'); - return false; // not executed - } - var nSet = Array.from(nStore.get(evt)); - var ctn = nSet.length; - var hasOnce = false; - for (var i=0; i < ctn; ++i) { - ++found; - // this.logger('found', found) - var ref = nSet[i]; - var _ = ref[0]; - var callback = ref[1]; - var ctx = ref[2]; - var type$1 = ref[3]; - this.logger("($trigger)", ("call run for " + evt)); - this.run(callback, payload, context || ctx); - if (type$1 === 'once' || type$1 === 'onlyOnce') { - hasOnce = true; - } - } - if (hasOnce) { - nStore.delete(evt); - } - return found; - } - // now this is not register yet - this.addToLazyStore(evt, payload, context, type); - return found; - }; - - /** - * this is an alias to the $trigger - * @NOTE breaking change in V1.6.0 we swap the parameter around - * @param {string} evt event name - * @param {*} params pass to the callback - * @param {string} type of call - * @param {object} context what context callback execute in - * @return {*} from $trigger - */ - EventService.prototype.$call = function $call (evt, params, type, context) { - if ( type === void 0 ) type = false; - if ( context === void 0 ) context = null; - - var args = [evt, params, context, type]; - return Reflect.apply(this.$trigger, this, args) - }; - - /** - * remove the evt from all the stores - * @param {string} evt name - * @return {boolean} true actually delete something - */ - EventService.prototype.$off = function $off (evt) { - var this$1 = this; - - this.validateEvt(evt); - var stores = [ this.lazyStore, this.normalStore ]; - var found = false; - stores.forEach(function (store) { - if (store.has(evt)) { - found = true; - this$1.logger('($off)', evt); - store.delete(evt); - } - }); - return found; - }; - - /** - * return all the listener from the event - * @param {string} evtName event name - * @param {boolean} [full=false] if true then return the entire content - * @return {array|boolean} listerner(s) or false when not found - */ - EventService.prototype.$get = function $get (evt, full) { - if ( full === void 0 ) full = false; - - this.validateEvt(evt); - var store = this.normalStore; - if (store.has(evt)) { - return Array - .from(store.get(evt)) - .map( function (l) { - if (full) { - return l; - } - var key = l[0]; - var callback = l[1]; - return callback; - }) - } - return false; - }; - - /** - * store the return result from the run - * @param {*} value whatever return from callback - */ - prototypeAccessors.$done.set = function (value) { - this.logger('($done)', 'value: ', value); - if (this.keep) { - this.result.push(value); - } else { - this.result = value; - } - }; - - /** - * @TODO is there any real use with the keep prop? - * getter for $done - * @return {*} whatever last store result - */ - prototypeAccessors.$done.get = function () { - if (this.keep) { - this.logger('(get $done)', this.result); - return this.result[this.result.length - 1] - } - return this.result; - }; - - Object.defineProperties( EventService.prototype, prototypeAccessors ); - - return EventService; - }(NbEventServiceBase)); - - // default - - // this will generate a event emitter and will be use everywhere - // output - function getEventEmitter(debugOn) { - var logger = debugOn ? function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - args.unshift('[NBS]'); - console.log.apply(null, args); - }: undefined; - return new EventService({ logger: logger }) - } - - // this is the new Event base interface - /** - * this is the slim client without Fly, you pick the version of Fly to use - * This is a breaking change because it swap the input positions - * @param {object} fly fly.js - * @param {object} config configuration - * @return {object} the jsonql client instance - */ - function jsonqlStaticClient(fly, config) { - if ( config === void 0 ) config = {}; - - var contract = config.contract; - var opts = checkOptions$1(config); - var jsonqlBase = new JsonqlBaseClient(fly, opts); - var contractPromise = getContractFromConfig(jsonqlBase, contract); - var ee = getEventEmitter(opts.debugOn); - // finally - var methods = generator(jsonqlBase, opts, contractPromise, ee); - methods.eventEmitter = ee; - return methods; - } - - // This is the static version that build with the Fly for Browser - - // this is the slim client without Fly - function jsonqlStaticClientFull(config) { - if ( config === void 0 ) config = {}; - - return jsonqlStaticClient(new Fly(), config) - } - - return jsonqlStaticClientFull; - -}))); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClientStatic=e()}(this,(function(){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r,n=e((function(t,e){var r;r=function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=2)}([function(t,e,r){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};t.exports={type:function(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()},isObject:function(t,e){return e?"object"===this.type(t):t&&"object"===(void 0===t?"undefined":n(t))},isFormData:function(t){return"undefined"!=typeof FormData&&t instanceof FormData},trim:function(t){return t.replace(/(^\s*)|(\s*$)/g,"")},encode:function(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")},formatParams:function(t){var e="",r=!0,n=this;return this.isObject(t)?(function t(o,i){var a=n.encode,u=n.type(o);if("array"==u)o.forEach((function(e,r){n.isObject(e)||(r=""),t(e,i+"%5B"+r+"%5D")}));else if("object"==u)for(var c in o)t(o[c],i?i+"%5B"+a(c)+"%5D":a(c));else r||(e+="&"),r=!1,e+=i+"="+a(o)}(t,""),e):t},merge:function(t,e){for(var r in e)t.hasOwnProperty(r)?this.isObject(e[r],1)&&this.isObject(t[r],1)&&this.merge(t[r],e[r]):t[r]=e[r];return t}}},,function(t,e,r){var n=function(){function t(t,e){for(var r=0;r0&&(t+=(-1===t.indexOf("?")?"?":"&")+w.join("&")),a.open(r.method,t);try{a.withCredentials=!!r.withCredentials,a.timeout=r.timeout||0,"stream"!==y&&(a.responseType=y)}catch(t){}var j=r.headers[u]||r.headers[c],O="application/x-www-form-urlencoded";for(var S in o.trim((j||"").toLowerCase())===O?e=o.formatParams(e):o.isFormData(e)||-1===["object","array"].indexOf(o.type(e))||(O="application/json;charset=utf-8",e=JSON.stringify(e)),j||b||(r.headers[u]=O),r.headers)if(S===u&&o.isFormData(e))delete r.headers[S];else try{a.setRequestHeader(S,r.headers[S])}catch(t){}function k(t,e,n){v(l.p,(function(){if(t){n&&(e.request=r);var o=t.call(l,e,Promise);e=void 0===o?e:o}d(e)||(e=Promise[0===n?"resolve":"reject"](e)),e.then((function(t){s(t)})).catch((function(t){h(t)}))}))}function E(t){t.engine=a,k(l.onerror,t,-1)}function A(t,e){this.message=t,this.status=e}a.onload=function(){try{var t=a.response||a.responseText;t&&r.parseJson&&-1!==(a.getResponseHeader(u)||"").indexOf("json")&&!o.isObject(t)&&(t=JSON.parse(t));var e=a.responseHeaders;if(!e){e={};var n=(a.getAllResponseHeaders()||"").split("\r\n");n.pop(),n.forEach((function(t){if(t){var r=t.split(":")[0];e[r]=a.getResponseHeader(r)}}))}var i=a.status,c=a.statusText,s={data:t,headers:e,status:i,statusText:c};if(o.merge(s,a._response),i>=200&&i<300||304===i)s.engine=a,s.request=r,k(l.handler,s,0);else{var f=new A(c,i);f.response=s,E(f)}}catch(f){E(new A(f.msg,a.status))}},a.onerror=function(t){E(new A(t.msg||"Network Error",0))},a.ontimeout=function(){E(new A("timeout [ "+a.timeout+"ms ]",1))},a._options=r,setTimeout((function(){a.send(b?null:e)}),0)}(n):s(n)}),(function(t){h(t)}))}))}));return h.engine=a,h}},{key:"all",value:function(t){return Promise.all(t)}},{key:"spread",value:function(t){return function(e){return t.apply(null,e)}}}]),t}();a.default=a,["get","post","put","patch","head","delete"].forEach((function(t){a.prototype[t]=function(e,r,n){return this.request(e,r,o.merge({method:t},n))}})),["lock","unlock","clear"].forEach((function(t){a.prototype[t]=function(){this.interceptors.request[t]()}})),t.exports=a}])},t.exports=r()})),o=(r=n)&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r,i="application/vnd.api+json",a={Accept:i,"Content-Type":[i,"charset=utf-8"].join(";")},u="query",c="mutation",s="socket",f="payload",l="condition",p="TS",h=["POST","PUT"],d="type",v="optional",g="enumv",y="args",b="checker",m="alias",_="__checked__",w={desc:"y"},j="No message",O="onResult",S="onError",k=Array.isArray,E="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},A="object"==typeof E&&E&&E.Object===Object&&E,T="object"==typeof self&&self&&self.Object===Object&&self,x=A||T||Function("return this")(),P=x.Symbol,q=Object.prototype,C=q.hasOwnProperty,$=q.toString,z=P?P.toStringTag:void 0;var N=Object.prototype.toString;var R="[object Null]",M="[object Undefined]",F=P?P.toStringTag:void 0;function J(t){return null==t?void 0===t?M:R:F&&F in Object(t)?function(t){var e=C.call(t,z),r=t[z];try{t[z]=void 0;var n=!0}catch(t){}var o=$.call(t);return n&&(e?t[z]=r:delete t[z]),o}(t):function(t){return N.call(t)}(t)}function I(t,e){return function(r){return t(e(r))}}var U=I(Object.getPrototypeOf,Object);function D(t){return null!=t&&"object"==typeof t}var H="[object Object]",L=Function.prototype,B=Object.prototype,K=L.toString,G=B.hasOwnProperty,V=K.call(Object);function W(t){if(!D(t)||J(t)!=H)return!1;var e=U(t);if(null===e)return!0;var r=G.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&K.call(r)==V}function Y(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&it(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var wt=function(t){return k(t)?t:[t]},jt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},Ot=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),xt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),Pt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),qt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),Ct=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),$t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),zt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Nt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),Rt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),Mt=Object.freeze({__proto__:null,Jsonql406Error:St,Jsonql500Error:kt,JsonqlForbiddenError:Et,JsonqlAuthorisationError:At,JsonqlContractAuthError:Tt,JsonqlResolverAppError:xt,JsonqlResolverNotFoundError:Pt,JsonqlEnumError:qt,JsonqlTypeError:Ct,JsonqlCheckerError:$t,JsonqlValidationError:zt,JsonqlError:Nt,JsonqlServerError:Rt}),Ft=Nt,Jt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function It(t){if(Jt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||j,a=e.detail||e;if(o&&Mt[o])throw new Mt[r](i,a);throw new Ft(i,a)}return t}function Ut(t){if(Array.isArray(t))throw new zt("",t);var e=t.message||j,r=t.detail||t;switch(!0){case t instanceof St:throw new St(e,r);case t instanceof kt:throw new kt(e,r);case t instanceof Et:throw new Et(e,r);case t instanceof At:throw new At(e,r);case t instanceof Tt:throw new Tt(e,r);case t instanceof xt:throw new xt(e,r);case t instanceof Pt:throw new Pt(e,r);case t instanceof qt:throw new qt(e,r);case t instanceof Ct:throw new Ct(e,r);case t instanceof $t:throw new $t(e,r);case t instanceof zt:throw new zt(e,r);case t instanceof Rt:throw new Rt(e,r);default:throw new Nt(e,r)}}var Dt=function(t){return!!k(t)||null!=t&&""!==_t(t)},Ht="[object Number]";function Lt(t){return function(t){return"number"==typeof t||D(t)&&J(t)==Ht}(t)&&t!=+t}var Bt="[object String]";function Kt(t){return"string"==typeof t||!k(t)&&D(t)&&J(t)==Bt}var Gt=function(t){return!Kt(t)&&!Lt(parseFloat(t))},Vt=function(t){return""!==_t(t)&&Kt(t)},Wt=function(t){return null!=t&&"boolean"==typeof t},Yt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==_t(t)&&(!1===e||!0===e&&null!==t)},Qt=d,Xt=v,Zt=g,te=y,ee=b,re=m,ne="continue",oe=function(t){switch(t){case"number":return Gt;case"string":return Vt;case"boolean":return Wt;default:return Yt}},ie=function(t,e){return void 0===e&&(e=""),!!k(t)&&(""===e||""===_t(e)||!(t.filter((function(t){return!oe(e)(t)})).length>0))},ae=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ue=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!oe(e)(t)})).length)})).length:e.length>e.filter((function(t){return!ie(r,t)})).length};var ce,se=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[ce?a:++n];if(!1===e(o[u],u,o))break}return t};var fe="[object Arguments]";function le(t){return D(t)&&J(t)==fe}var pe=Object.prototype,he=pe.hasOwnProperty,de=pe.propertyIsEnumerable,ve=le(function(){return arguments}())?le:function(t){return D(t)&&he.call(t,"callee")&&!de.call(t,"callee")};var ge="object"==typeof exports&&exports&&!exports.nodeType&&exports,ye=ge&&"object"==typeof module&&module&&!module.nodeType&&module,be=ye&&ye.exports===ge?x.Buffer:void 0,me=(be?be.isBuffer:void 0)||function(){return!1},_e=9007199254740991,we=/^(?:0|[1-9]\d*)$/;function je(t,e){var r=typeof t;return!!(e=null==e?_e:e)&&("number"==r||"symbol"!=r&&we.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=Oe}var ke={};ke["[object Float32Array]"]=ke["[object Float64Array]"]=ke["[object Int8Array]"]=ke["[object Int16Array]"]=ke["[object Int32Array]"]=ke["[object Uint8Array]"]=ke["[object Uint8ClampedArray]"]=ke["[object Uint16Array]"]=ke["[object Uint32Array]"]=!0,ke["[object Arguments]"]=ke["[object Array]"]=ke["[object ArrayBuffer]"]=ke["[object Boolean]"]=ke["[object DataView]"]=ke["[object Date]"]=ke["[object Error]"]=ke["[object Function]"]=ke["[object Map]"]=ke["[object Number]"]=ke["[object Object]"]=ke["[object RegExp]"]=ke["[object Set]"]=ke["[object String]"]=ke["[object WeakMap]"]=!1;var Ee,Ae="object"==typeof exports&&exports&&!exports.nodeType&&exports,Te=Ae&&"object"==typeof module&&module&&!module.nodeType&&module,xe=Te&&Te.exports===Ae&&A.process,Pe=function(){try{var t=Te&&Te.require&&Te.require("util").types;return t||xe&&xe.binding&&xe.binding("util")}catch(t){}}(),qe=Pe&&Pe.isTypedArray,Ce=qe?(Ee=qe,function(t){return Ee(t)}):function(t){return D(t)&&Se(t.length)&&!!ke[J(t)]},$e=Object.prototype.hasOwnProperty;function ze(t,e){var r=k(t),n=!r&&ve(t),o=!r&&!n&&me(t),i=!r&&!n&&!o&&Ce(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},Qe.prototype.set=function(t,e){var r=this.__data__,n=We(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var Xe,Ze=x["__core-js_shared__"],tr=(Xe=/[^.]+$/.exec(Ze&&Ze.keys&&Ze.keys.IE_PROTO||""))?"Symbol(src)_1."+Xe:"";var er=Function.prototype.toString;function rr(t){if(null!=t){try{return er.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var nr=/^\[object .+?Constructor\]$/,or=Function.prototype,ir=Object.prototype,ar=or.toString,ur=ir.hasOwnProperty,cr=RegExp("^"+ar.call(ur).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function sr(t){return!(!Je(t)||function(t){return!!tr&&tr in t}(t))&&(Le(t)?cr:nr).test(rr(t))}function fr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return sr(r)?r:void 0}var lr=fr(x,"Map"),pr=fr(Object,"create");var hr="__lodash_hash_undefined__",dr=Object.prototype.hasOwnProperty;var vr=Object.prototype.hasOwnProperty;var gr="__lodash_hash_undefined__";function yr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&Er?new Or:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=ae(t))?!ue({arg:r},e):!oe(t)(r))})).length)})).length}return!1},Gn=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Kn,null,a);case"array"===t:return!ie(e.arg);case!1!==(r=ae(t)):return!ue(e,r);default:return!oe(t)(e.arg)}},Vn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Wn=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!ie(e))throw new Nt("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!ie(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==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Vn(t,a):t,index:r,param:a,optional:i}}));default:throw new Nt("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Dt(e)&&!(r.type.length>r.type.filter((function(e){return Gn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Gn(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Yn=function(){try{var t=fr(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function Qn(t,e,r){"__proto__"==e&&Yn?Yn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function Xn(t,e,r){(void 0===r||Ve(t[e],r))&&(void 0!==r||e in t)||Qn(t,e,r)}var Zn="object"==typeof exports&&exports&&!exports.nodeType&&exports,to=Zn&&"object"==typeof module&&module&&!module.nodeType&&module,eo=to&&to.exports===Zn?x.Buffer:void 0,ro=eo?eo.allocUnsafe:void 0;function no(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new Tr(n).set(new Tr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var oo=Object.create,io=function(){function t(){}return function(e){if(!Je(e))return{};if(oo)return oo(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function ao(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var uo=Object.prototype.hasOwnProperty;function co(t,e,r){var n=t[e];uo.call(t,e)&&Ve(n,r)&&(void 0!==r||e in t)||Qn(t,e,r)}var so=Object.prototype.hasOwnProperty;function fo(t){if(!Je(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Re(t),r=[];for(var n in t)("constructor"!=n||!e&&so.call(t,n))&&r.push(n);return r}function lo(t){return Be(t)?ze(t,!0):fo(t)}function po(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=mo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(bo);function Oo(t,e){return jo(function(t,e,r){return e=yo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=yo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=So.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!Je(r))return!1;var n=typeof e;return!!("number"==n?Be(r)&&je(e,r.length):"string"==n&&e in r)&&Ve(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,wt(t))}),Reflect.apply(t,null,r))}};function Wo(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function Yo(t,e,r,n){void 0===n&&(n=!1);var o=Wo(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var Qo=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return Bo(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch(Ut)}},Xo=function(t,e,r,n,o){var i={},a=function(t){i=Yo(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return Bo(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch(Ut)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},Zo=function(t,e,r,n,o){var i={},a=function(t){i=Yo(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return Bo(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch(Ut)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},ti=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Qo(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Qo(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var ei=function(t,e){return function(r){for(var n=[],o=arguments.length-1;o-- >0;)n[o]=arguments[o+1];return new Promise((function(o,i){t.$only(Ot(e,r,O),o),t.$only(Ot(e,r,S),i),t.$trigger(e,{resolverName:r,args:n})}))}},ri=function(t,e,r){var n=t.$queues,o=r.debugOn;o&&console.info("(validateRegisteredEvents)","storedEvt",n),n.forEach((function(t){var r=t[0],n=t[1].resolverName;if(o&&console.info("(validateRegisteredEvents)",r,n),!e[r][n])throw new Error(r+"."+n+" not existed in contract!")}))};function ni(t,e,r,n){var o=function(t,e,r,n){return Vo(Xo,Zo,ti)({},t,e,r,n)}(t,e,r,n);ri(e,n,r);var i=function(t){e.$only(t,(function(r){var n=r.resolverName,i=r.args;o[t][n]?Reflect.apply(o[t][n],null,i).then((function(r){e.$trigger(Ot(t,n,O),r)})).catch((function(r){e.$trigger(Ot(t,n,S),r)})):console.error(n+" is not defined in the contract!")}))};for(var a in o)i(a);setTimeout((function(){e.$suspend=!1}),1)}var oi=function(t,e,r,n){n.$suspend=!0,r.then((function(r){ni(t,n,e,r)}));var o={query:ei(n,"query"),mutation:ei(n,"mutation"),auth:ei(n,"auth"),getToken:function(){return t.rawAuthToken}};return e.exposeContract&&(o.getContract=function(){return t.get()}),e.enableAuth&&(o.userdata=function(){return t.userdata}),o.version="1.5.2",o};function ii(t){return!!function(t){return W(t)&&(jt(t,u)||jt(t,c)||jt(t,s))}(t)&&t}function ai(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var ui=function(t,e){return void 0===e&&(e={}),ii(e)?Promise.resolve(e):t.getContract()},ci="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function si(t){this.message=t}si.prototype=new Error,si.prototype.name="InvalidCharacterError";var fi="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new si("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=ci.indexOf(n);return a};var li=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(fi(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return fi(e)}};function pi(t){this.message=t}pi.prototype=new Error,pi.prototype.name="InvalidTokenError";var hi=function(t,e){if("string"!=typeof t)throw new pi("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(li(t.split(".")[r]))}catch(t){throw new pi("Invalid token specified: "+t.message)}},di=pi;hi.InvalidTokenError=di;var vi,gi,yi,bi,mi,_i,wi,ji,Oi,Si=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function ki(t){if(Vt(t))return function(t){var e=t.iat||Si(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Nt("Token has expired on "+r,t)}return t}(hi(t));throw new Nt("Token must be a string!")}Ko("HS256",["string"]),Ko(!1,["boolean","number","string"],((vi={})[m]="exp",vi[v]=!0,vi)),Ko(!1,["boolean","number","string"],((gi={})[m]="nbf",gi[v]=!0,gi)),Ko(!1,["boolean","string"],((yi={})[m]="iss",yi[v]=!0,yi)),Ko(!1,["boolean","string"],((bi={})[m]="sub",bi[v]=!0,bi)),Ko(!1,["boolean","string"],((mi={})[m]="iss",mi[v]=!0,mi)),Ko(!1,["boolean"],((_i={})[v]=!0,_i)),Ko(!1,["boolean","string"],((wi={})[v]=!0,wi)),Ko(!1,["boolean","string"],((ji={})[v]=!0,ji)),Ko(!1,["boolean"],((Oi={})[v]=!0,Oi));var Ei=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},Ai=Object.assign?Object.assign:function(t,e,r,n){for(var o=arguments,i=1;i=0;e--){var r=Wi().key(e);t(Yi(r),r)}},remove:function(t){return Wi().removeItem(t)},clearAll:function(){return Wi().clear()}};function Wi(){return Gi.localStorage}function Yi(t){return Wi().getItem(t)}var Qi=qi.trim,Xi={name:"cookieStorage",read:function(t){if(!t||!ra(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Zi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Zi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:ta,remove:ea,clearAll:function(){ta((function(t,e){ea(e)}))}},Zi=qi.Global.document;function ta(t){for(var e=Zi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Qi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function ea(t){t&&ra(t)&&(Zi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function ra(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Zi.cookie)}var na=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var oa=qi.bind,ia=qi.each,aa=qi.create,ua=qi.slice,ca=function(){var t=aa(sa,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,oa(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,oa(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),ia(r,(function(e,r){t.fire(r,void 0,e)}))}}};var sa={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,oa(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=ua(arguments,1);ia(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},fa=e((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),la=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=fa.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=fa.compress(this._serialize(r));t(e,n)}}};var pa=[Vi,Xi],ha=[na,ca,la],da=Li.createStore(pa,ha),va=qi.Global;function ga(){return va.sessionStorage}function ya(t){return ga().getItem(t)}var ba=[{name:"sessionStorage",read:ya,write:function(t,e){return ga().setItem(t,e)},each:function(t){for(var e=ga().length-1;e>=0;e--){var r=ga().key(e);t(ya(r),r)}},remove:function(t){return ga().removeItem(t)},clearAll:function(){return ga().clear()}},Xi],ma=[na,la],_a=Li.createStore(ba,ma),wa=da,ja=_a,Oa=function(t){var e;return(e={}).args=t,e};function Sa(t,e){var r;return(r={})[t]=e,r[p]=[Ei()],r}var ka=function(t){return jt(t,"data")&&!jt(t,"error")?t.data:t},Ea=function(t){this.opts=t,this.instanceKey=ai(this.opts.hostname)+"",this.localStore=wa,this.sessionStore=ja},Aa={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};Ea.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?ko({},o,e):e,r))},Ea.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},Ea.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},Ea.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},Aa.lset.set=function(t){return this.__setMethod("localStore",t)},Aa.lget.get=function(){return this.__getMethod("localStore")},Ea.prototype.ldel=function(t){return this.__delMethod("localStore",t)},Ea.prototype.lclear=function(){return this.__clearMethod("localStore")},Aa.sset.set=function(t){return this.__setMethod("sessionStore",t)},Aa.sget.get=function(){return this.__getMethod("sessionStore")},Ea.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},Ea.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(Ea.prototype,Aa);var Ta=h[0],xa=h[1],Pa=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=ki)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(Lo(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new zt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&Lo(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!ii(t))throw new zt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=ii(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={headers:{configurable:!0}};return r.headers.set=function(t){this.extraHeader=t},e.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=ko({},{_cb:Ei()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=ko({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=ko({},{method:Ta,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},e.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},e.prototype.processJsonp=function(t){return ka(t)},e.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=Ho(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ka(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new Rt("Server side error",r)}))},e.prototype.getHeaders=function(){return this.opts.enableAuth?ko({},a,this.getAuthHeader(),this.extraHeader):ko({},a,this.extraHeader)},e.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},e.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=ko({},this.extraParams,w)),this.request({},{method:"GET"},this.contractHeader).then(It).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new Rt("getRemoteContract",e)}))},e.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Kt(t)&&k(e)){var n=Oa(e);return!0===r?n:Sa(t,n)}throw new zt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(It)},e.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[f]=e,o[l]=r,!0===n)return o;if(Kt(t))return Sa(t,o);throw new zt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:xa}).then(It)},Object.defineProperties(e.prototype,r),e}(Ea)))),qa={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:i,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Ca={hostname:Ko(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:Ko("jsonql",["string"]),loginHandlerName:Ko("login",["string"]),logoutHandlerName:Ko("logout",["string"]),enableJsonp:Ko(!1,["boolean"]),enableAuth:Ko(!1,["boolean"]),useJwt:Ko(!0,["boolean"]),persistToken:Ko(!1,["boolean","number"]),useLocalstorage:Ko(!0,["boolean"]),storageKey:Ko("jsonqlstore",["string"]),authKey:Ko("jsonqlauthkey",["string"]),contractExpired:Ko(0,["number"]),keepContract:Ko(!0,["boolean"]),exposeContract:Ko(!1,["boolean"]),exposeStore:Ko(!1,["boolean"]),showContractDesc:Ko(!1,["boolean"]),contractKey:Ko(!1,["boolean"]),contractKeyName:Ko("X-JSONQL-CV-KEY",["string"]),enableTimeout:Ko(!1,["boolean"]),timeout:Ko(5e3,["number"]),returnInstance:Ko(!1,["boolean"]),allowReturnRawToken:Ko(!1,["boolean"]),debugOn:Ko(!1,["boolean"])};function $a(t){return Wo(t,_)?t:function(t){return Go(t,Ca,qa)}(t)}var za=new WeakMap,Na=new WeakMap,Ra=function(){this.__suspend__=null,this.queueStore=new Set},Ma={$suspend:{configurable:!0},$queues:{configurable:!0}};Ma.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Ra.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ma.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Ra.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Ra.prototype,Ma);var Fa=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){za.set(this,t)},r.normalStore.get=function(){return za.get(this)},r.lazyStore.set=function(t){Na.set(this,t)},r.lazyStore.get=function(){return Na.get(this)},e.prototype.hashFnToKey=function(t){return ai(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Ra));function Ja(t,e){void 0===e&&(e={});var r,n=e.contract,o=$a(e),i=new Pa(t,o),a=ui(i,n),u=(r=o.debugOn,new Fa({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),c=oi(i,o,a,u);return c.eventEmitter=u,c}return function(t){return void 0===t&&(t={}),Ja(new o,t)}})); //# sourceMappingURL=jsonql-client.static.js.map diff --git a/packages/http-client/dist/jsonql-client.static.js.map b/packages/http-client/dist/jsonql-client.static.js.map index fa64e484..eb8ed311 100644 --- a/packages/http-client/dist/jsonql-client.static.js.map +++ b/packages/http-client/dist/jsonql-client.static.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client.static.js","sources":["../node_modules/lodash-es/isArray.js","../node_modules/rollup-plugin-node-globals/src/global.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/lodash-es/_arrayMap.js","../node_modules/lodash-es/_baseSlice.js","../node_modules/lodash-es/_baseFindIndex.js","../node_modules/lodash-es/_baseIsNaN.js","../node_modules/lodash-es/_strictIndexOf.js","../node_modules/lodash-es/_asciiToArray.js","../node_modules/lodash-es/_hasUnicode.js","../node_modules/lodash-es/_unicodeToArray.js","../node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-errors/src/resolver-not-found-error.js","../node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-errors/src/index.js","../node_modules/jsonql-errors/src/client-errors-handler.js","../node_modules/jsonql-params-validator/src/number.js","../node_modules/jsonql-params-validator/src/string.js","../node_modules/jsonql-params-validator/src/boolean.js","../node_modules/jsonql-params-validator/src/any.js","../node_modules/jsonql-params-validator/src/constants.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/_listCacheClear.js","../node_modules/lodash-es/eq.js","../node_modules/lodash-es/_stackDelete.js","../node_modules/lodash-es/_stackGet.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-params-validator/src/validator.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/negate.js","../node_modules/lodash-es/_baseFindKey.js","../node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-params-validator/src/options/check-options-sync.js","../node_modules/jsonql-params-validator/src/options/construct-config.js","../node_modules/jsonql-params-validator/src/options/index.js","../node_modules/jsonql-params-validator/index.js","../src/core/methods-generator.js","../src/core/jsonql-static-generator.js","../node_modules/jsonql-utils/src/contract.js","../node_modules/nb-event-service/src/hash-code.js","../src/utils.js","../node_modules/jwt-decode/lib/atob.js","../node_modules/jsonql-jwt/src/client/decode-token/decode-token.js","../node_modules/jsonql-utils/src/timestamp.js","../node_modules/store/plugins/defaults.js","../src/stores/local-store.js","../src/stores/session-store.js","../src/stores/index.js","../node_modules/jsonql-utils/src/params-api.js","../node_modules/jsonql-utils/src/results.js","../src/base/store-cls.js","../src/base/http-cls.js","../src/base/contract-cls.js","../src/base/auth-cls.js","../src/base/base-cls.js","../src/base/index.js","../src/options/base-options.js","../src/options/check-options.js","../src/options/index.js","../node_modules/nb-event-service/src/suspend.js","../node_modules/nb-event-service/src/store-service.js","../node_modules/nb-event-service/src/event-service.js","../node_modules/nb-event-service/index.js","../src/ee.js","../src/static.js","../src/static-full.js"],"sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length;\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg];\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @return {*} json object on success\n */\nconst parse = function(n) {\n try {\n return JSON.parse(n)\n } catch(e) {\n return n;\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false;\n /*\n console.info('obj', obj)\n console.error(e)\n throw new Error(e)\n */\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = (n) => {\n if (typeof n === 'string') {\n return parse(n)\n }\n return JSON.parse(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== '';\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n","/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error)\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","/**\n * This is a custom error to throw when could not find the resolver\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class JsonqlResolverNotFoundError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlResolverNotFoundError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlResolverNotFoundError);\n }\n }\n\n static get statusCode() {\n return 404;\n }\n\n static get name() {\n return 'JsonqlResolverNotFoundError';\n }\n}\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError);\n }\n }\n\n static get name() {\n return 'JsonqlEnumError';\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlTypeError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError);\n }\n }\n\n static get name() {\n return 'JsonqlTypeError';\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args)\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError)\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError';\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError';\n }\n}\n","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message)\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// server side\nimport Jsonql406Error from './406-error'\nimport Jsonql500Error from './500-error'\n\nimport JsonqlForbiddenError from './forbidden-error'\nimport JsonqlAuthorisationError from './authorisation-error'\nimport JsonqlContractAuthError from './contract-auth-error'\nimport JsonqlResolverAppError from './resolver-app-error'\nimport JsonqlResolverNotFoundError from './resolver-not-found-error'\n\n// check options error\nimport JsonqlEnumError from './enum-error'\nimport JsonqlTypeError from './type-error'\nimport JsonqlCheckerError from './checker-error'\n// share\nimport JsonqlValidationError from './validation-error'\nimport JsonqlError from './error'\n\nimport JsonqlServerError from './server-error'\n\nexport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlForbiddenError,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n};\n","// this will add directly to the then call in each http call\n\nimport * as errors from './index'\nimport getErrorByStatus from './get-error-by-status'\nimport { NO_ERROR_MSG } from 'jsonql-constants'\nconst { JsonqlError } = errors\n\n/**\n * We can not just check something like result.data what if the result if false?\n * @param {object} obj the result object\n * @param {string} key we want to check if its exist or not\n * @return {boolean} true on found\n */\nconst isObjectHasKey = (obj, key) => {\n const keys = Object.keys(obj)\n return !!keys.filter(k => key === k).length;\n}\n\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nexport default function clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false;\n}\n\nexport default checkIsString\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nexport const ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\n","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber;\n case STRING_TYPE:\n return checkIsString;\n case BOOLEAN_TYPE:\n return checkIsBoolean;\n default:\n return checkIsAny;\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false;\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false;\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p;\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length;\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length;\n}\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport filter from 'lodash-es/filter'\n\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true;\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (_value !== undefined) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true;\n }).length)\n }).length;\n }\n }\n return false;\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p;\n let _args = [arg];\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return Reflect.apply(checkIsObject, null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\n\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n checkIsObject,\n combineFn,\n notEmpty\n} from './index'\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params;\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false;\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (arg !== undefined) {\n return arg;\n }\n return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ))\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ))\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ))\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length:\n let ctn = params.length;\n // this happens when we have those array. type\n let _type = [ DEFAULT_TYPE ]\n // we only looking at the first one, this might be a @BUG\n /*\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n } */\n // if we use the params as guide then the rest will get throw out\n // which is not what we want, instead, anything without the param\n // will get a any type and optional flag\n return args.map((arg, i) => {\n let optional = i >= ctn ? true : !!params[i].optional\n let param = params[i] || { type: _type, name: `_${i}` }\n return {\n arg: optional ? getOptionalValue(arg, param) : arg,\n index: i,\n param,\n optional\n }\n })\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n // v1.4.4 this fixed the problem, the root level optional is from the last fn\n if (p.optional === true || p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length;\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport isFunction from 'lodash-es/isFunction'\nimport merge from 'lodash-es/merge'\nimport mapValues from 'lodash-es/mapValues'\n\nimport JsonqlEnumError from 'jsonql-errors/src/enum-error'\nimport JsonqlTypeError from 'jsonql-errors/src/type-error'\nimport JsonqlCheckerError from 'jsonql-errors/src/checker-error'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true;\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // log('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n // log(ENUM_KEY, value[ENUM_KEY])\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n // log(CHECKER_KEY, value[CHECKER_KEY])\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args;\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","// this is port back from the client to share across all projects\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return merge(\n runValidation(\n prepareArgsForValidation(config, appProps),\n cb\n ),\n constProps\n )\n}\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\nimport checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n };\n if (optional === true) {\n base[OPTIONAL_KEY] = true;\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv;\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker;\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias;\n }\n return base;\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__';\n\n/**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n checkConfigAsync,\n checkConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nexport const inArray = isInArray;\nexport const isObjectHasKey = isObjectHasKeyFn;\n","// breaking out the inner methods generator in here\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { LOGOUT_NAME, LOGIN_NAME, KEY_WORD } from 'jsonql-constants'\nimport { chainFns } from 'jsonql-utils/src/chain-fns'\nimport { injectToFn } from 'jsonql-utils/src/obj-define-props'\n\n/**\n * generate authorisation specific methods\n * @param {object} jsonqlInstance instance of this\n * @param {string} name of method\n * @param {object} opts configuration\n * @param {object} contract to match\n * @return {function} for use\n */\nconst authMethodGenerator = (jsonqlInstance, name, opts, contract) => {\n return (...args) => {\n const params = contract.auth[name].params;\n const values = params.map((p, i) => args[i])\n const header = args[params.length] || {};\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [name, values, header])\n )\n .catch(finalCatch)\n }\n}\n\n/**\n * Break up the different type each - create query methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let query = {}\n for (let queryFn in contract.query) {\n // to keep it clean we use a param to id the auth method\n // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn;\n // generate the query method\n query = injectToFn(query, queryFn, function queryFnHandler(...args) {\n const params = contract.query[queryFn].params;\n const _args = params.map((param, i) => args[i])\n // debug('query', queryFn, _params);\n // @TODO this need to change to a different way to add an extra header\n const header = {}\n // @TODO validate against the type\n return validateAsync(_args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [queryFn, _args, header])\n )\n .catch(finalCatch)\n })\n }\n obj.query = query;\n // create an alias to the helloWorld method\n obj.helloWorld = query.helloWorld;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create mutation methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let mutation = {}\n // process the mutation, the reason the mutation has a fixed number of parameters\n // there is only the payload, and conditions parameters\n // plus a header at the end\n for (let mutationFn in contract.mutation) {\n mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header = {}) {\n const args = [payload, conditions];\n const params = contract.mutation[mutationFn].params;\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .mutation\n .apply(jsonqlInstance, [mutationFn, payload, conditions, header])\n )\n .catch(finalCatch)\n })\n }\n obj.mutation = mutation;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create auth methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createAuthMethods = (obj, jsonqlInstance, ee, config, contract) => {\n if (config.enableAuth && contract.auth) {\n let auth = {} // v1.3.1 add back the auth prop name in contract\n const { loginHandlerName, logoutHandlerName } = config;\n if (contract.auth[loginHandlerName]) {\n // changing to the name the config specify\n auth[loginHandlerName] = function loginHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance))\n .then(token => {\n ee.$trigger(LOGIN_NAME, token)\n return token;\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) {\n auth[logoutHandlerName] = function logoutHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance))\n .then(r => {\n ee.$trigger(LOGOUT_NAME, r)\n return r;\n })\n }\n } else {\n auth[logoutHandlerName] = function logoutHandlerFn() {\n jsonqlInstance.postLogoutAction(KEY_WORD)\n ee.$trigger(LOGOUT_NAME, KEY_WORD)\n }\n }\n obj.auth = auth;\n }\n\n return obj;\n}\n\n/**\n * Here just generate the methods calls\n * @param {object} jsonqlInstance what it said\n * @param {object} ee event emitter\n * @param {object} config configuration\n * @param {object} contract the map\n * @return {object} with mapped methods\n */\nexport function methodsGenerator(jsonqlInstance, ee, config, contract) {\n let obj = {}\n const executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods)\n return executor(obj, jsonqlInstance, ee, config, contract)\n}\n","// This generator will use the old style\n// with default methods\nimport { ON_RESULT_PROP_NAME, ON_ERROR_PROP_NAME } from 'jsonql-constants'\nimport { createEvt } from 'jsonql-utils/src/generic'\n\nimport { methodsGenerator } from './methods-generator'\n\n/**\n * Group all the same methods together\n * @param {object} ee event emitters\n * @param {string} type query, mutation or auth\n * @param {string} resolverName use as the guide\n * @param {array} args from the call\n * @return {function} the handler itself\n */\nconst handler = (ee, type) => {\n // we don't run validate here because we want until the contract is ready\n return (resolverName, ...args) => (\n new Promise((resolver, rejecter) => {\n // this are the callbacks\n ee.$only(createEvt(type, resolverName, ON_RESULT_PROP_NAME), resolver)\n ee.$only(createEvt(type, resolverName, ON_ERROR_PROP_NAME), rejecter)\n // this is the main call\n ee.$trigger(type, { resolverName, args })\n })\n )\n}\n\n/**\n * @param {object} ee eventEmitter\n * @param {object} contract the map\n * @param {object} config configuration\n */\nconst validateRegisteredEvents = (ee, contract, config) => {\n const storedEvt = ee.$queues;\n const debug = config.debugOn;\n if (debug) {\n console.info('(validateRegisteredEvents)', 'storedEvt', storedEvt)\n }\n storedEvt.forEach(args => {\n let [type, payload] = args;\n let { resolverName } = payload;\n if (debug) {\n console.info('(validateRegisteredEvents)', type, resolverName)\n }\n if (!contract[type][resolverName]) {\n throw new Error(`${type}.${resolverName} not existed in contract!`)\n }\n })\n}\n\n/**\n * set up all the event handlers once the contract is ready\n * @param {object} jsonqlInstance what the name said\n * @param {object} ee event emitter\n * @param {object} config the configuration\n * @param {object} contract the map\n * @return {void} nothing\n */\nfunction setupEventHandlers(jsonqlInstance, ee, config, contract) {\n let methods = methodsGenerator(jsonqlInstance, ee, config, contract)\n validateRegisteredEvents(ee, contract, config)\n // create handler\n for (let type in methods) {\n // setup event listeners - only one listener per type\n ee.$only(type, function({resolverName, args}) {\n if (methods[type][resolverName]) {\n Reflect.apply(methods[type][resolverName], null, args)\n .then(result => {\n ee.$trigger(createEvt(type, resolverName, ON_RESULT_PROP_NAME), result)\n })\n .catch(err => {\n ee.$trigger(createEvt(type, resolverName, ON_ERROR_PROP_NAME), err)\n })\n } else {\n console.error(`${resolverName} is not defined in the contract!`)\n }\n })\n }\n // all done now release the queue if any\n setTimeout(() => {\n ee.$suspend = false;\n }, 1)\n}\n\n/**\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} config options\n * @param {object} contractPromise an unresolve promise\n * @param {object} ee eventEmitter\n * @return {object} constructed functions call\n */\nconst generator = (jsonqlInstance, config, contractPromise, ee) => {\n ee.$suspend = true; // hold all the calls\n // wait for the promise to resolve\n contractPromise.then(contract => {\n setupEventHandlers(jsonqlInstance, ee, config, contract)\n })\n // construct the api\n let obj = {\n query: handler(ee, 'query'),\n mutation: handler(ee, 'mutation'),\n auth: handler(ee, 'auth')\n }\n // allow getting the token for valdiate agains the socket\n obj.getToken = () => jsonqlInstance.rawAuthToken;\n // this will pass to the ws-client if needed\n // obj.eventEmitter = ee;\n // this will require a param\n if (config.exposeContract) {\n obj.getContract = () => jsonqlInstance.get()\n }\n if (config.enableAuth) {\n obj.userdata = () => jsonqlInstance.userdata;\n }\n obj.version = '__VERSION__';\n // output\n return obj;\n}\n\nexport default generator;\n","// split the contract into the node side and the generic side\nimport { isObjectHasKey } from './generic'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n SOCKET_NAME,\n QUERY_ARG_NAME,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlResolverNotFoundError } from 'jsonql-errors'\n/**\n * Check if the json is a contract file or not\n * @param {object} contract json object\n * @return {boolean} true\n */\nexport function checkIsContract(contract) {\n return isPlainObject(contract)\n && (\n isObjectHasKey(contract, QUERY_NAME)\n || isObjectHasKey(contract, MUTATION_NAME)\n || isObjectHasKey(contract, SOCKET_NAME)\n )\n}\n\n/**\n * Wrapper method that check if it's contract then return the contract or false\n * @param {object} contract the object to check\n * @return {boolean | object} false when it's not\n */\nexport function isContract(contract) {\n return checkIsContract(contract) ? contract : false;\n}\n\n/**\n * Ported from jsonql-params-validator but different\n * if we don't find the socket part then return false\n * @param {object} contract the contract object\n * @return {object|boolean} false on failed\n */\nexport function extractSocketPart(contract) {\n if (isObjectHasKey(contract, 'socket')) {\n return contract.socket;\n }\n return false;\n}\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @param {boolean} [fallback=false] this is a fall back option for old code\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport function groupByNamespace(contract, fallback = false) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n if (fallback) {\n return contract; // just return the whole contract\n }\n throw new JsonqlError(`socket not found in contract!`)\n }\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\n}\n\n/**\n * @NOTE ported from jsonql-ws-client\n * Got to make sure the connection order otherwise\n * it will hang\n * @param {object} nspSet contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspSet, publicNamespace) {\n let names = []; // need to make sure the order!\n for (let namespace in nspSet) {\n if (namespace === publicNamespace) {\n names[1] = namespace;\n } else {\n names[0] = namespace;\n }\n }\n return names;\n}\n\n\n/**\n * Extract the args from the payload\n * @param {object} payload to work with\n * @param {string} type of call\n * @return {array} args\n */\nexport function extractArgsFromPayload(payload, type) {\n switch (type) {\n case QUERY_NAME:\n return payload[QUERY_ARG_NAME];\n case MUTATION_NAME:\n return [\n payload[PAYLOAD_PARAM_NAME],\n payload[CONDITION_PARAM_NAME]\n ];\n default:\n throw new JsonqlError(`Unknown ${type} to extract argument from!`)\n }\n}\n\n/**\n * Like what the name said\n * @param {object} contract the contract json\n * @param {string} type query|mutation\n * @param {string} name of the function\n * @return {object} the params part of the contract\n */\nexport function extractParamsFromContract(contract, type, name) {\n try {\n const result = contract[type][name];\n // debug('extractParamsFromContract', result)\n if (!result) {\n // debug(name, type, contract)\n throw new JsonqlResolverNotFoundError(name, type)\n }\n return result;\n } catch(e) {\n throw new JsonqlResolverNotFoundError(name, e)\n }\n}\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport default function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n","// take only the module part which is what we use here\n// and export it again to use through out the client\n// this way we avoid those that we don't want node.js module got build into the code\nimport { isContract } from 'jsonql-utils/src/contract'\nimport hashCodeFn from 'nb-event-service/src/hash-code'\n/**\n * @param {object} jsonqlInstance the init instance of jsonql client\n * @param {object} contract the static contract\n * @return {object} contract may be from server\n */\nconst getContractFromConfig = function(jsonqlInstance, contract = {}) {\n if (isContract(contract)) {\n return Promise.resolve(contract)\n }\n return jsonqlInstance.getContract()\n}\n// wrapper method to make sure it's a string\nconst hashCode = str => hashCodeFn(str) + ''\n\n// simple util to check if an object has any properties\n// const hasProp = obj => isObject(obj) && Object.keys(obj).length\n\n// export some constants as well\n// since it's only use here there is no point of adding it to the constants module\n// or may be we add it back later\nconst ENDPOINT_TABLE = 'endpoint' // not in use anymore delete later @TODO\nconst USERDATA_TABLE = 'userdata'\nconst CLS_LOCAL_STORE_NAME = 'localStore'\nconst CLS_SESS_STORE_NAME = 'sessionStore'\nconst CLS_CONTRACT_NAME = 'contract'\nconst CLS_PROFILE_IDX = 'prof_idx'\nconst LOG_ERROR_SWITCH = '__error__'\nconst ZERO_IDX = 0\n// export\nexport {\n hashCode,\n getContractFromConfig,\n ENDPOINT_TABLE,\n USERDATA_TABLE,\n CLS_LOCAL_STORE_NAME,\n CLS_SESS_STORE_NAME,\n CLS_CONTRACT_NAME,\n CLS_PROFILE_IDX,\n LOG_ERROR_SWITCH,\n ZERO_IDX\n}\n","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\nfunction polyfill (input) {\n var str = String(input).replace(/=+$/, '');\n if (str.length % 4 == 1) {\n throw new InvalidCharacterError(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = '';\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n return output;\n}\n\n\nmodule.exports = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill;\n","// when the user is login with the jwt\n// we use call this to decode the token and then add the payload\n// to the resolver so the user can call ResolverName.userdata\n// and get back the payload\nimport jwt_decode from 'jwt-decode'\nimport isString from 'jsonql-params-validator/src/string'\nimport JsonqlError from 'jsonql-errors/src/error'\n\nconst timestamp = function (sec = false) {\n var time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n\n/**\n * We only check the nbf and exp\n * @param {object} token for checking\n * @return {object} token on success\n */\nfunction validate(token) {\n const start = token.iat || timestamp(true)\n // we only check the exp for the time being\n if (token.exp) {\n if (start >= token.exp) {\n const expired = new Date(token.exp).toISOString()\n throw new JsonqlError(`Token has expired on ${expired}`, token)\n }\n }\n return token;\n}\n\n/**\n * The browser client version it has far fewer options and it doesn't verify it\n * because it couldn't this is the job for the server\n * @TODO we need to add some extra proessing here to check for the exp field\n * @param {string} token to decrypted\n * @return {object} decrypted object\n */\nexport default function jwtDecode(token) {\n if (isString(token)) {\n const t = jwt_decode(token)\n return validate(t)\n }\n throw new JsonqlError('Token must be a string!')\n}\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n","module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n","// sort of persist on the user side\nimport engine from 'store/src/store-engine'\n\nimport localStorage from 'store/storages/localStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// @1.5.0 stop using the expired plugin, and deal with it ourself\n// import expiredPlugin from 'store/plugins/expire'\nimport eventsPlugin from 'store/plugins/events'\nimport compressionPlugin from 'store/plugins/compression'\n\nconst storages = [localStorage, cookieStorage]\nconst plugins = [defaultPlugin, eventsPlugin, compressionPlugin]\n\nconst localStore = engine.createStore(storages, plugins)\n\nexport default localStore\n","// session store with watch\nimport engine from 'store/src/store-engine'\n\nimport sessionStorage from 'store/storages/sessionStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// start using compression in 1.5.0 \nimport compressionPlugin from 'store/plugins/compression'\n// @1.5.0 stop using the expired plugin and deal it ourself\n// import expiredPlugin from 'store/plugins/expire'\n\nconst storages = [sessionStorage, cookieStorage]\nconst plugins = [defaultPlugin, compressionPlugin]\n\nconst sessionStore = engine.createStore(storages, plugins)\n\nexport default sessionStore\n","// export store interface\n// @TODO need to figure out how to make this as a outside dependencies instead of built into it\nimport localStoreEngine from './local-store'\nimport sessionStoreEngine from './session-store'\n\n// export back the raw version for development purposes\nexport const localStore = localStoreEngine\nexport const sessionStore = sessionStoreEngine\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport isString from 'lodash-es/isString'\n\nimport { timestamp } from './timestamp'\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? JSON.parse(payload) : payload;\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName\n * @param {*} payload\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload) {\n return {\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload;\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload;\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getNameFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// break up from node-middleware\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n API_REQUEST_METHODS,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME ,\n QUERY_ARG_NAME,\n DATA_KEY,\n ERROR_KEY,\n INDEX_KEY,\n EXT,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport { isObjectHasKey } from './generic'\nimport { timestamp } from './timestamp'\nimport isArray from 'lodash-es/isArray'\nimport merge from 'lodash-es/merge'\n/**\n * getting what is calling after the above check\n * @param {string} method of call\n * @return {mixed} false on failed\n */\nexport const getCallMethod = method => {\n const [ POST, PUT ] = API_REQUEST_METHODS;\n switch (true) {\n case method === POST:\n return QUERY_NAME;\n case method === PUT:\n return MUTATION_NAME;\n default:\n return false;\n }\n}\n\n/**\n * wrapper method\n * @param {mixed} result of fn return\n * @param {boolean|array} [ts=false] when pass this then we append a new value to the end\n * @return {string} stringify data\n */\nexport const packResult = function(result, ts = false) {\n let payload = { [DATA_KEY]: result }\n if (ts && isArray(ts)) {\n ts.push(timestamp())\n payload[TIMESTAMP_PARAM_NAME] = ts\n }\n return JSON.stringify(payload)\n}\n\n/**\n * Check if the error object contain out custom key\n * @param {*} e object\n * @return {boolean} true\n */\nexport const isJsonqlErrorObj = e => {\n const searchFields = ['detail', 'className']\n const test = !!searchFields.filter(field => isObjectHasKey(e, field)).length\n if (test) {\n return ['className', 'message', 'statusCode']\n .filter(field => isObjectHasKey(e, field))\n .map(field => (\n {\n [field]: typeof e[field] === 'object' ? e[field].toString() : e[field]\n }\n ))\n .reduce(merge, {detail: e.toString()}) // can only get as much as possible\n }\n return false;\n}\n\n/**\n * wrapper method - the output is trying to match up the structure of the Error sub class\n * @param {mixed} detail of fn error\n * @param {string} [className=JsonqlError] the errorName\n * @param {number} [statusCode=500] the original error code\n * @return {string} stringify error\n */\nexport const packError = function(detail, className = 'JsonqlError', statusCode = 0, message = '') {\n let errorObj = { detail, className, statusCode, message }\n // we need to check the detail object to see if it has detail, className and message\n // if it has then we should merge the object instead\n return JSON.stringify({\n [ERROR_KEY]: isJsonqlErrorObj(detail) || errorObj,\n [TIMESTAMP_PARAM_NAME]: timestamp()\n })\n}\n\n// ported from http-client\n\n/**\n * handle the return data\n * @TODO how to handle the return timestamp and calculate the diff?\n * @param {object} result return from server\n * @return {object} strip the data part out, or if the error is presented\n */\nexport const resultHandler = result => (\n (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result\n)\n","// new 1.5.0\n// create a class method to handle all the saving and retriving data\n// using the instanceKey to id the data hence allow to use multiple instance\nimport merge from 'lodash-es/merge'\nimport { localStore, sessionStore } from '../stores'\nimport { CLS_SESS_STORE_NAME, CLS_LOCAL_STORE_NAME, hashCode } from '../utils'\n\n// this becomes the base class instead of the HttpCls\nexport default class StoreClass {\n\n constructor(opts) {\n this.opts = opts\n // make it a string\n this.instanceKey = hashCode(this.opts.hostname)\n // pass this store for use later\n this.localStore = localStore\n this.sessionStore = sessionStore\n /*\n if (this.opts.debugOn) { // reuse this to clear out the data\n this.log('clear all stores')\n localStore.clearAll()\n sessionStore.clearAll()\n\n localStore.set('TEST', Date.now())\n sessionStore.set('TEST', Date.now())\n }\n */\n }\n // store in local storage id by the instanceKey\n // values should be an object so with key so we just merge\n // into the existing store without going through the keys\n __setMethod(storeType, values) {\n let store = this[storeType]\n let data = this.__getMethod(storeType)\n const skey = this.opts.storageKey\n const ikey = this.instanceKey\n store.set(skey, {\n [ikey]: data ? merge({}, data, values) : values\n })\n }\n // return the data id by the instaceKey\n __getMethod(storeType) {\n let store = this[storeType]\n let data = store.get(this.opts.storageKey)\n return data ? data[this.instanceKey] : false\n }\n // remove from local store id by instanceKey\n __delMethod(storeType, key) {\n let data = this.__getMethod(storeType)\n if (data) {\n let store = {}\n for (let k in data) {\n if (k !== key) {\n store[k] = data[k]\n }\n }\n this.__setMethod(storeType, store)\n }\n }\n // clear everything by this instanceKey\n __clearMethod(storeKey) {\n const skey = this.opts.storageKey\n const store = this[storeKey]\n let data = store.get(skey)\n if (data) {\n let _store = {}\n for (let k in data) {\n if (k !== this.instanceKey) {\n _store[k] = data[k]\n }\n }\n store.set(skey, _store)\n }\n }\n // Alias for different store\n set lset(values) {\n return this.__setMethod(CLS_LOCAL_STORE_NAME, values)\n }\n\n get lget() {\n return this.__getMethod(CLS_LOCAL_STORE_NAME)\n }\n\n ldel(key) {\n return this.__delMethod(CLS_LOCAL_STORE_NAME, key)\n }\n\n lclear() {\n return this.__clearMethod(CLS_LOCAL_STORE_NAME)\n }\n\n // store in session store id by the instanceKey\n set sset(values) {\n // this.log('--- sset ---', values)\n return this.__setMethod(CLS_SESS_STORE_NAME, values)\n }\n\n get sget() {\n return this.__getMethod(CLS_SESS_STORE_NAME)\n }\n\n sdel(key) {\n return this.__delMethod(CLS_SESS_STORE_NAME, key)\n }\n\n sclear() {\n return this.__clearMethod(CLS_SESS_STORE_NAME)\n }\n\n\n}\n","// base HttpClass\nimport merge from 'lodash-es/merge'\nimport {\n createQuery,\n createMutation,\n getNameFromPayload\n} from 'jsonql-utils/src/params-api'\nimport { cacheBurst, urlParams } from 'jsonql-utils/src/urls'\nimport { resultHandler } from 'jsonql-utils/src/results'\nimport { isObject, isString } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlServerError,\n JsonqlError,\n clientErrorsHandler\n} from 'jsonql-errors'\nimport {\n API_REQUEST_METHODS,\n DEFAULT_HEADER,\n JSONP_CALLBACK_NAME,\n SHOW_CONTRACT_DESC_PARAM\n} from 'jsonql-constants'\nimport { LOG_ERROR_SWITCH } from '../utils'\n\n// extract the one we need\nconst [ POST, PUT ] = API_REQUEST_METHODS\n\nimport StoreClass from './store-cls'\n\nexport default class HttpClass extends StoreClass {\n /**\n * The opts has been check at the init stage\n * @param {object} opts configuration options\n */\n constructor(opts) {\n super(opts)\n // change the way how we init Fly\n // flyio now become external depedencies and it makes it easier to switch\n // @BUG should we run test to check if we have the windows object?\n // this.log(opts)\n // this.fly = opts.Fly ? new opts.Fly() : new Fly()\n // to a different environment like WeChat mini app\n\n this.extraHeader = {};\n // @1.2.1 for adding query to the call on the fly\n this.extraParams = {};\n // this.log('start up opts', opts);\n this.reqInterceptor()\n this.resInterceptor()\n }\n\n // set headers for that one call\n set headers(header) {\n this.extraHeader = header;\n }\n\n /**\n * Create the reusage request method\n * @param {object} payload jsonql payload\n * @param {object} options extra options add the request\n * @param {object} headers extra headers add to the call\n * @return {object} the fly request instance\n */\n request(payload, options = {}, headers = {}) {\n this.headers = headers;\n let params = merge({}, cacheBurst(), this.extraParams)\n // @TODO need to add a jsonp url and payload\n if (this.opts.enableJsonp) {\n let resolverName = getNameFromPayload(payload)\n params = merge({}, params, {[JSONP_CALLBACK_NAME]: resolverName})\n payload = payload[resolverName]\n }\n // double up the url param and see what happen @TODO remove later\n const reqParams = merge({}, { method: POST, params }, options)\n this.log('request params', reqParams, this.jsonqlEndpoint)\n\n return this.fly.request(this.jsonqlEndpoint, payload, reqParams)\n }\n\n /**\n * This will replace the create baseRequest method\n *\n */\n reqInterceptor() {\n this.fly.interceptors.request.use(\n req => {\n const headers = this.getHeaders()\n this.log('request interceptor call', headers)\n\n for (let key in headers) {\n req.headers[key] = headers[key]\n }\n return req;\n }\n )\n }\n\n // @TODO\n processJsonp(result) {\n return resultHandler(result)\n }\n\n /**\n * This will be replacement of the first then call\n *\n */\n resInterceptor() {\n const self = this;\n const jsonp = self.opts.enableJsonp;\n this.fly.interceptors.response.use(\n res => {\n this.log('response interceptor call', res)\n self.cleanUp()\n // now more processing here\n // there is a problem if we throw the result.error here\n // the original data is lost, so we need to do what we did before\n // deal with that error in the first then instead\n const result = isString(res.data) ? JSON.parse(res.data) : res.data;\n if (jsonp) {\n return self.processJsonp(result)\n }\n return resultHandler(result)\n },\n // this get call when it's not 200\n err => {\n self.cleanUp()\n this.log(LOG_ERROR_SWITCH, err)\n throw new JsonqlServerError('Server side error', err)\n }\n )\n }\n\n /**\n * Get the headers inject into the call\n * @return {object} headers\n */\n getHeaders() {\n if (this.opts.enableAuth) {\n return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader)\n }\n return merge({}, DEFAULT_HEADER, this.extraHeader)\n }\n\n /**\n * Post http call operation to clean up things we need\n */\n cleanUp() {\n this.extraHeader = {}\n this.extraParams = {}\n }\n\n /**\n * GET for contract only\n * @return {promise} resolve the contract\n */\n getRemoteContract() {\n if (this.opts.showContractDesc) {\n this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM)\n }\n return this.request({}, {method: 'GET'}, this.contractHeader)\n .then(clientErrorsHandler)\n .then(result => {\n this.log('get contract result', result)\n // when refresh the window the result is different!\n // @TODO need to check the Koa side about why is that\n // also it should set a flag if we want the description or not\n if (result.cache && result.contract) {\n return result.contract;\n }\n // just the normal result\n return result\n })\n .catch(err => {\n this.log(LOG_ERROR_SWITCH, 'getRemoteContract err', err)\n throw new JsonqlServerError('getRemoteContract', err)\n })\n }\n\n /**\n * POST to server - query\n * @param {object} name of the resolver\n * @param {array} args arguments\n * @return {object} promise resolve to the resolver return\n */\n query(name, args = []) {\n return this.request(createQuery(name, args))\n .then(clientErrorsHandler)\n }\n\n /**\n * PUT to server - mutation\n * @param {string} name of resolver\n * @param {object} payload what it said\n * @param {object} conditions what it said\n * @return {object} promise resolve to the resolver return\n */\n mutation(name, payload = {}, conditions = {}) {\n return this.request(createMutation(name, payload, conditions), {method: PUT})\n .then(clientErrorsHandler)\n }\n\n}\n","// all the contract related methods will be here\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { timestamp } from 'jsonql-utils/src/timestamp'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { ENDPOINT_TABLE, CLS_CONTRACT_NAME } from '../utils'\nimport { localStore } from '../stores'\nimport HttpClass from './http-cls'\n\n// export\nexport default class ContractClass extends HttpClass {\n\n constructor(opts) {\n super(opts)\n }\n\n /**\n * return the contract public api\n * @return {object} contract\n */\n getContract() {\n const contract = this.readContract()\n this.log('getContract first call', contract)\n return contract ? Promise.resolve(contract)\n : this.getRemoteContract().then(this.storeContract.bind(this))\n }\n\n /**\n * We are changing the way how to auth to get the contract.json\n * Instead of in the url, we will be putting that key value in the header\n * @return {object} header\n */\n get contractHeader() {\n let base = {};\n if (this.opts.contractKey !== false) {\n base[this.opts.contractKeyName] = this.opts.contractKey;\n }\n return base;\n }\n\n /**\n * Save the contract to local store\n * @param {object} contract to save\n * @return {object|boolean} false when its not a contract or contract on OK\n */\n storeContract(contract) {\n // first need to check if the contract is a contract\n if (!isContract(contract)) {\n throw new JsonqlValidationError(`Contract is malformed!`)\n }\n this.lset = {[CLS_CONTRACT_NAME]: contract}\n // return it\n this.log('storeContract return result', contract)\n return contract;\n }\n\n /**\n * return the contract from options or localStore\n * @return {object|boolean} false on not found\n */\n readContract() {\n let contract = isContract(this.opts.contract)\n if (contract !== false) {\n return contract;\n }\n let data = this.lget\n if (data) {\n return data[CLS_CONTRACT_NAME]\n }\n return false;\n }\n}\n","// this is the new auth class that integrate with the jsonql-jwt\n// all the auth related methods will be here\nimport { decodeToken } from 'jsonql-jwt/src/client'\nimport { isNumber } from 'jsonql-params-validator'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { CREDENTIAL_STORAGE_KEY, AUTH_HEADER, BEARER } from 'jsonql-constants'\nimport { CLS_PROFILE_IDX, ZERO_IDX, USERDATA_TABLE } from '../utils'\nimport ContractClass from './contract-cls'\n// export\nexport default class AuthClass extends ContractClass {\n\n constructor(opts) {\n super(opts)\n if (opts.enableAuth) {\n this.setDecoder = decodeToken;\n }\n }\n\n /**\n * for overwrite\n * @param {string} token stored token\n * @return {string} token\n */\n decoder(token) {\n return token;\n }\n\n /**\n * set the profile index\n * @param {number} idx\n */\n set profileIndex(idx) {\n const key = CLS_PROFILE_IDX\n if (isNumber(idx)) {\n this[key] = idx;\n if (this.opts.persistToken) {\n this.lset = {[key]: idx}\n }\n return;\n }\n throw new JsonqlValidationError('profileIndex', `Expect idx to be number but got ${typeof idx}`)\n }\n\n /**\n * get the profile index\n * @return {number} idx\n */\n get profileIndex() {\n const key = CLS_PROFILE_IDX\n if (this.opts.persistToken) {\n const data = this.lget;\n if (data[key]) {\n return data[key]\n }\n }\n return this[key] ? this[key] : ZERO_IDX\n }\n\n /**\n * Return the token from session store\n * @param {number} [idx=false] profile index\n * @return {string} token\n */\n rawAuthToken(idx = false) {\n if (idx !== false) {\n this.profileIndex = idx;\n }\n // this should return from the base\n return this.jsonqlToken; // see base-cls\n }\n\n /**\n * Setter to add a decoder when retrieve user token\n * @param {function} d a decoder\n */\n set setDecoder(d) {\n if (typeof d === 'function') {\n this.decoder = d;\n }\n }\n\n /**\n * getter to return the session or local store set method\n * @param {*} data to save\n * @return {object} set method\n */\n set saveProfile(data) {\n if (this.opts.persistToken) {\n // this.log('--- saveProfile lset ---', data)\n this.lset = data\n } else {\n // this.log('--- saveProfile sset ---', data)\n this.sset = data\n }\n }\n\n /**\n * getter to return the session or local store get method\n * @return {object} get method\n */\n get readProfile() {\n return this.opts.persistToken ? this.lget : this.sget\n }\n\n // these were in the base class before but it should be here\n /**\n * save token\n * @param {string} token to store\n * @return {string|boolean} false on failed\n */\n set jsonqlToken(token) {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n // @TODO also have to make sure the token is not already existed!\n let tokens = (data && data[key]) ? data[key] : []\n tokens.push(token)\n this.saveProfile = {[key]: tokens}\n // store the userdata\n this.jsonqlUserdata = this.decoder(token)\n }\n\n /**\n * Jsonql token getter\n * 1.5.1 each token associate with the same profileIndex\n * @return {string|boolean} false when failed\n */\n get jsonqlToken() {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex])\n return data[key][this.profileIndex]\n }\n return false\n }\n\n /**\n * this one will use the sessionStore\n * basically we hook this onto the token store and decode it to store here\n * we only store one decoded user data at a time, but the token can be multiple\n */\n set jsonqlUserdata(userdata) {\n this.sset = {[USERDATA_TABLE]: userdata}\n }\n\n /**\n * this one store in the session store\n * get login userdata decoded jwt\n * 1.5.1 each userdata associate with the same profileIndex\n * @return {object|null}\n */\n get jsonqlUserdata() {\n const data = this.sget\n return data ? data[USERDATA_TABLE] : false\n }\n\n /**\n * Construct the auth header\n * @return {object} header\n */\n getAuthHeader() {\n const token = this.jsonqlToken // only call the getter to get the default one\n return token ? {[this.opts.AUTH_HEADER]: `${BEARER} ${token}`} : {};\n }\n\n /**\n * return all the stored token and decode it\n * @param {number} [idx=false] profile index\n * @return {array|boolean|string} false not found or array\n */\n getProfiles(idx = false) {\n const self = this; // just in case the scope problem\n const data = self.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n if (idx !== false && isNumber(idx)) {\n return data[key][idx] || false\n }\n return data[key].map(self.decoder.bind(self))\n }\n return false\n }\n\n /**\n * call after the login\n * @param {string} token return from server\n * @return {object} decoded token to userdata object\n */\n postLoginAction(token) {\n this.jsonqlToken = token\n return token\n }\n\n /**\n * call after the logout @TODO\n */\n postLogoutAction(...args) {\n console.info(`postLogoutAction`, args)\n }\n}\n","// this the core of the internal storage management\nimport { CREDENTIAL_STORAGE_KEY } from 'jsonql-constants'\n// import { isObject, isArray } from 'jsonql-params-validator'\n// import { JsonqlValidationError } from 'jsonql-errors'\n// import { timestamp } from 'jsonql-utils/src/timestamp'\n// import { inArray } from 'jsonql-utils/src/generic'\nimport { USERDATA_TABLE, LOG_ERROR_SWITCH } from '../utils'\nimport AuthCls from './auth-cls'\n\n// This class will only focus on the storage system\nexport default class JsonqlBaseClient extends AuthCls {\n // change the order of the interface in 1.4.10 to match up the top level\n constructor(fly, opts) {\n // change at 1.4.10 pass it directly without init it\n this.fly = fly;\n super(opts)\n }\n\n /**\n * construct the end point\n * @return {string} the end point to call\n */\n get jsonqlEndpoint() {\n const baseUrl = this.opts.hostname || ''\n return [baseUrl, this.opts.jsonqlPath].join('/')\n }\n\n /**\n * simple log\n */\n log(...args) {\n if (this.opts.debugOn === true) {\n const fns = ['info', 'error']\n const idx = (args[0] === LOG_ERROR_SWITCH) ? 1 : 0\n Reflect.apply(console[fns[idx]], console, args.splice(0, idx))\n }\n }\n\n}\n","// export interface\n// @public\nimport JsonqlBaseClient from './base-cls'\n\nexport default JsonqlBaseClient\n","// all the client configuration options here\nimport {\n JSONQL_PATH,\n CONTENT_TYPE,\n BEARER,\n CLIENT_STORAGE_KEY,\n CLIENT_AUTH_KEY,\n CONTRACT_KEY_NAME,\n AUTH_HEADER,\n ISSUER_NAME,\n LOGOUT_NAME,\n BOOLEAN_TYPE,\n STRING_TYPE,\n NUMBER_TYPE,\n DEFAULT_HEADER\n} from 'jsonql-constants'\nimport { createConfig } from 'jsonql-params-validator'\nexport const constProps = {\n contract: false,\n MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong?\n CONTENT_TYPE,\n BEARER,\n AUTH_HEADER\n}\n\n// grab the localhost name and put into the hostname as default\nconst getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n return null\n }\n}\n\nexport const appProps = {\n\n hostname: createConfig(getHostName(), [STRING_TYPE]), // required the hostname\n jsonqlPath: createConfig(JSONQL_PATH, [STRING_TYPE]), // The path on the server\n\n loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]),\n logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]),\n // add to koa v1.3.0 - this might remove in the future\n enableJsonp: createConfig(false, [BOOLEAN_TYPE]),\n enableAuth: createConfig(false, [BOOLEAN_TYPE]),\n // enable useJwt by default @TODO replace with something else and remove them later\n useJwt: createConfig(true, [BOOLEAN_TYPE]),\n // when true then store infinity or pass a time in seconds then we check against\n // the token date of creation\n persistToken: createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE]),\n // the header\n // v1.2.0 we are using this option during the dev\n // so it won't save anything to the localstorage and fetch a new contract\n // whenever the browser reload\n useLocalstorage: createConfig(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage\n storageKey: createConfig(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage\n authKey: createConfig(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage\n contractExpired: createConfig(0, [NUMBER_TYPE]),// -1 always fetch contract,\n // 0 never expired,\n // > 0 then compare the timestamp with the current one to see if we need to get contract again\n // useful during development\n keepContract: createConfig(true, [BOOLEAN_TYPE]),\n exposeContract: createConfig(false, [BOOLEAN_TYPE]),\n exposeStore: createConfig(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn \n // @1.2.1 new option for the contract-console to fetch the contract with description\n showContractDesc: createConfig(false, [BOOLEAN_TYPE]),\n contractKey: createConfig(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this\n contractKeyName: createConfig(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs\n enableTimeout: createConfig(false, [BOOLEAN_TYPE]), // @TODO\n timeout: createConfig(5000, [NUMBER_TYPE]), // 5 seconds\n returnInstance: createConfig(false, [BOOLEAN_TYPE]),\n allowReturnRawToken: createConfig(false, [BOOLEAN_TYPE]),\n debugOn: createConfig(false, [BOOLEAN_TYPE])\n}\n","// This is for the sync version therefore we don't need to care about the contract options\nimport { appProps, constProps } from './base-options'\nimport { checkConfig } from 'jsonql-params-validator'\n\nexport default function checkOptions(config) {\n return checkConfig(config, appProps, constProps)\n}\n","// export interface\nimport checkOptionsAsyncLocal from './check-options-async'\nimport checkOptionsLocal from './check-options'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport { objHasProp } from 'jsonql-utils/src/obj-define-props'\n/**\n * 1.5.0 overload the orginal functions to pass over the check\n */\nfunction checkOptionsAsync(config) {\n return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsyncLocal(config)\n}\n\n// sync version without needing the promise\nfunction checkOptions(config) {\n return objHasProp(config, CHECKED_KEY) ? config : checkOptionsLocal(config)\n}\n\nexport {\n checkOptionsAsync,\n checkOptions\n}\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n\nexport default class SuspendClass {\n\n constructor() {\n // suspend, release and queue\n this.__suspend__ = null;\n this.queueStore = new Set()\n /*\n this.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n })\n */\n }\n\n /**\n * setter to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n set $suspend(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend__;\n this.__suspend__ = value;\n this.logger('($suspend)', `Change from ${lastValue} --> ${value}`)\n if (lastValue === true && value === false) {\n setTimeout(() => {\n this.release()\n }, 1)\n }\n } else {\n throw new Error(`$suspend only accept Boolean value!`)\n }\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {any} value\n * @return {Boolean} true when added or false when it's not\n */\n $queue(...args) {\n if (this.__suspend__ === true) {\n this.logger('($queue)', 'added to $queue', args)\n // there shouldn't be any duplicate ...\n this.queueStore.add(args)\n }\n return this.__suspend__;\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size;\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n release() {\n let size = this.queueStore.size\n this.logger('(release)', `Release was called ${size}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('queue', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport genHaskKey from './hash-code'\nimport SuspendClass from './suspend'\n\nexport default class NbEventServiceBase extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger;\n }\n this.keep = config.keep;\n // for the $done setter\n this.result = config.keep ? [] : null;\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (typeof e !== 'string') {\n this.logger('(validateEvt)', e)\n throw new Error(`event name must be string type!`)\n }\n })\n return true;\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n return true;\n }\n }\n throw new Error(`callback required to be function type!`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n const types = ['on', 'only', 'once', 'onlyOnce']\n return !!types.filter(t => type === t).length;\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run)', callback, payload, ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName]; // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger('(takeFromStore)', `has ${evt}`, content)\n store.delete(evt)\n return content;\n }\n return false;\n }\n throw new Error(`${storeName} is not supported!`)\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n let fnSet;\n if (store.has(evt)) {\n this.logger('(addToStore)', `${evt} existed`)\n fnSet = store.get(evt)\n } else {\n this.logger('(addToStore)', `create new Set for ${evt}`)\n // this is new\n fnSet = new Set()\n }\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args;\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger('(addToStore)', `insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(l => {\n let [hash,] = l;\n if (hash === args[0]) {\n return true;\n }\n return false;\n }).length;\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true;\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list;\n return type !== t;\n }).length;\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n this.logger('(checkTypeInLazyStore)', store)\n if (store) {\n return !!Array\n .from(store)\n .filter(l => {\n let [,,t] = l;\n return t !== type;\n }).length\n }\n return false;\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger('(addToNormalStore)', evt, type, 'try to add to normal store')\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n this.logger('(addToNormalStore)', `${type} can add to ${evt} normal store`)\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store;\n return size;\n }\n return false;\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store;\n return size;\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg];\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n return genHaskKey(fn.toString()) + '';\n }\n}\n","// The top level\nimport NbStoreService from './store-service'\n// export\nexport default class EventService extends NbStoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on';\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger('($on)', `${evt} callback is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger('($on)', `${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0;\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($on)`, `call run on ${evt}`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n return size;\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n const type = 'once';\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (lazyStoreContent === false) {\n this.logger('($once)', `${evt} not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, type, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger('($once)', `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'only';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($only)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($only)', `${evt} found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( l => {\n const [ payload, ctx, t ] = l;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($only)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n })\n }\n return added;\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD added in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'onlyOnce';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== 'onlyOnce') {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($onlyOnce)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added;\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {}\n */\n $replace(evt, callback, context = null, type = 'on') {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n this.logger(`($replace)`, evt, callback)\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0;\n // first check the normal store\n let nStore = this.normalStore;\n this.logger('($trigger)', 'normalStore', nStore)\n if (nStore.has(evt)) {\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n this.logger('($trigger)', evt, 'found; add to queue: ', added)\n if (added === true) {\n this.logger('($trigger)', evt, 'not executed. Exit now.')\n return false; // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length;\n let hasOnce = false;\n let hasOnly = false;\n for (let i=0; i < ctn; ++i) {\n ++found;\n // this.logger('found', found)\n let [ _, callback, ctx, type ] = nSet[i]\n this.logger(`($trigger)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n if (type === 'once' || type === 'onlyOnce') {\n hasOnce = true;\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found;\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found;\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter around\n * @param {string} evt event name\n * @param {*} params pass to the callback\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, params, type = false, context = null) {\n let args = [evt, params, context, type]\n return Reflect.apply(this.$trigger, this, args)\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n let found = false;\n stores.forEach(store => {\n if (store.has(evt)) {\n found = true;\n this.logger('($off)', evt)\n store.delete(evt)\n }\n })\n return found;\n }\n\n /**\n * return all the listener from the event\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n this.validateEvt(evt)\n let store = this.normalStore;\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l;\n }\n let [key, callback, ] = l;\n return callback;\n })\n }\n return false;\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done)', 'value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value;\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n if (this.keep) {\n this.logger('(get $done)', this.result)\n return this.result[this.result.length - 1]\n }\n return this.result;\n }\n\n\n}\n","// default\nimport NBEventService from './src/event-service'\n\nexport default NBEventService\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// output\nexport default function(debugOn) {\n let logger = debugOn ? (...args) => {\n args.unshift('[NBS]')\n console.log.apply(null, args)\n }: undefined;\n return new NBEventService({ logger })\n}\n","// this is the new Event base interface\n// the export will be different and purposely design for framework that\n// is very hard to use Promise such as Vue\nimport jsonqlStaticGenerator from './core/jsonql-static-generator'\nimport JsonqlBaseClient from './base'\nimport { checkOptions } from './options'\nimport { getContractFromConfig } from './utils'\nimport getEventEmitter from './ee'\n/**\n * this is the slim client without Fly, you pick the version of Fly to use\n * This is a breaking change because it swap the input positions\n * @param {object} fly fly.js\n * @param {object} config configuration\n * @return {object} the jsonql client instance\n */\nexport default function jsonqlStaticClient(fly, config = {}) {\n const { contract } = config;\n const opts = checkOptions(config)\n const jsonqlBase = new JsonqlBaseClient(fly, opts)\n const contractPromise = getContractFromConfig(jsonqlBase, contract)\n const ee = getEventEmitter(opts.debugOn)\n // finally\n let methods = jsonqlStaticGenerator(jsonqlBase, opts, contractPromise, ee)\n methods.eventEmitter = ee;\n return methods;\n}\n","// This is the static version that build with the Fly for Browser\nimport Fly from 'flyio/dist/npm/fly'\nimport jsonqlStaticClient from './static'\n\n// this is the slim client without Fly\nexport default function jsonqlStaticClientFull(config = {}) {\n return jsonqlStaticClient(new Fly(), config)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"jsonql-client.static.js","sources":["../node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"8mjDAAA"} \ No newline at end of file diff --git a/packages/http-client/dist/jsonql-client.umd.js b/packages/http-client/dist/jsonql-client.umd.js index 3203c88b..53b86dac 100644 --- a/packages/http-client/dist/jsonql-client.umd.js +++ b/packages/http-client/dist/jsonql-client.umd.js @@ -1,9559 +1,2 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = global || self, global.jsonqlClient = factory()); -}(this, (function () { 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var fly = createCommonjsModule(function (module, exports) { - (function webpackUniversalModuleDefinition(root, factory) { - { module.exports = factory(); } - })(commonjsGlobal, function() { - return /******/ (function(modules) { // webpackBootstrap - /******/ // The module cache - /******/ var installedModules = {}; - /******/ - /******/ // The require function - /******/ function __webpack_require__(moduleId) { - /******/ - /******/ // Check if module is in cache - /******/ if(installedModules[moduleId]) { - /******/ return installedModules[moduleId].exports; - /******/ } - /******/ // Create a new module (and put it into the cache) - /******/ var module = installedModules[moduleId] = { - /******/ i: moduleId, - /******/ l: false, - /******/ exports: {} - /******/ }; - /******/ - /******/ // Execute the module function - /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - /******/ - /******/ // Flag the module as loaded - /******/ module.l = true; - /******/ - /******/ // Return the exports of the module - /******/ return module.exports; - /******/ } - /******/ - /******/ - /******/ // expose the modules object (__webpack_modules__) - /******/ __webpack_require__.m = modules; - /******/ - /******/ // expose the module cache - /******/ __webpack_require__.c = installedModules; - /******/ - /******/ // identity function for calling harmony imports with the correct context - /******/ __webpack_require__.i = function(value) { return value; }; - /******/ - /******/ // define getter function for harmony exports - /******/ __webpack_require__.d = function(exports, name, getter) { - /******/ if(!__webpack_require__.o(exports, name)) { - /******/ Object.defineProperty(exports, name, { - /******/ configurable: false, - /******/ enumerable: true, - /******/ get: getter - /******/ }); - /******/ } - /******/ }; - /******/ - /******/ // getDefaultExport function for compatibility with non-harmony modules - /******/ __webpack_require__.n = function(module) { - /******/ var getter = module && module.__esModule ? - /******/ function getDefault() { return module['default']; } : - /******/ function getModuleExports() { return module; }; - /******/ __webpack_require__.d(getter, 'a', getter); - /******/ return getter; - /******/ }; - /******/ - /******/ // Object.prototype.hasOwnProperty.call - /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; - /******/ - /******/ // __webpack_public_path__ - /******/ __webpack_require__.p = ""; - /******/ - /******/ // Load entry module and return exports - /******/ return __webpack_require__(__webpack_require__.s = 2); - /******/ }) - /************************************************************************/ - /******/ ([ - /* 0 */ - /***/ (function(module, exports, __webpack_require__) { - - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - module.exports = { - type: function type(ob) { - return Object.prototype.toString.call(ob).slice(8, -1).toLowerCase(); - }, - isObject: function isObject(ob, real) { - if (real) { - return this.type(ob) === "object"; - } else { - return ob && (typeof ob === 'undefined' ? 'undefined' : _typeof(ob)) === 'object'; - } - }, - isFormData: function isFormData(val) { - return typeof FormData !== 'undefined' && val instanceof FormData; - }, - trim: function trim(str) { - return str.replace(/(^\s*)|(\s*$)/g, ''); - }, - encode: function encode(val) { - return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); - }, - formatParams: function formatParams(data) { - var str = ""; - var first = true; - var that = this; - if (!this.isObject(data)) { - return data; - } - - function _encode(sub, path) { - var encode = that.encode; - var type = that.type(sub); - if (type == "array") { - sub.forEach(function (e, i) { - if (!that.isObject(e)) { i = ""; } - _encode(e, path + ('%5B' + i + '%5D')); - }); - } else if (type == "object") { - for (var key in sub) { - if (path) { - _encode(sub[key], path + "%5B" + encode(key) + "%5D"); - } else { - _encode(sub[key], encode(key)); - } - } - } else { - if (!first) { - str += "&"; - } - first = false; - str += path + "=" + encode(sub); - } - } - - _encode(data, ""); - return str; - }, - - // Do not overwrite existing attributes - merge: function merge(a, b) { - for (var key in b) { - if (!a.hasOwnProperty(key)) { - a[key] = b[key]; - } else if (this.isObject(b[key], 1) && this.isObject(a[key], 1)) { - this.merge(a[key], b[key]); - } - } - return a; - } - }; - - /***/ }), - /* 1 */, - /* 2 */ - /***/ (function(module, exports, __webpack_require__) { - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - var utils = __webpack_require__(0); - var isBrowser = typeof document !== "undefined"; - - var Fly = function () { - function Fly(engine) { - _classCallCheck(this, Fly); - - this.engine = engine || XMLHttpRequest; - - this.default = this; //For typeScript - - /** - * Add lock/unlock API for interceptor. - * - * Once an request/response interceptor is locked, the incoming request/response - * will be added to a queue before they enter the interceptor, they will not be - * continued until the interceptor is unlocked. - * - * @param [interceptor] either is interceptors.request or interceptors.response - */ - function wrap(interceptor) { - var resolve = void 0; - var reject = void 0; - - function _clear() { - interceptor.p = resolve = reject = null; - } - - utils.merge(interceptor, { - lock: function lock() { - if (!resolve) { - interceptor.p = new Promise(function (_resolve, _reject) { - resolve = _resolve; - reject = _reject; - }); - } - }, - unlock: function unlock() { - if (resolve) { - resolve(); - _clear(); - } - }, - clear: function clear() { - if (reject) { - reject("cancel"); - _clear(); - } - } - }); - } - - var interceptors = this.interceptors = { - response: { - use: function use(handler, onerror) { - this.handler = handler; - this.onerror = onerror; - } - }, - request: { - use: function use(handler) { - this.handler = handler; - } - } - }; - - var irq = interceptors.request; - var irp = interceptors.response; - wrap(irp); - wrap(irq); - - this.config = { - method: "GET", - baseURL: "", - headers: {}, - timeout: 0, - params: {}, // Default Url params - parseJson: true, // Convert response data to JSON object automatically. - withCredentials: false - }; - } - - _createClass(Fly, [{ - key: "request", - value: function request(url, data, options) { - var _this = this; - - var engine = new this.engine(); - var contentType = "Content-Type"; - var contentTypeLowerCase = contentType.toLowerCase(); - var interceptors = this.interceptors; - var requestInterceptor = interceptors.request; - var responseInterceptor = interceptors.response; - var requestInterceptorHandler = requestInterceptor.handler; - var promise = new Promise(function (resolve, reject) { - if (utils.isObject(url)) { - options = url; - url = options.url; - } - options = options || {}; - options.headers = options.headers || {}; - - function isPromise(p) { - // some polyfill implementation of Promise may be not standard, - // so, we test by duck-typing - return p && p.then && p.catch; - } - - /** - * If the request/response interceptor has been locked, - * the new request/response will enter a queue. otherwise, it will be performed directly. - * @param [promise] if the promise exist, means the interceptor is locked. - * @param [callback] - */ - function enqueueIfLocked(promise, callback) { - if (promise) { - promise.then(function () { - callback(); - }); - } else { - callback(); - } - } - - // make the http request - function makeRequest(options) { - data = options.body; - // Normalize the request url - url = utils.trim(options.url); - var baseUrl = utils.trim(options.baseURL || ""); - if (!url && isBrowser && !baseUrl) { url = location.href; } - if (url.indexOf("http") !== 0) { - var isAbsolute = url[0] === "/"; - if (!baseUrl && isBrowser) { - var arr = location.pathname.split("/"); - arr.pop(); - baseUrl = location.protocol + "//" + location.host + (isAbsolute ? "" : arr.join("/")); - } - if (baseUrl[baseUrl.length - 1] !== "/") { - baseUrl += "/"; - } - url = baseUrl + (isAbsolute ? url.substr(1) : url); - if (isBrowser) { - - // Normalize the url which contains the ".." or ".", such as - // "http://xx.com/aa/bb/../../xx" to "http://xx.com/xx" . - var t = document.createElement("a"); - t.href = url; - url = t.href; - } - } - - var responseType = utils.trim(options.responseType || ""); - var needQuery = ["GET", "HEAD", "DELETE", "OPTION"].indexOf(options.method) !== -1; - var dataType = utils.type(data); - var params = options.params || {}; - - // merge url params when the method is "GET" (data is object) - if (needQuery && dataType === "object") { - params = utils.merge(data, params); - } - // encode params to String - params = utils.formatParams(params); - - // save url params - var _params = []; - if (params) { - _params.push(params); - } - // Add data to url params when the method is "GET" (data is String) - if (needQuery && data && dataType === "string") { - _params.push(data); - } - - // make the final url - if (_params.length > 0) { - url += (url.indexOf("?") === -1 ? "?" : "&") + _params.join("&"); - } - - engine.open(options.method, url); - - // try catch for ie >=9 - try { - engine.withCredentials = !!options.withCredentials; - engine.timeout = options.timeout || 0; - if (responseType !== "stream") { - engine.responseType = responseType; - } - } catch (e) {} - - var customContentType = options.headers[contentType] || options.headers[contentTypeLowerCase]; - - // default content type - var _contentType = "application/x-www-form-urlencoded"; - // If the request data is json object, transforming it to json string, - // and set request content-type to "json". In browser, the data will - // be sent as RequestBody instead of FormData - if (utils.trim((customContentType || "").toLowerCase()) === _contentType) { - data = utils.formatParams(data); - } else if (!utils.isFormData(data) && ["object", "array"].indexOf(utils.type(data)) !== -1) { - _contentType = 'application/json;charset=utf-8'; - data = JSON.stringify(data); - } - //If user doesn't set content-type, set default. - if (!(customContentType || needQuery)) { - options.headers[contentType] = _contentType; - } - - for (var k in options.headers) { - if (k === contentType && utils.isFormData(data)) { - // Delete the content-type, Let the browser set it - delete options.headers[k]; - } else { - try { - // In browser environment, some header fields are readonly, - // write will cause the exception . - engine.setRequestHeader(k, options.headers[k]); - } catch (e) {} - } - } - - function onresult(handler, data, type) { - enqueueIfLocked(responseInterceptor.p, function () { - if (handler) { - //如果失败,添加请求信息 - if (type) { - data.request = options; - } - var ret = handler.call(responseInterceptor, data, Promise); - data = ret === undefined ? data : ret; - } - if (!isPromise(data)) { - data = Promise[type === 0 ? "resolve" : "reject"](data); - } - data.then(function (d) { - resolve(d); - }).catch(function (e) { - reject(e); - }); - }); - } - - function onerror(e) { - e.engine = engine; - onresult(responseInterceptor.onerror, e, -1); - } - - function Err(msg, status) { - this.message = msg; - this.status = status; - } - - engine.onload = function () { - try { - // The xhr of IE9 has not response field - var response = engine.response || engine.responseText; - if (response && options.parseJson && (engine.getResponseHeader(contentType) || "").indexOf("json") !== -1 - // Some third engine implementation may transform the response text to json object automatically, - // so we should test the type of response before transforming it - && !utils.isObject(response)) { - response = JSON.parse(response); - } - - var headers = engine.responseHeaders; - // In browser - if (!headers) { - headers = {}; - var items = (engine.getAllResponseHeaders() || "").split("\r\n"); - items.pop(); - items.forEach(function (e) { - if (!e) { return; } - var key = e.split(":")[0]; - headers[key] = engine.getResponseHeader(key); - }); - } - var status = engine.status; - var statusText = engine.statusText; - var _data = { data: response, headers: headers, status: status, statusText: statusText }; - // The _response filed of engine is set in adapter which be called in engine-wrapper.js - utils.merge(_data, engine._response); - if (status >= 200 && status < 300 || status === 304) { - _data.engine = engine; - _data.request = options; - onresult(responseInterceptor.handler, _data, 0); - } else { - var e = new Err(statusText, status); - e.response = _data; - onerror(e); - } - } catch (e) { - onerror(new Err(e.msg, engine.status)); - } - }; - - engine.onerror = function (e) { - onerror(new Err(e.msg || "Network Error", 0)); - }; - - engine.ontimeout = function () { - onerror(new Err("timeout [ " + engine.timeout + "ms ]", 1)); - }; - engine._options = options; - setTimeout(function () { - engine.send(needQuery ? null : data); - }, 0); - } - - enqueueIfLocked(requestInterceptor.p, function () { - utils.merge(options, JSON.parse(JSON.stringify(_this.config))); - var headers = options.headers; - headers[contentType] = headers[contentType] || headers[contentTypeLowerCase] || ""; - delete headers[contentTypeLowerCase]; - options.body = data || options.body; - url = utils.trim(url || ""); - options.method = options.method.toUpperCase(); - options.url = url; - var ret = options; - if (requestInterceptorHandler) { - ret = requestInterceptorHandler.call(requestInterceptor, options, Promise) || options; - } - if (!isPromise(ret)) { - ret = Promise.resolve(ret); - } - ret.then(function (d) { - //if options continue - if (d === options) { - makeRequest(d); - } else { - resolve(d); - } - }, function (err) { - reject(err); - }); - }); - }); - promise.engine = engine; - return promise; - } - }, { - key: "all", - value: function all(promises) { - return Promise.all(promises); - } - }, { - key: "spread", - value: function spread(callback) { - return function (arr) { - return callback.apply(null, arr); - }; - } - }]); - - return Fly; - }(); - - //For typeScript - - - Fly.default = Fly; - - ["get", "post", "put", "patch", "head", "delete"].forEach(function (e) { - Fly.prototype[e] = function (url, data, option) { - return this.request(url, data, utils.merge({ method: e }, option)); - }; - }); - ["lock", "unlock", "clear"].forEach(function (e) { - Fly.prototype[e] = function () { - this.interceptors.request[e](); - }; - }); - module.exports = Fly; - - /***/ }) - /******/ ]); - }); - }); - - var Fly = unwrapExports(fly); - - // the core stuff to id if it's calling with jsonql - var DATA_KEY = 'data'; - var ERROR_KEY = 'error'; - - var JSONQL_PATH = 'jsonql'; - // according to the json query spec - var CONTENT_TYPE = 'application/vnd.api+json'; - var CHARSET = 'charset=utf-8'; - var DEFAULT_HEADER = { - 'Accept': CONTENT_TYPE, - 'Content-Type': [ CONTENT_TYPE, CHARSET ].join(';') - }; - - // export const INDEX = 'index'; use INDEX_KEY instead - var DEFAULT_TYPE = 'any'; - - // @TODO remove this is not in use - // export const CLIENT_CONFIG_FILE = '.clients.json'; - // export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js'; - // type of resolvers - var QUERY_NAME = 'query'; - var MUTATION_NAME = 'mutation'; - var SOCKET_NAME = 'socket'; - // for calling the mutation - var PAYLOAD_PARAM_NAME = 'payload'; // @TODO shortern them - var CONDITION_PARAM_NAME = 'condition'; - var QUERY_ARG_NAME = 'args'; - var TIMESTAMP_PARAM_NAME = 'TS'; - // new jsonp - var JSONP_CALLBACK_NAME = 'jsonqlJsonpCallback'; - - // methods allow - var API_REQUEST_METHODS = ['POST', 'PUT']; - // for contract-cli - var KEY_WORD = 'continue'; - - var TYPE_KEY = 'type'; - var OPTIONAL_KEY = 'optional'; - var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word - var ARGS_KEY = 'args'; - var CHECKER_KEY = 'checker'; - var ALIAS_KEY = 'alias'; - var CHECKED_KEY = '__checked__'; - var LOGIN_NAME = 'login'; - var ISSUER_NAME = LOGIN_NAME; // legacy issue need to replace them later - var LOGOUT_NAME = 'logout'; - - var AUTH_HEADER = 'Authorization'; - var BEARER = 'Bearer'; - - // for client use @TODO need to clean this up some of them are not in use - var CREDENTIAL_STORAGE_KEY = 'jsonqlcredential'; - var CLIENT_STORAGE_KEY = 'jsonqlstore'; - var CLIENT_AUTH_KEY = 'jsonqlauthkey'; - // contract key - var CONTRACT_KEY_NAME = 'X-JSONQL-CV-KEY'; - var SHOW_CONTRACT_DESC_PARAM = {desc: 'y'}; - - var OR_SEPERATOR = '|'; - - var STRING_TYPE = 'string'; - var BOOLEAN_TYPE = 'boolean'; - var ARRAY_TYPE = 'array'; - var OBJECT_TYPE = 'object'; - - var NUMBER_TYPE = 'number'; - var ARRAY_TYPE_LFT = 'array.<'; - var ARRAY_TYPE_RGT = '>'; - - var NO_ERROR_MSG = 'No message'; - var NO_STATUS_CODE = -1; - var HSA_ALGO = 'HS256'; - - /** - * 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; - - 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$1 = root.Symbol; - - /** 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$1 ? Symbol$1.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$1 ? Symbol$1.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); - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** Built-in value references. */ - var getPrototype = overArg(Object.getPrototypeOf, Object); - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @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 objectTag = '[object Object]'; - - /** Used for built-in method references. */ - var funcProto = Function.prototype, - objectProto$2 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty$1.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; - } - - /** - * 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; - } - - /** `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$1 ? Symbol$1.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(''); - } - - // bunch of generic helpers - - /** - * DIY in Array - * @param {array} arr to check from - * @param {*} value to check against - * @return {boolean} true on found - */ - var inArray = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; - - // quick and dirty to turn non array to array - var toArray = function (arg) { return isArray(arg) ? arg : [arg]; }; - - /** - * @param {object} obj for search - * @param {string} key target - * @return {boolean} true on success - */ - var isObjectHasKey = function(obj, key) { - try { - var keys = Object.keys(obj); - return inArray(keys, key) - } catch(e) { - // @BUG when the obj is not an OBJECT we got some weird output - return false; - /* - console.info('obj', obj) - console.error(e) - throw new Error(e) - */ - } - }; - - /** - * This is a custom error to throw when server throw a 406 - * 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 Jsonql406Error = /*@__PURE__*/(function (Error) { - function Jsonql406Error() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - // We can't access the static name from an instance - // but we can do it like this - this.className = Jsonql406Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql406Error); - } - } - - if ( Error ) Jsonql406Error.__proto__ = Error; - Jsonql406Error.prototype = Object.create( Error && Error.prototype ); - Jsonql406Error.prototype.constructor = Jsonql406Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 406; - }; - - staticAccessors.name.get = function () { - return 'Jsonql406Error'; - }; - - Object.defineProperties( Jsonql406Error, staticAccessors ); - - return Jsonql406Error; - }(Error)); - - /** - * This is a custom error to throw when server throw a 500 - * 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 Jsonql500Error = /*@__PURE__*/(function (Error) { - function Jsonql500Error() { - 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 = Jsonql500Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql500Error); - } - } - - if ( Error ) Jsonql500Error.__proto__ = Error; - Jsonql500Error.prototype = Object.create( Error && Error.prototype ); - Jsonql500Error.prototype.constructor = Jsonql500Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'Jsonql500Error'; - }; - - Object.defineProperties( Jsonql500Error, staticAccessors ); - - return Jsonql500Error; - }(Error)); - - /** - * this is the 403 Forbidden error - * that means this user is not login - * use the 401 for try to login and failed - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlForbiddenError = /*@__PURE__*/(function (Error) { - function JsonqlForbiddenError() { - 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 = JsonqlForbiddenError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlForbiddenError); - } - } - - if ( Error ) JsonqlForbiddenError.__proto__ = Error; - JsonqlForbiddenError.prototype = Object.create( Error && Error.prototype ); - JsonqlForbiddenError.prototype.constructor = JsonqlForbiddenError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 403; - }; - - staticAccessors.name.get = function () { - return 'JsonqlForbiddenError'; - }; - - Object.defineProperties( JsonqlForbiddenError, staticAccessors ); - - return JsonqlForbiddenError; - }(Error)); - - /** - * This is a custom error to throw when pass credential but fail - * 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 JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { - function JsonqlAuthorisationError() { - 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 = JsonqlAuthorisationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlAuthorisationError); - } - } - - if ( Error ) JsonqlAuthorisationError.__proto__ = Error; - JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); - JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlAuthorisationError'; - }; - - Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); - - return JsonqlAuthorisationError; - }(Error)); - - /** - * This is a custom error when not supply the credential and try to get contract - * 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 JsonqlContractAuthError = /*@__PURE__*/(function (Error) { - function JsonqlContractAuthError() { - 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 = JsonqlContractAuthError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlContractAuthError); - } - } - - if ( Error ) JsonqlContractAuthError.__proto__ = Error; - JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); - JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlContractAuthError'; - }; - - Object.defineProperties( JsonqlContractAuthError, staticAccessors ); - - return JsonqlContractAuthError; - }(Error)); - - /** - * This is a custom error to throw when the resolver throw error and capture inside the middleware - * 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 JsonqlResolverAppError = /*@__PURE__*/(function (Error) { - function JsonqlResolverAppError() { - 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 = JsonqlResolverAppError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverAppError); - } - } - - if ( Error ) JsonqlResolverAppError.__proto__ = Error; - JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverAppError'; - }; - - Object.defineProperties( JsonqlResolverAppError, staticAccessors ); - - return JsonqlResolverAppError; - }(Error)); - - /** - * This is a custom error to throw when could not find the resolver - * 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 JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { - function JsonqlResolverNotFoundError() { - 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 = JsonqlResolverNotFoundError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverNotFoundError); - } - } - - if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; - JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 404; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverNotFoundError'; - }; - - Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); - - return JsonqlResolverNotFoundError; - }(Error)); - - // this get throw from within the checkOptions when run through the enum failed - var JsonqlEnumError = /*@__PURE__*/(function (Error) { - function JsonqlEnumError() { - 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 = JsonqlEnumError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlEnumError); - } - } - - if ( Error ) JsonqlEnumError.__proto__ = Error; - JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); - JsonqlEnumError.prototype.constructor = JsonqlEnumError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlEnumError'; - }; - - Object.defineProperties( JsonqlEnumError, staticAccessors ); - - return JsonqlEnumError; - }(Error)); - - // this will throw from inside the checkOptions - var JsonqlTypeError = /*@__PURE__*/(function (Error) { - function JsonqlTypeError() { - 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 = JsonqlTypeError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlTypeError); - } - } - - if ( Error ) JsonqlTypeError.__proto__ = Error; - JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); - JsonqlTypeError.prototype.constructor = JsonqlTypeError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlTypeError'; - }; - - Object.defineProperties( JsonqlTypeError, staticAccessors ); - - return JsonqlTypeError; - }(Error)); - - // allow supply a custom checker function - // if that failed then we throw this error - var JsonqlCheckerError = /*@__PURE__*/(function (Error) { - function JsonqlCheckerError() { - 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 = JsonqlCheckerError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlCheckerError); - } - } - - if ( Error ) JsonqlCheckerError.__proto__ = Error; - JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); - JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlCheckerError'; - }; - - Object.defineProperties( JsonqlCheckerError, staticAccessors ); - - return JsonqlCheckerError; - }(Error)); - - // custom validation error class - // when validaton failed - var JsonqlValidationError = /*@__PURE__*/(function (Error) { - function JsonqlValidationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlValidationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlValidationError); - } - } - - if ( Error ) JsonqlValidationError.__proto__ = Error; - JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); - JsonqlValidationError.prototype.constructor = JsonqlValidationError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlValidationError'; - }; - - Object.defineProperties( JsonqlValidationError, staticAccessors ); - - return JsonqlValidationError; - }(Error)); - - /** - * This is a custom error to throw whenever a error happen inside the jsonql - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlError = /*@__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)); - - // this is from an example from Koa team to use for internal middleware ctx.throw - // but after the test the res.body part is unable to extract the required data - // I keep this one here for future reference - - var JsonqlServerError = /*@__PURE__*/(function (Error) { - function JsonqlServerError(statusCode, message) { - Error.call(this, message); - this.statusCode = statusCode; - this.className = JsonqlServerError.name; - } - - if ( Error ) JsonqlServerError.__proto__ = Error; - JsonqlServerError.prototype = Object.create( Error && Error.prototype ); - JsonqlServerError.prototype.constructor = JsonqlServerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlServerError'; - }; - - Object.defineProperties( JsonqlServerError, staticAccessors ); - - return JsonqlServerError; - }(Error)); - - // server side - - var errors = /*#__PURE__*/Object.freeze({ - __proto__: null, - Jsonql406Error: Jsonql406Error, - Jsonql500Error: Jsonql500Error, - JsonqlForbiddenError: JsonqlForbiddenError, - JsonqlAuthorisationError: JsonqlAuthorisationError, - JsonqlContractAuthError: JsonqlContractAuthError, - JsonqlResolverAppError: JsonqlResolverAppError, - JsonqlResolverNotFoundError: JsonqlResolverNotFoundError, - JsonqlEnumError: JsonqlEnumError, - JsonqlTypeError: JsonqlTypeError, - JsonqlCheckerError: JsonqlCheckerError, - JsonqlValidationError: JsonqlValidationError, - JsonqlError: JsonqlError, - JsonqlServerError: JsonqlServerError - }); - - // this will add directly to the then call in each http call - var JsonqlError$1 = JsonqlError; - - /** - * We can not just check something like result.data what if the result if false? - * @param {object} obj the result object - * @param {string} key we want to check if its exist or not - * @return {boolean} true on found - */ - var isObjectHasKey$1 = function (obj, key) { - var keys = Object.keys(obj); - return !!keys.filter(function (k) { return key === k; }).length; - }; - - /** - * It will ONLY have our own jsonql specific implement check - * @param {object} result the server return result - * @return {object} this will just throw error - */ - function clientErrorsHandler(result) { - if (isObjectHasKey$1(result, 'error')) { - var error = result.error; - var className = error.className; - var name = error.name; - var errorName = className || name; - // just throw the whole thing back - var msg = error.message || NO_ERROR_MSG; - var detail = error.detail || error; - if (errorName && errors[errorName]) { - throw new errors[className](msg, detail) - } - throw new JsonqlError$1(msg, detail) - } - // pass through to the next - return result; - } - - /** - * this will put into generator call at the very end and catch - * the error throw from inside then throw again - * this is necessary because we split calls inside and the throw - * will not reach the actual client unless we do it this way - * @param {object} e Error - * @return {void} just throw - */ - function finalCatch(e) { - // this is a hack to get around the validateAsync not actually throw error - // instead it just rejected it with the array of failed parameters - if (Array.isArray(e)) { - // if we want the message then I will have to create yet another function - // to wrap this function to provide the name prop - throw new JsonqlValidationError('', e) - } - var msg = e.message || NO_ERROR_MSG; - var detail = e.detail || e; - // @BUG the instance of not always work for some reason! - // need to figure out a better way to find out the type of the error - switch (true) { - case e instanceof Jsonql406Error: - throw new Jsonql406Error(msg, detail) - case e instanceof Jsonql500Error: - throw new Jsonql500Error(msg, detail) - case e instanceof JsonqlForbiddenError: - throw new JsonqlForbiddenError(msg, detail) - case e instanceof JsonqlAuthorisationError: - throw new JsonqlAuthorisationError(msg, detail) - case e instanceof JsonqlContractAuthError: - throw new JsonqlContractAuthError(msg, detail) - case e instanceof JsonqlResolverAppError: - throw new JsonqlResolverAppError(msg, detail) - case e instanceof JsonqlResolverNotFoundError: - throw new JsonqlResolverNotFoundError(msg, detail) - case e instanceof JsonqlEnumError: - throw new JsonqlEnumError(msg, detail) - case e instanceof JsonqlTypeError: - throw new JsonqlTypeError(msg, detail) - case e instanceof JsonqlCheckerError: - throw new JsonqlCheckerError(msg, detail) - case e instanceof JsonqlValidationError: - throw new JsonqlValidationError(msg, detail) - case e instanceof JsonqlServerError: - throw new JsonqlServerError(msg, detail) - default: - throw new JsonqlError(msg, detail) - } - } - - // split the contract into the node side and the generic side - /** - * Check if the json is a contract file or not - * @param {object} contract json object - * @return {boolean} true - */ - function checkIsContract(contract) { - return isPlainObject(contract) - && ( - isObjectHasKey(contract, QUERY_NAME) - || isObjectHasKey(contract, MUTATION_NAME) - || isObjectHasKey(contract, SOCKET_NAME) - ) - } - - /** - * Wrapper method that check if it's contract then return the contract or false - * @param {object} contract the object to check - * @return {boolean | object} false when it's not - */ - function isContract(contract) { - return checkIsContract(contract) ? contract : false; - } - - /** - * generate a 32bit hash based on the function.toString() - * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery - * @param {string} s the converted to string function - * @return {string} the hashed function string - */ - function hashCode(s) { - return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) - } - - // take only the module part which is what we use here - /** - * @param {object} jsonqlInstance the init instance of jsonql client - * @param {object} contract the static contract - * @return {object} contract may be from server - */ - var getContractFromConfig = function(jsonqlInstance, contract) { - if ( contract === void 0 ) contract = {}; - - if (isContract(contract)) { - return Promise.resolve(contract) - } - return jsonqlInstance.getContract() - }; - // wrapper method to make sure it's a string - var hashCode$1 = function (str) { return hashCode(str) + ''; }; - var USERDATA_TABLE = 'userdata'; - var CLS_LOCAL_STORE_NAME = 'localStore'; - var CLS_SESS_STORE_NAME = 'sessionStore'; - var CLS_CONTRACT_NAME = 'contract'; - var CLS_PROFILE_IDX = 'prof_idx'; - var LOG_ERROR_SWITCH = '__error__'; - var ZERO_IDX = 0; - - /** - * The code was extracted from: - * https://github.com/davidchambers/Base64.js - */ - - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - - function InvalidCharacterError(message) { - this.message = message; - } - - InvalidCharacterError.prototype = new Error(); - InvalidCharacterError.prototype.name = 'InvalidCharacterError'; - - function polyfill (input) { - var str = String(input).replace(/=+$/, ''); - if (str.length % 4 == 1) { - throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); - } - for ( - // initialize result and counters - var bc = 0, bs, buffer, idx = 0, output = ''; - // get next character - buffer = str.charAt(idx++); - // character found in table? initialize bit storage and add its ascii value; - ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, - // and if not first of each 4 characters, - // convert the first 8 bits to one ascii character - bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 - ) { - // try to find character in table (0-63, not found => -1) - buffer = chars.indexOf(buffer); - } - return output; - } - - - var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; - - function b64DecodeUnicode(str) { - return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { - var code = p.charCodeAt(0).toString(16).toUpperCase(); - if (code.length < 2) { - code = '0' + code; - } - return '%' + code; - })); - } - - var base64_url_decode = function(str) { - var output = str.replace(/-/g, "+").replace(/_/g, "/"); - switch (output.length % 4) { - case 0: - break; - case 2: - output += "=="; - break; - case 3: - output += "="; - break; - default: - throw "Illegal base64url string!"; - } - - try{ - return b64DecodeUnicode(output); - } catch (err) { - return atob(output); - } - }; - - function InvalidTokenError(message) { - this.message = message; - } - - InvalidTokenError.prototype = new Error(); - InvalidTokenError.prototype.name = 'InvalidTokenError'; - - var lib = function (token,options) { - if (typeof token !== 'string') { - throw new InvalidTokenError('Invalid token specified'); - } - - options = options || {}; - var pos = options.header === true ? 0 : 1; - try { - return JSON.parse(base64_url_decode(token.split('.')[pos])); - } catch (e) { - throw new InvalidTokenError('Invalid token specified: ' + e.message); - } - }; - - var InvalidTokenError_1 = InvalidTokenError; - lib.InvalidTokenError = InvalidTokenError_1; - - /** `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; - }; - - // when the user is login with the jwt - - 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 = lib(token); - return validate(t) - } - throw new JsonqlError('Token must be a string!') - } - - /** - * Check several parameter that there is something in the param - * @param {*} param input - * @return {boolean} - */ - var isNotEmpty = function (a) { - if (isArray(a)) { - return true; - } - return a !== undefined && a !== null && trim(a) !== ''; - }; - - /** `Object#toString` result references. */ - var numberTag = '[object Number]'; - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - // validator numbers - /** - * @2015-05-04 found a problem if the value is a number like string - * it will pass, so add a chck if it's string before we pass to next - * @param {number} value expected value - * @return {boolean} true if OK - */ - var checkIsNumber = function(value) { - return isString(value) ? false : !isNaN( parseFloat(value) ) - }; - - // check for boolean - - /** - * @param {boolean} value expected - * @return {boolean} true if OK - */ - var checkIsBoolean = function(value) { - return value !== null && value !== undefined && typeof value === 'boolean' - }; - - // validate any thing only check if there is something - - /** - * @param {*} value the value - * @param {boolean} [checkNull=true] strict check if there is null value - * @return {boolean} true is OK - */ - var checkIsAny = function(value, checkNull) { - if ( checkNull === void 0 ) checkNull = true; - - if (value !== undefined && value !== '' && trim(value) !== '') { - if (checkNull === false || (checkNull === true && value !== null)) { - return true; - } - } - return false; - }; - - // Good practice rule - No magic number - - var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; - var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; - var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; - // @TODO the jsdoc return array. and we should also allow array syntax - var DEFAULT_TYPE$1 = DEFAULT_TYPE; - var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; - var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; - - var TYPE_KEY$1 = TYPE_KEY; - var OPTIONAL_KEY$1 = OPTIONAL_KEY; - var ENUM_KEY$1 = ENUM_KEY; - var ARGS_KEY$1 = ARGS_KEY; - var CHECKER_KEY$1 = CHECKER_KEY; - var ALIAS_KEY$1 = ALIAS_KEY; - - var ARRAY_TYPE$1 = ARRAY_TYPE; - var OBJECT_TYPE$1 = OBJECT_TYPE; - var STRING_TYPE$1 = STRING_TYPE; - var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; - var NUMBER_TYPE$1 = NUMBER_TYPE; - var KEY_WORD$1 = KEY_WORD; - var OR_SEPERATOR$1 = OR_SEPERATOR; - - // not actually in use - // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; - - // primitive types - - /** - * this is a wrapper method to call different one based on their type - * @param {string} type to check - * @return {function} a function to handle the type - */ - var combineFn = function(type) { - switch (type) { - case NUMBER_TYPE$1: - return checkIsNumber; - case STRING_TYPE$1: - return checkIsString; - case BOOLEAN_TYPE$1: - return checkIsBoolean; - default: - return checkIsAny; - } - }; - - // validate array type - - /** - * @param {array} value expected - * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well - * @return {boolean} true if OK - */ - var checkIsArray = function(value, type) { - if ( type === void 0 ) type=''; - - if (isArray(value)) { - if (type === '' || trim(type)==='') { - return true; - } - // we test it in reverse - // @TODO if the type is an array (OR) then what? - // we need to take into account this could be an array - var c = value.filter(function (v) { return !combineFn(type)(v); }); - return !(c.length > 0) - } - return false; - }; - - /** - * check if it matches the array. pattern - * @param {string} type - * @return {boolean|array} false means NO, always return array - */ - var isArrayLike = function(type) { - // @TODO could that have something like array<> instead of array.<>? missing the dot? - // because type script is Array without the dot - if (type.indexOf(ARRAY_TYPE_LFT$1) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { - var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); - if (_type.indexOf(OR_SEPERATOR$1)) { - return _type.split(OR_SEPERATOR$1) - } - return [_type] - } - return false; - }; - - /** - * we might encounter something like array. then we need to take it apart - * @param {object} p the prepared object for processing - * @param {string|array} type the type came from - * @return {boolean} for the filter to operate on - */ - var arrayTypeHandler = function(p, type) { - var arg = p.arg; - // need a special case to handle the OR type - // we need to test the args instead of the type(s) - if (type.length > 1) { - return !arg.filter(function (v) { return ( - !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) - ); }).length; - } - // type is array so this will be or! - return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length; - }; - - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]'; - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** Used for built-in method references. */ - var objectProto$3 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - - /** Built-in value references. */ - var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER$1 = 9007199254740991; - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; - } - - /** `Object#toString` result references. */ - var argsTag$1 = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - mapTag = '[object Map]', - numberTag$1 = '[object Number]', - objectTag$1 = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag$1 = '[object String]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag$1] = - typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag$1] = - typedArrayTags[weakMapTag] = false; - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - - /** Detect free variable `exports`. */ - var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports$1 && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - - /** Used for built-in method references. */ - var objectProto$4 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$3 = objectProto$4.hasOwnProperty; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$3.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$5 = Object.prototype; - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; - - return value === proto; - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeKeys = overArg(Object.keys, Object); - - /** Used for built-in method references. */ - var objectProto$6 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$4 = objectProto$6.hasOwnProperty; - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$4.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** `Object#toString` result references. */ - var asyncTag = '[object AsyncFunction]', - funcTag$1 = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike$1(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype; - - /** Built-in value references. */ - var splice = arrayProto.splice; - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** Used for built-in method references. */ - var funcProto$1 = Function.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$1 = funcProto$1.toString; - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString$1.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used for built-in method references. */ - var funcProto$2 = Function.prototype, - objectProto$7 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$2 = funcProto$2.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$5 = objectProto$7.hasOwnProperty; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString$2.call(hasOwnProperty$5).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /* Built-in method references that are verified to be native. */ - var Map$1 = getNative(root, 'Map'); - - /* Built-in method references that are verified to be native. */ - var nativeCreate = getNative(Object, 'create'); - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used for built-in method references. */ - var objectProto$8 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$6 = objectProto$8.hasOwnProperty; - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty$6.call(data, key) ? data[key] : undefined; - } - - /** Used for built-in method references. */ - var objectProto$9 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$7 = objectProto$9.hasOwnProperty; - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key); - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; - return this; - } - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map$1 || ListCache), - 'string': new Hash - }; - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; - - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED$2); - return this; - } - - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } - - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } - - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } - - /** Built-in value references. */ - var Uint8Array$1 = root.Uint8Array; - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$1 = 1, - COMPARE_UNORDERED_FLAG$1 = 2; - - /** `Object#toString` result references. */ - var boolTag$1 = '[object Boolean]', - dateTag$1 = '[object Date]', - errorTag$1 = '[object Error]', - mapTag$1 = '[object Map]', - numberTag$2 = '[object Number]', - regexpTag$1 = '[object RegExp]', - setTag$1 = '[object Set]', - stringTag$2 = '[object String]', - symbolTag$1 = '[object Symbol]'; - - var arrayBufferTag$1 = '[object ArrayBuffer]', - dataViewTag$1 = '[object DataView]'; - - /** Used to convert symbols to primitives and strings. */ - var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined, - symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag$1: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag$1: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array$1(object), new Uint8Array$1(other))) { - return false; - } - return true; - - case boolTag$1: - case dateTag$1: - case numberTag$2: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag$1: - return object.name == other.name && object.message == other.message; - - case regexpTag$1: - case stringTag$2: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag$1: - var convert = mapToArray; - - case setTag$1: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG$1; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag$1: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** Used for built-in method references. */ - var objectProto$a = Object.prototype; - - /** Built-in value references. */ - var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable$1.call(object, symbol); - }); - }; - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$2 = 1; - - /** Used for built-in method references. */ - var objectProto$b = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$8 = objectProto$b.hasOwnProperty; - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) { - return false; - } - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'); - - /* Built-in method references that are verified to be native. */ - var Promise$1 = getNative(root, 'Promise'); - - /* Built-in method references that are verified to be native. */ - var Set$1 = getNative(root, 'Set'); - - /* Built-in method references that are verified to be native. */ - var WeakMap$1 = getNative(root, 'WeakMap'); - - /** `Object#toString` result references. */ - var mapTag$2 = '[object Map]', - objectTag$2 = '[object Object]', - promiseTag = '[object Promise]', - setTag$2 = '[object Set]', - weakMapTag$1 = '[object WeakMap]'; - - var dataViewTag$2 = '[object DataView]'; - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map$1), - promiseCtorString = toSource(Promise$1), - setCtorString = toSource(Set$1), - weakMapCtorString = toSource(WeakMap$1); - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$2) || - (Map$1 && getTag(new Map$1) != mapTag$2) || - (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || - (Set$1 && getTag(new Set$1) != setTag$2) || - (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag$2 ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag$2; - case mapCtorString: return mapTag$2; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag$2; - case weakMapCtorString: return weakMapTag$1; - } - } - return result; - }; - } - - var getTag$1 = getTag; - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$3 = 1; - - /** `Object#toString` result references. */ - var argsTag$2 = '[object Arguments]', - arrayTag$1 = '[object Array]', - objectTag$3 = '[object Object]'; - - /** Used for built-in method references. */ - var objectProto$c = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$9 = objectProto$c.hasOwnProperty; - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag$1 : getTag$1(object), - othTag = othIsArr ? arrayTag$1 : getTag$1(other); - - objTag = objTag == argsTag$2 ? objectTag$3 : objTag; - othTag = othTag == argsTag$2 ? objectTag$3 : othTag; - - var objIsObj = objTag == objectTag$3, - othIsObj = othTag == objectTag$3, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { - var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$4 = 1, - COMPARE_UNORDERED_FLAG$2 = 2; - - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } - - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - - /** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } - - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } - - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /** Error message constants. */ - var FUNC_ERROR_TEXT = 'Expected a function'; - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** Used to match property names within property paths. */ - var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** Used as references for various `Number` constants. */ - var INFINITY$1 = 1 / 0; - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; - } - - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$5 = 1, - COMPARE_UNORDERED_FLAG$3 = 2; - - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); - }; - } - - /** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ - function identity(value) { - return value; - } - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - - /** - * Creates a function that returns the value at `path` of a given object. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - * @example - * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; - * - * _.map(objects, _.property('a.b')); - * // => [2, 1] - * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] - */ - function property(path) { - return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); - } - - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } - - // validate object type - /** - * @TODO if provide with the keys then we need to check if the key:value type as well - * @param {object} value expected - * @param {array} [keys=null] if it has the keys array to compare as well - * @return {boolean} true if OK - */ - var checkIsObject = function(value, keys) { - if ( keys === void 0 ) keys=null; - - if (isPlainObject(value)) { - if (!keys) { - return true; - } - if (checkIsArray(keys)) { - // please note we DON'T care if some is optional - // plese refer to the contract.json for the keys - return !keys.filter(function (key) { - var _value = value[key.name]; - return !(key.type.length > key.type.filter(function (type) { - var tmp; - if (_value !== undefined) { - if ((tmp = isArrayLike(type)) !== false) { - return !arrayTypeHandler({arg: _value}, tmp) - // return tmp.filter(t => !checkIsArray(_value, t)).length; - // @TODO there might be an object within an object with keys as well :S - } - return !combineFn(type)(_value) - } - return true; - }).length) - }).length; - } - } - return false; - }; - - /** - * fold this into it's own function to handler different object type - * @param {object} p the prepared object for process - * @return {boolean} - */ - var objectTypeHandler = function(p) { - var arg = p.arg; - var param = p.param; - var _args = [arg]; - if (Array.isArray(param.keys) && param.keys.length) { - _args.push(param.keys); - } - // just simple check - return Reflect.apply(checkIsObject, null, _args) - }; - - // move the index.js code here that make more sense to find where things are - // import debug from 'debug' - // const debugFn = debug('jsonql-params-validator:validator') - // also export this for use in other places - - /** - * We need to handle those optional parameter without a default value - * @param {object} params from contract.json - * @return {boolean} for filter operation false is actually OK - */ - var optionalHandler = function( params ) { - var arg = params.arg; - var param = params.param; - if (isNotEmpty(arg)) { - // debug('call optional handler', arg, params); - // loop through the type in param - return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } - ).length) - } - return false; - }; - - /** - * actually picking the validator - * @param {*} type for checking - * @param {*} value for checking - * @return {boolean} true on OK - */ - var validateHandler = function(type, value) { - var tmp; - switch (true) { - case type === OBJECT_TYPE$1: - // debugFn('call OBJECT_TYPE') - return !objectTypeHandler(value) - case type === ARRAY_TYPE$1: - // debugFn('call ARRAY_TYPE') - return !checkIsArray(value.arg) - // @TODO when the type is not present, it always fall through here - // so we need to find a way to actually pre-check the type first - // AKA check the contract.json map before running here - case (tmp = isArrayLike(type)) !== false: - // debugFn('call ARRAY_LIKE: %O', value) - return !arrayTypeHandler(value, tmp) - default: - return !combineFn(type)(value.arg) - } - }; - - /** - * it get too longer to fit in one line so break it out from the fn below - * @param {*} arg value - * @param {object} param config - * @return {*} value or apply default value - */ - var getOptionalValue = function(arg, param) { - if (arg !== undefined) { - return arg; - } - return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null) - }; - - /** - * padding the arguments with defaultValue if the arguments did not provide the value - * this will be the name export - * @param {array} args normalized arguments - * @param {array} params from contract.json - * @return {array} merge the two together - */ - var normalizeArgs = function(args, params) { - // first we should check if this call require a validation at all - // there will be situation where the function doesn't need args and params - if (!checkIsArray(params)) { - // debugFn('params value', params) - throw new JsonqlError(PARAMS_NOT_ARRAY_ERR) - } - if (params.length === 0) { - return []; - } - if (!checkIsArray(args)) { - throw new JsonqlError(ARGS_NOT_ARRAY_ERR) - } - // debugFn(args, params); - // fall through switch - switch(true) { - case args.length == params.length: // standard - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, - param: params[i] - } - ); }) - case params[0].variable === true: // using spread syntax - var type = params[0].type; - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, // keep the index for reference - param: params[i] || { type: type, name: '_' } - } - ); }) - // with optional defaultValue parameters - case args.length < params.length: - return params.map(function (param, i) { return ( - { - param: param, - index: i, - arg: getOptionalValue(args[i], param), - optional: param.optional || false - } - ); }) - // this one pass more than it should have anything after the args.length will be cast as any type - case args.length > params.length: - var ctn = params.length; - // this happens when we have those array. type - var _type = [ DEFAULT_TYPE$1 ]; - // we only looking at the first one, this might be a @BUG - /* - if ((tmp = isArrayLike(params[0].type[0])) !== false) { - _type = tmp; - } */ - // if we use the params as guide then the rest will get throw out - // which is not what we want, instead, anything without the param - // will get a any type and optional flag - return args.map(function (arg, i) { - var optional = i >= ctn ? true : !!params[i].optional; - var param = params[i] || { type: _type, name: ("_" + i) }; - return { - arg: optional ? getOptionalValue(arg, param) : arg, - index: i, - param: param, - optional: optional - } - }) - // @TODO find out if there is more cases not cover - default: // this should never happen - // debugFn('args', args) - // debugFn('params', params) - // this is unknown therefore we just throw it! - throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) - } - }; - - // what we want is after the validaton we also get the normalized result - // which is with the optional property if the argument didn't provide it - /** - * process the array of params back to their arguments - * @param {array} result the params result - * @return {array} arguments - */ - var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; - - /** - * validator main interface - * @param {array} args the arguments pass to the method call - * @param {array} params from the contract for that method - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {array} empty array on success, or failed parameter and reasons - */ - var validateSync = function(args, params, withResult) { - var obj; - - if ( withResult === void 0 ) withResult = false; - var cleanArgs = normalizeArgs(args, params); - var checkResult = cleanArgs.filter(function (p) { - // v1.4.4 this fixed the problem, the root level optional is from the last fn - if (p.optional === true || p.param.optional === true) { - return optionalHandler(p) - } - // because array of types means OR so if one pass means pass - return !(p.param.type.length > p.param.type.filter( - function (type) { return validateHandler(type, p); } - ).length) - }); - // using the same convention we been using all this time - return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) - }; - - /** - * A wrapper method that return promise - * @param {array} args arguments - * @param {array} params from contract.json - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {object} promise.then or catch - */ - var validateAsync = function(args, params, withResult) { - if ( withResult === void 0 ) withResult = false; - - return new Promise(function (resolver, rejecter) { - var result = validateSync(args, params, withResult); - if (withResult) { - return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) - : resolver(result[DATA_KEY]) - } - // the different is just in the then or catch phrase - return result.length ? rejecter(result) : resolver([]) - }) - }; - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** Detect free variable `exports`. */ - var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; - - /** Built-in value references. */ - var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, - allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** Built-in value references. */ - var objectCreate = Object.create; - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike$1(value); - } - - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; - } - - /** Used for built-in method references. */ - var objectProto$d = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$a = objectProto$d.hasOwnProperty; - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$a.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$e = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$b = objectProto$e.hasOwnProperty; - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty$b.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn(object) { - return isArrayLike$1(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } - - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeMax = Math.max; - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ - function constant(value) { - return function() { - return value; - }; - } - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeNow = Date.now; - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike$1(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - - /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; - } - - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; - } - - /** Error message constants. */ - var FUNC_ERROR_TEXT$1 = 'Expected a function'; - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT$1); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols$1 = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = baseIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } - - /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ - function omitBy(object, predicate) { - return pickBy(object, negate(baseIteratee(predicate))); - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } - - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ - function findKey(object, predicate) { - return baseFindKey(object, baseIteratee(predicate), baseForOwn); - } - - /** - * @param {array} arr Array for check - * @param {*} value target - * @return {boolean} true on successs - */ - var isInArray = function(arr, value) { - return !!arr.filter(function (a) { return a === value; }).length; - }; - - var isObjectHasKey$2 = function(obj, key) { - var keys = Object.keys(obj); - return isInArray(keys, key) - }; - - // just not to make my head hurt - var isEmpty = function (value) { return !isNotEmpty(value); }; - - /** - * Map the alias to their key then grab their value over - * @param {object} config the user supplied config - * @param {object} appProps the default option map - * @return {object} the config keys replaced with the appProps key by the ALIAS - */ - function mapAliasConfigKeys(config, appProps) { - // need to do two steps - // 1. take key with alias key - var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$1]; } ); - if (isEqual(aliasMap, {})) { - return config; - } - return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) - } - - /** - * We only want to run the valdiation against the config (user supplied) value - * but keep the defaultOptions untouch - * @param {object} config configuraton supplied by user - * @param {object} appProps the default options map - * @return {object} the pristine values that will add back to the final output - */ - function preservePristineValues(config, appProps) { - // @BUG this will filter out those that is alias key - // we need to first map the alias keys back to their full key - var _config = mapAliasConfigKeys(config, appProps); - // take the default value out - var pristineValues = mapValues( - omitBy(appProps, function (value, key) { return isObjectHasKey$2(_config, key); }), - function (value) { return value.args; } - ); - // for testing the value - var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !isObjectHasKey$2(_config, key); }); - // output - return { - pristineValues: pristineValues, - checkAgainstAppProps: checkAgainstAppProps, - config: _config // passing this correct values back - } - } - - /** - * This will take the value that is ONLY need to check - * @param {object} config that one - * @param {object} props map for creating checking - * @return {object} put that arg into the args - */ - function processConfigAction(config, props) { - // debugFn('processConfigAction', props) - // v.1.2.0 add checking if its mark optional and the value is empty then pass - return mapValues(props, function (value, key) { - var obj, obj$1; - - return ( - config[key] === undefined || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) - ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) - : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) - ); - } - ) - } - - /** - * Quick transform - * @TODO we should only validate those that is pass from the config - * and pass through those values that is from the defaultOptions - * @param {object} opts that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ - function prepareArgsForValidation(opts, appProps) { - var ref = preservePristineValues(opts, appProps); - var config = ref.config; - var pristineValues = ref.pristineValues; - var checkAgainstAppProps = ref.checkAgainstAppProps; - // output - return [ - processConfigAction(config, checkAgainstAppProps), - pristineValues - ] - } - - // breaking the whole thing up to see what cause the multiple calls issue - - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:options:validation') - - /** - * just make sure it returns an array to use - * @param {*} arg input - * @return {array} output - */ - var toArray$1 = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; - - /** - * DIY in array - * @param {array} arr to check against - * @param {*} value to check - * @return {boolean} true on OK - */ - var inArray$1 = function (arr, value) { return ( - !!arr.filter(function (v) { return v === value; }).length - ); }; - - /** - * break out to make the code easier to read - * @param {object} value to process - * @param {function} cb the validateSync - * @return {array} empty on success - */ - function validateHandler$1(value, cb) { - var obj; - - // cb is the validateSync methods - var args = [ - [ value[ARGS_KEY$1] ], - [( obj = {}, obj[TYPE_KEY$1] = toArray$1(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] - ]; - // debugFn('validateHandler', args) - return Reflect.apply(cb, null, args) - } - - /** - * Check against the enum value if it's provided - * @param {*} value to check - * @param {*} enumv to check against if it's not false - * @return {boolean} true on OK - */ - var enumHandler = function (value, enumv) { - if (checkIsArray(enumv)) { - return inArray$1(enumv, value) - } - return true; - }; - - /** - * Allow passing a function to check the value - * There might be a problem here if the function is incorrect - * and that will makes it hard to debug what is going on inside - * @TODO there could be a few feature add to this one under different circumstance - * @param {*} value to check - * @param {function} checker for checking - */ - var checkerHandler = function (value, checker) { - try { - return isFunction(checker) ? checker.apply(null, [value]) : false; - } catch (e) { - return false; - } - }; - - /** - * Taken out from the runValidaton this only validate the required values - * @param {array} args from the config2argsAction - * @param {function} cb validateSync - * @return {array} of configuration values - */ - function runValidationAction(cb) { - return function (value, key) { - // debugFn('runValidationAction', key, value) - if (value[KEY_WORD$1]) { - return value[ARGS_KEY$1] - } - var check = validateHandler$1(value, cb); - if (check.length) { - // log('runValidationAction', key, value) - throw new JsonqlTypeError(key, check) - } - if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { - // log(ENUM_KEY, value[ENUM_KEY]) - throw new JsonqlEnumError(key) - } - if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { - // log(CHECKER_KEY, value[CHECKER_KEY]) - throw new JsonqlCheckerError(key) - } - return value[ARGS_KEY$1] - } - } - - /** - * @param {object} args from the config2argsAction - * @param {function} cb validateSync - * @return {object} of configuration values - */ - function runValidation(args, cb) { - var argsForValidate = args[0]; - var pristineValues = args[1]; - // turn the thing into an array and see what happen here - // debugFn('_args', argsForValidate) - var result = mapValues(argsForValidate, runValidationAction(cb)); - return merge(result, pristineValues) - } - - /// this is port back from the client to share across all projects - - // import debug from 'debug' - // const debugFn = debug('jsonql-params-validator:check-options-async') - - /** - * Quick transform - * @param {object} config that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ - var configToArgs = function (config, appProps) { - return Promise.resolve( - prepareArgsForValidation(config, appProps) - ) - }; - - /** - * @param {object} config user provide configuration option - * @param {object} appProps mutation configuration options - * @param {object} constProps the immutable configuration options - * @param {function} cb the validateSync method - * @return {object} Promise resolve merge config object - */ - function checkOptionsAsync(config, appProps, constProps, cb) { - if ( config === void 0 ) config = {}; - - return configToArgs(config, appProps) - .then(function (args1) { return runValidation(args1, cb); }) - // next if every thing good then pass to final merging - .then(function (args2) { return merge({}, args2, constProps); }) - } - - // create function to construct the config entry so we don't need to keep building object - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:construct-config'); - /** - * @param {*} args value - * @param {string} type for value - * @param {boolean} [optional=false] - * @param {boolean|array} [enumv=false] - * @param {boolean|function} [checker=false] - * @return {object} config entry - */ - function constructConfig(args, type, optional, enumv, checker, alias) { - if ( optional === void 0 ) optional=false; - if ( enumv === void 0 ) enumv=false; - if ( checker === void 0 ) checker=false; - if ( alias === void 0 ) alias=false; - - var base = {}; - base[ARGS_KEY] = args; - base[TYPE_KEY] = type; - if (optional === true) { - base[OPTIONAL_KEY] = true; - } - if (checkIsArray(enumv)) { - base[ENUM_KEY] = enumv; - } - if (isFunction(checker)) { - base[CHECKER_KEY] = checker; - } - if (isString(alias)) { - base[ALIAS_KEY] = alias; - } - return base; - } - - // export also create wrapper methods - - /** - * This has a different interface - * @param {*} value to supply - * @param {string|array} type for checking - * @param {object} params to map against the config check - * @param {array} params.enumv NOT enum - * @param {boolean} params.optional false then nothing - * @param {function} params.checker need more work on this one later - * @param {string} params.alias mostly for cmd - */ - var createConfig = function (value, type, params) { - if ( params === void 0 ) params = {}; - - // Note the enumv not ENUM - // const { enumv, optional, checker, alias } = params; - // let args = [value, type, optional, enumv, checker, alias]; - var o = params[OPTIONAL_KEY]; - var e = params[ENUM_KEY]; - var c = params[CHECKER_KEY]; - var a = params[ALIAS_KEY]; - return constructConfig.apply(null, [value, type, o, e, c, a]) - }; - - /** - * We recreate the method here to avoid the circlar import - * @param {object} config user supply configuration - * @param {object} appProps mutation options - * @param {object} [constantProps={}] optional: immutation options - * @return {object} all checked configuration - */ - var checkConfigAsync = function(validateSync) { - return function(config, appProps, constantProps) { - if ( constantProps === void 0 ) constantProps= {}; - - return checkOptionsAsync(config, appProps, constantProps, validateSync) - } - }; - - // export - var isString$1 = checkIsString; - var isNumber$1 = checkIsNumber; - var validateAsync$1 = validateAsync; - - var createConfig$1 = createConfig; - - var checkConfigAsync$1 = checkConfigAsync(validateSync); - - var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; - - var appProps = { - algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), - expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), - notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), - audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), - subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), - issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), - noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), - header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), - keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), - mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) - }; - - /** - * @param {boolean} sec return in second or not - * @return {number} timestamp - */ - var timestamp$1 = function (sec) { - if ( sec === void 0 ) sec = false; - - var time = Date.now(); - return sec ? Math.floor( time / 1000 ) : time; - }; - - var assign = make_assign(); - var create = make_create(); - var trim$1 = make_trim(); - var Global = (typeof window !== 'undefined' ? window : commonjsGlobal); - - var util = { - assign: assign, - create: create, - trim: trim$1, - bind: bind, - slice: slice, - each: each, - map: map, - pluck: pluck, - isList: isList, - isFunction: isFunction$1, - isObject: isObject$1, - Global: Global - }; - - function make_assign() { - if (Object.assign) { - return Object.assign - } else { - return function shimAssign(obj, props1, props2, etc) { - var arguments$1 = arguments; - - for (var i = 1; i < arguments.length; i++) { - each(Object(arguments$1[i]), function(val, key) { - obj[key] = val; - }); - } - return obj - } - } - } - - function make_create() { - if (Object.create) { - return function create(obj, assignProps1, assignProps2, etc) { - var assignArgsList = slice(arguments, 1); - return assign.apply(this, [Object.create(obj)].concat(assignArgsList)) - } - } else { - function F() {} // eslint-disable-line no-inner-declarations - return function create(obj, assignProps1, assignProps2, etc) { - var assignArgsList = slice(arguments, 1); - F.prototype = obj; - return assign.apply(this, [new F()].concat(assignArgsList)) - } - } - } - - function make_trim() { - if (String.prototype.trim) { - return function trim(str) { - return String.prototype.trim.call(str) - } - } else { - return function trim(str) { - return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '') - } - } - } - - function bind(obj, fn) { - return function() { - return fn.apply(obj, Array.prototype.slice.call(arguments, 0)) - } - } - - function slice(arr, index) { - return Array.prototype.slice.call(arr, index || 0) - } - - function each(obj, fn) { - pluck(obj, function(val, key) { - fn(val, key); - return false - }); - } - - function map(obj, fn) { - var res = (isList(obj) ? [] : {}); - pluck(obj, function(v, k) { - res[k] = fn(v, k); - return false - }); - return res - } - - function pluck(obj, fn) { - if (isList(obj)) { - for (var i=0; i= 0; i--) { - var key = localStorage().key(i); - fn(read(key), key); - } - } - - function remove(key) { - return localStorage().removeItem(key) - } - - function clearAll() { - return localStorage().clear() - } - - // cookieStorage is useful Safari private browser mode, where localStorage - // doesn't work but cookies do. This implementation is adopted from - // https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage - - - var Global$2 = util.Global; - var trim$2 = util.trim; - - var cookieStorage = { - name: 'cookieStorage', - read: read$1, - write: write$1, - each: each$3, - remove: remove$1, - clearAll: clearAll$1, - }; - - var doc = Global$2.document; - - function read$1(key) { - if (!key || !_has(key)) { return null } - var regexpStr = "(?:^|.*;\\s*)" + - escape(key).replace(/[\-\.\+\*]/g, "\\$&") + - "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"; - return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")) - } - - function each$3(callback) { - var cookies = doc.cookie.split(/; ?/g); - for (var i = cookies.length - 1; i >= 0; i--) { - if (!trim$2(cookies[i])) { - continue - } - var kvp = cookies[i].split('='); - var key = unescape(kvp[0]); - var val = unescape(kvp[1]); - callback(val, key); - } - } - - function write$1(key, data) { - if(!key) { return } - doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; - } - - function remove$1(key) { - if (!key || !_has(key)) { - return - } - doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; - } - - function clearAll$1() { - each$3(function(_, key) { - remove$1(key); - }); - } - - function _has(key) { - return (new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie) - } - - var defaults = defaultsPlugin; - - function defaultsPlugin() { - var defaultValues = {}; - - return { - defaults: defaults, - get: get - } - - function defaults(_, values) { - defaultValues = values; - } - - function get(super_fn, key) { - var val = super_fn(); - return (val !== undefined ? val : defaultValues[key]) - } - } - - var bind$2 = util.bind; - var each$4 = util.each; - var create$2 = util.create; - var slice$2 = util.slice; - - var events = eventsPlugin; - - function eventsPlugin() { - var pubsub = _newPubSub(); - - return { - watch: watch, - unwatch: unwatch, - once: once, - - set: set, - remove: remove, - clearAll: clearAll - } - - // new pubsub functions - function watch(_, key, listener) { - return pubsub.on(key, bind$2(this, listener)) - } - function unwatch(_, subId) { - pubsub.off(subId); - } - function once(_, key, listener) { - pubsub.once(key, bind$2(this, listener)); - } - - // overwrite function to fire when appropriate - function set(super_fn, key, val) { - var oldVal = this.get(key); - super_fn(); - pubsub.fire(key, val, oldVal); - } - function remove(super_fn, key) { - var oldVal = this.get(key); - super_fn(); - pubsub.fire(key, undefined, oldVal); - } - function clearAll(super_fn) { - var oldVals = {}; - this.each(function(val, key) { - oldVals[key] = val; - }); - super_fn(); - each$4(oldVals, function(oldVal, key) { - pubsub.fire(key, undefined, oldVal); - }); - } - } - - - function _newPubSub() { - return create$2(_pubSubBase, { - _id: 0, - _subSignals: {}, - _subCallbacks: {} - }) - } - - var _pubSubBase = { - _id: null, - _subCallbacks: null, - _subSignals: null, - on: function(signal, callback) { - if (!this._subCallbacks[signal]) { - this._subCallbacks[signal] = {}; - } - this._id += 1; - this._subCallbacks[signal][this._id] = callback; - this._subSignals[this._id] = signal; - return this._id - }, - off: function(subId) { - var signal = this._subSignals[subId]; - delete this._subCallbacks[signal][subId]; - delete this._subSignals[subId]; - }, - once: function(signal, callback) { - var subId = this.on(signal, bind$2(this, function() { - callback.apply(this, arguments); - this.off(subId); - })); - }, - fire: function(signal) { - var args = slice$2(arguments, 1); - each$4(this._subCallbacks[signal], function(callback) { - callback.apply(this, args); - }); - } - }; - - var lzString = createCommonjsModule(function (module) { - /* eslint-disable */ - // Copyright (c) 2013 Pieroxy - // This work is free. You can redistribute it and/or modify it - // under the terms of the WTFPL, Version 2 - // For more information see LICENSE.txt or http://www.wtfpl.net/ - // - // For more information, the home page: - // http://pieroxy.net/blog/pages/lz-string/testing.html - // - // LZ-based compression algorithm, version 1.4.4 - var LZString = (function() { - - // private property - var f = String.fromCharCode; - var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; - var baseReverseDic = {}; - - function getBaseValue(alphabet, character) { - if (!baseReverseDic[alphabet]) { - baseReverseDic[alphabet] = {}; - for (var i=0 ; i>> 8; - buf[i*2+1] = current_value % 256; - } - return buf; - }, - - //decompress from uint8array (UCS-2 big endian format) - decompressFromUint8Array:function (compressed) { - if (compressed===null || compressed===undefined){ - return LZString.decompress(compressed); - } else { - var buf=new Array(compressed.length/2); // 2 bytes per character - for (var i=0, TotalLen=buf.length; i> 1; - } - } else { - value = 1; - for (i=0 ; i> 1; - } - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - delete context_dictionaryToCreate[context_w]; - } else { - value = context_dictionary[context_w]; - for (i=0 ; i> 1; - } - - - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - // Add wc to the dictionary. - context_dictionary[context_wc] = context_dictSize++; - context_w = String(context_c); - } - } - - // Output the code for w. - if (context_w !== "") { - if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) { - if (context_w.charCodeAt(0)<256) { - for (i=0 ; i> 1; - } - } else { - value = 1; - for (i=0 ; i> 1; - } - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - delete context_dictionaryToCreate[context_w]; - } else { - value = context_dictionary[context_w]; - for (i=0 ; i> 1; - } - - - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - } - - // Mark the end of the stream - value = 2; - for (i=0 ; i> 1; - } - - // Flush the last char - while (true) { - context_data_val = (context_data_val << 1); - if (context_data_position == bitsPerChar-1) { - context_data.push(getCharFromInt(context_data_val)); - break; - } - else { context_data_position++; } - } - return context_data.join(''); - }, - - decompress: function (compressed) { - if (compressed == null) { return ""; } - if (compressed == "") { return null; } - return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); }); - }, - - _decompress: function (length, resetValue, getNextValue) { - var dictionary = [], - next, - enlargeIn = 4, - dictSize = 4, - numBits = 3, - entry = "", - result = [], - i, - w, - bits, resb, maxpower, power, - c, - data = {val:getNextValue(0), position:resetValue, index:1}; - - for (i = 0; i < 3; i += 1) { - dictionary[i] = i; - } - - bits = 0; - maxpower = Math.pow(2,2); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - switch (next = bits) { - case 0: - bits = 0; - maxpower = Math.pow(2,8); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - c = f(bits); - break; - case 1: - bits = 0; - maxpower = Math.pow(2,16); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - c = f(bits); - break; - case 2: - return ""; - } - dictionary[3] = c; - w = c; - result.push(c); - while (true) { - if (data.index > length) { - return ""; - } - - bits = 0; - maxpower = Math.pow(2,numBits); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - switch (c = bits) { - case 0: - bits = 0; - maxpower = Math.pow(2,8); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - - dictionary[dictSize++] = f(bits); - c = dictSize-1; - enlargeIn--; - break; - case 1: - bits = 0; - maxpower = Math.pow(2,16); - power=1; - while (power!=maxpower) { - resb = data.val & data.position; - data.position >>= 1; - if (data.position == 0) { - data.position = resetValue; - data.val = getNextValue(data.index++); - } - bits |= (resb>0 ? 1 : 0) * power; - power <<= 1; - } - dictionary[dictSize++] = f(bits); - c = dictSize-1; - enlargeIn--; - break; - case 2: - return result.join(''); - } - - if (enlargeIn == 0) { - enlargeIn = Math.pow(2, numBits); - numBits++; - } - - if (dictionary[c]) { - entry = dictionary[c]; - } else { - if (c === dictSize) { - entry = w + w.charAt(0); - } else { - return null; - } - } - result.push(entry); - - // Add w+entry[0] to the dictionary. - dictionary[dictSize++] = w + entry.charAt(0); - enlargeIn--; - - w = entry; - - if (enlargeIn == 0) { - enlargeIn = Math.pow(2, numBits); - numBits++; - } - - } - } - }; - return LZString; - })(); - - if( module != null ) { - module.exports = LZString; - } - }); - - var compression = compressionPlugin; - - function compressionPlugin() { - return { - get: get, - set: set, - } - - function get(super_fn, key) { - var val = super_fn(key); - if (!val) { return val } - var decompressed = lzString.decompress(val); - // fallback to existing values that are not compressed - return (decompressed == null) ? val : this._deserialize(decompressed) - } - - function set(super_fn, key, val) { - var compressed = lzString.compress(this._serialize(val)); - super_fn(key, compressed); - } - } - - // sort of persist on the user side - - var storages = [localStorage_1, cookieStorage]; - var plugins = [defaults, events, compression]; - - var localStore = storeEngine.createStore(storages, plugins); - - var Global$3 = util.Global; - - var sessionStorage_1 = { - name: 'sessionStorage', - read: read$2, - write: write$2, - each: each$5, - remove: remove$2, - clearAll: clearAll$2 - }; - - function sessionStorage() { - return Global$3.sessionStorage - } - - function read$2(key) { - return sessionStorage().getItem(key) - } - - function write$2(key, data) { - return sessionStorage().setItem(key, data) - } - - function each$5(fn) { - for (var i = sessionStorage().length - 1; i >= 0; i--) { - var key = sessionStorage().key(i); - fn(read$2(key), key); - } - } - - function remove$2(key) { - return sessionStorage().removeItem(key) - } - - function clearAll$2() { - return sessionStorage().clear() - } - - // session store with watch - // @1.5.0 stop using the expired plugin and deal it ourself - // import expiredPlugin from 'store/plugins/expire' - - var storages$1 = [sessionStorage_1, cookieStorage]; - var plugins$1 = [defaults, compression]; - - var sessionStore = storeEngine.createStore(storages$1, plugins$1); - - // export store interface - - // export back the raw version for development purposes - var localStore$1 = localStore; - var sessionStore$1 = sessionStore; - - // ported from jsonql-params-validator - - /** - * @param {*} args arguments to send - *@return {object} formatted payload - */ - var formatPayload = function (args) { - var obj; - - return ( - ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) - ); - }; - - /** - * Get name from the payload (ported back from jsonql-koa) - * @param {*} payload to extract from - * @return {string} name - */ - function getNameFromPayload(payload) { - return Object.keys(payload)[0] - } - - /** - * wrapper method to add the timestamp as well - * @param {string} resolverName - * @param {*} payload - * @return {object} delierable - */ - function createDeliverable(resolverName, payload) { - var obj; - - return ( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME] = [ timestamp$1() ], obj ) - } - - /** - * @param {string} resolverName name of function - * @param {array} [args=[]] from the ...args - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createQuery(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - - if (isString(resolverName) && isArray(args)) { - var payload = formatPayload(args); - if (jsonp === true) { - return payload; - } - return createDeliverable(resolverName, payload) - } - throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) - } - - /** - * @param {string} resolverName name of function - * @param {*} payload to send - * @param {object} [condition={}] for what - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createMutation(resolverName, payload, condition, jsonp) { - if ( condition === void 0 ) condition = {}; - if ( jsonp === void 0 ) jsonp = false; - - var _payload = {}; - _payload[PAYLOAD_PARAM_NAME] = payload; - _payload[CONDITION_PARAM_NAME] = condition; - if (jsonp === true) { - return _payload; - } - if (isString(resolverName)) { - return createDeliverable(resolverName, _payload) - } - throw new JsonqlValidationError("[createMutation] expect resolverName to be string!", { resolverName: resolverName, payload: payload, condition: condition }) - } - - /** - * @return {object} _cb as key with timestamp - */ - var cacheBurst = function () { return ({ _cb: timestamp$1() }); }; - - // break up from node-middleware - - // ported from http-client - - /** - * handle the return data - * @TODO how to handle the return timestamp and calculate the diff? - * @param {object} result return from server - * @return {object} strip the data part out, or if the error is presented - */ - var resultHandler = function (result) { return ( - (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result - ); }; - - // new 1.5.0 - - // this becomes the base class instead of the HttpCls - var StoreClass = function StoreClass(opts) { - this.opts = opts; - // make it a string - this.instanceKey = hashCode$1(this.opts.hostname); - // pass this store for use later - this.localStore = localStore$1; - this.sessionStore = sessionStore$1; - /* - if (this.opts.debugOn) { // reuse this to clear out the data - this.log('clear all stores') - localStore.clearAll() - sessionStore.clearAll() - - localStore.set('TEST', Date.now()) - sessionStore.set('TEST', Date.now()) - } - */ - }; - - var prototypeAccessors = { lset: { configurable: true },lget: { configurable: true },sset: { configurable: true },sget: { configurable: true } }; - // store in local storage id by the instanceKey - // values should be an object so with key so we just merge - // into the existing store without going through the keys - StoreClass.prototype.__setMethod = function __setMethod (storeType, values) { - var obj; - - var store = this[storeType]; - var data = this.__getMethod(storeType); - var skey = this.opts.storageKey; - var ikey = this.instanceKey; - store.set(skey, ( obj = {}, obj[ikey] = data ? merge({}, data, values) : values, obj )); - }; - // return the data id by the instaceKey - StoreClass.prototype.__getMethod = function __getMethod (storeType) { - var store = this[storeType]; - var data = store.get(this.opts.storageKey); - return data ? data[this.instanceKey] : false - }; - // remove from local store id by instanceKey - StoreClass.prototype.__delMethod = function __delMethod (storeType, key) { - var data = this.__getMethod(storeType); - if (data) { - var store = {}; - for (var k in data) { - if (k !== key) { - store[k] = data[k]; - } - } - this.__setMethod(storeType, store); - } - }; - // clear everything by this instanceKey - StoreClass.prototype.__clearMethod = function __clearMethod (storeKey) { - var skey = this.opts.storageKey; - var store = this[storeKey]; - var data = store.get(skey); - if (data) { - var _store = {}; - for (var k in data) { - if (k !== this.instanceKey) { - _store[k] = data[k]; - } - } - store.set(skey, _store); - } - }; - // Alias for different store - prototypeAccessors.lset.set = function (values) { - return this.__setMethod(CLS_LOCAL_STORE_NAME, values) - }; - - prototypeAccessors.lget.get = function () { - return this.__getMethod(CLS_LOCAL_STORE_NAME) - }; - - StoreClass.prototype.ldel = function ldel (key) { - return this.__delMethod(CLS_LOCAL_STORE_NAME, key) - }; - - StoreClass.prototype.lclear = function lclear () { - return this.__clearMethod(CLS_LOCAL_STORE_NAME) - }; - - // store in session store id by the instanceKey - prototypeAccessors.sset.set = function (values) { - // this.log('--- sset ---', values) - return this.__setMethod(CLS_SESS_STORE_NAME, values) - }; - - prototypeAccessors.sget.get = function () { - return this.__getMethod(CLS_SESS_STORE_NAME) - }; - - StoreClass.prototype.sdel = function sdel (key) { - return this.__delMethod(CLS_SESS_STORE_NAME, key) - }; - - StoreClass.prototype.sclear = function sclear () { - return this.__clearMethod(CLS_SESS_STORE_NAME) - }; - - Object.defineProperties( StoreClass.prototype, prototypeAccessors ); - - // base HttpClass - - // extract the one we need - var POST = API_REQUEST_METHODS[0]; - var PUT = API_REQUEST_METHODS[1]; - - var HttpClass = /*@__PURE__*/(function (StoreClass) { - function HttpClass(opts) { - StoreClass.call(this, opts); - // change the way how we init Fly - // flyio now become external depedencies and it makes it easier to switch - // @BUG should we run test to check if we have the windows object? - // this.log(opts) - // this.fly = opts.Fly ? new opts.Fly() : new Fly() - // to a different environment like WeChat mini app - - this.extraHeader = {}; - // @1.2.1 for adding query to the call on the fly - this.extraParams = {}; - // this.log('start up opts', opts); - this.reqInterceptor(); - this.resInterceptor(); - } - - if ( StoreClass ) HttpClass.__proto__ = StoreClass; - HttpClass.prototype = Object.create( StoreClass && StoreClass.prototype ); - HttpClass.prototype.constructor = HttpClass; - - var prototypeAccessors = { headers: { configurable: true } }; - - // set headers for that one call - prototypeAccessors.headers.set = function (header) { - this.extraHeader = header; - }; - - /** - * Create the reusage request method - * @param {object} payload jsonql payload - * @param {object} options extra options add the request - * @param {object} headers extra headers add to the call - * @return {object} the fly request instance - */ - HttpClass.prototype.request = function request (payload, options, headers) { - var obj; - - if ( options === void 0 ) options = {}; - if ( headers === void 0 ) headers = {}; - this.headers = headers; - var params = merge({}, cacheBurst(), this.extraParams); - // @TODO need to add a jsonp url and payload - if (this.opts.enableJsonp) { - var resolverName = getNameFromPayload(payload); - params = merge({}, params, ( obj = {}, obj[JSONP_CALLBACK_NAME] = resolverName, obj )); - payload = payload[resolverName]; - } - // double up the url param and see what happen @TODO remove later - var reqParams = merge({}, { method: POST, params: params }, options); - this.log('request params', reqParams, this.jsonqlEndpoint); - - return this.fly.request(this.jsonqlEndpoint, payload, reqParams) - }; - - /** - * This will replace the create baseRequest method - * - */ - HttpClass.prototype.reqInterceptor = function reqInterceptor () { - var this$1 = this; - - this.fly.interceptors.request.use( - function (req) { - var headers = this$1.getHeaders(); - this$1.log('request interceptor call', headers); - - for (var key in headers) { - req.headers[key] = headers[key]; - } - return req; - } - ); - }; - - // @TODO - HttpClass.prototype.processJsonp = function processJsonp (result) { - return resultHandler(result) - }; - - /** - * This will be replacement of the first then call - * - */ - HttpClass.prototype.resInterceptor = function resInterceptor () { - var this$1 = this; - - var self = this; - var jsonp = self.opts.enableJsonp; - this.fly.interceptors.response.use( - function (res) { - this$1.log('response interceptor call', res); - self.cleanUp(); - // now more processing here - // there is a problem if we throw the result.error here - // the original data is lost, so we need to do what we did before - // deal with that error in the first then instead - var result = isString$1(res.data) ? JSON.parse(res.data) : res.data; - if (jsonp) { - return self.processJsonp(result) - } - return resultHandler(result) - }, - // this get call when it's not 200 - function (err) { - self.cleanUp(); - this$1.log(LOG_ERROR_SWITCH, err); - throw new JsonqlServerError('Server side error', err) - } - ); - }; - - /** - * Get the headers inject into the call - * @return {object} headers - */ - HttpClass.prototype.getHeaders = function getHeaders () { - if (this.opts.enableAuth) { - return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader) - } - return merge({}, DEFAULT_HEADER, this.extraHeader) - }; - - /** - * Post http call operation to clean up things we need - */ - HttpClass.prototype.cleanUp = function cleanUp () { - this.extraHeader = {}; - this.extraParams = {}; - }; - - /** - * GET for contract only - * @return {promise} resolve the contract - */ - HttpClass.prototype.getRemoteContract = function getRemoteContract () { - var this$1 = this; - - if (this.opts.showContractDesc) { - this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM); - } - return this.request({}, {method: 'GET'}, this.contractHeader) - .then(clientErrorsHandler) - .then(function (result) { - this$1.log('get contract result', result); - // when refresh the window the result is different! - // @TODO need to check the Koa side about why is that - // also it should set a flag if we want the description or not - if (result.cache && result.contract) { - return result.contract; - } - // just the normal result - return result - }) - .catch(function (err) { - this$1.log(LOG_ERROR_SWITCH, 'getRemoteContract err', err); - throw new JsonqlServerError('getRemoteContract', err) - }) - }; - - /** - * POST to server - query - * @param {object} name of the resolver - * @param {array} args arguments - * @return {object} promise resolve to the resolver return - */ - HttpClass.prototype.query = function query (name, args) { - if ( args === void 0 ) args = []; - - return this.request(createQuery(name, args)) - .then(clientErrorsHandler) - }; - - /** - * PUT to server - mutation - * @param {string} name of resolver - * @param {object} payload what it said - * @param {object} conditions what it said - * @return {object} promise resolve to the resolver return - */ - HttpClass.prototype.mutation = function mutation (name, payload, conditions) { - if ( payload === void 0 ) payload = {}; - if ( conditions === void 0 ) conditions = {}; - - return this.request(createMutation(name, payload, conditions), {method: PUT}) - .then(clientErrorsHandler) - }; - - Object.defineProperties( HttpClass.prototype, prototypeAccessors ); - - return HttpClass; - }(StoreClass)); - - // all the contract related methods will be here - - // export - var ContractClass = /*@__PURE__*/(function (HttpClass) { - function ContractClass(opts) { - HttpClass.call(this, opts); - } - - if ( HttpClass ) ContractClass.__proto__ = HttpClass; - ContractClass.prototype = Object.create( HttpClass && HttpClass.prototype ); - ContractClass.prototype.constructor = ContractClass; - - var prototypeAccessors = { contractHeader: { configurable: true } }; - - /** - * return the contract public api - * @return {object} contract - */ - ContractClass.prototype.getContract = function getContract () { - var contract = this.readContract(); - this.log('getContract first call', contract); - return contract ? Promise.resolve(contract) - : this.getRemoteContract().then(this.storeContract.bind(this)) - }; - - /** - * We are changing the way how to auth to get the contract.json - * Instead of in the url, we will be putting that key value in the header - * @return {object} header - */ - prototypeAccessors.contractHeader.get = function () { - var base = {}; - if (this.opts.contractKey !== false) { - base[this.opts.contractKeyName] = this.opts.contractKey; - } - return base; - }; - - /** - * Save the contract to local store - * @param {object} contract to save - * @return {object|boolean} false when its not a contract or contract on OK - */ - ContractClass.prototype.storeContract = function storeContract (contract) { - var obj; - - // first need to check if the contract is a contract - if (!isContract(contract)) { - throw new JsonqlValidationError("Contract is malformed!") - } - this.lset = ( obj = {}, obj[CLS_CONTRACT_NAME] = contract, obj ); - // return it - this.log('storeContract return result', contract); - return contract; - }; - - /** - * return the contract from options or localStore - * @return {object|boolean} false on not found - */ - ContractClass.prototype.readContract = function readContract () { - var contract = isContract(this.opts.contract); - if (contract !== false) { - return contract; - } - var data = this.lget; - if (data) { - return data[CLS_CONTRACT_NAME] - } - return false; - }; - - Object.defineProperties( ContractClass.prototype, prototypeAccessors ); - - return ContractClass; - }(HttpClass)); - - // this is the new auth class that integrate with the jsonql-jwt - // export - var AuthClass = /*@__PURE__*/(function (ContractClass) { - function AuthClass(opts) { - ContractClass.call(this, opts); - if (opts.enableAuth) { - this.setDecoder = jwtDecode; - } - } - - if ( ContractClass ) AuthClass.__proto__ = ContractClass; - AuthClass.prototype = Object.create( ContractClass && ContractClass.prototype ); - AuthClass.prototype.constructor = AuthClass; - - var prototypeAccessors = { profileIndex: { configurable: true },setDecoder: { configurable: true },saveProfile: { configurable: true },readProfile: { configurable: true },jsonqlToken: { configurable: true },jsonqlUserdata: { configurable: true } }; - - /** - * for overwrite - * @param {string} token stored token - * @return {string} token - */ - AuthClass.prototype.decoder = function decoder (token) { - return token; - }; - - /** - * set the profile index - * @param {number} idx - */ - prototypeAccessors.profileIndex.set = function (idx) { - var obj; - - var key = CLS_PROFILE_IDX; - if (isNumber$1(idx)) { - this[key] = idx; - if (this.opts.persistToken) { - this.lset = ( obj = {}, obj[key] = idx, obj ); - } - return; - } - throw new JsonqlValidationError('profileIndex', ("Expect idx to be number but got " + (typeof idx))) - }; - - /** - * get the profile index - * @return {number} idx - */ - prototypeAccessors.profileIndex.get = function () { - var key = CLS_PROFILE_IDX; - if (this.opts.persistToken) { - var data = this.lget; - if (data[key]) { - return data[key] - } - } - return this[key] ? this[key] : ZERO_IDX - }; - - /** - * Return the token from session store - * @param {number} [idx=false] profile index - * @return {string} token - */ - AuthClass.prototype.rawAuthToken = function rawAuthToken (idx) { - if ( idx === void 0 ) idx = false; - - if (idx !== false) { - this.profileIndex = idx; - } - // this should return from the base - return this.jsonqlToken; // see base-cls - }; - - /** - * Setter to add a decoder when retrieve user token - * @param {function} d a decoder - */ - prototypeAccessors.setDecoder.set = function (d) { - if (typeof d === 'function') { - this.decoder = d; - } - }; - - /** - * getter to return the session or local store set method - * @param {*} data to save - * @return {object} set method - */ - prototypeAccessors.saveProfile.set = function (data) { - if (this.opts.persistToken) { - // this.log('--- saveProfile lset ---', data) - this.lset = data; - } else { - // this.log('--- saveProfile sset ---', data) - this.sset = data; - } - }; - - /** - * getter to return the session or local store get method - * @return {object} get method - */ - prototypeAccessors.readProfile.get = function () { - return this.opts.persistToken ? this.lget : this.sget - }; - - // these were in the base class before but it should be here - /** - * save token - * @param {string} token to store - * @return {string|boolean} false on failed - */ - prototypeAccessors.jsonqlToken.set = function (token) { - var obj; - - var data = this.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - // @TODO also have to make sure the token is not already existed! - var tokens = (data && data[key]) ? data[key] : []; - tokens.push(token); - this.saveProfile = ( obj = {}, obj[key] = tokens, obj ); - // store the userdata - this.jsonqlUserdata = this.decoder(token); - }; - - /** - * Jsonql token getter - * 1.5.1 each token associate with the same profileIndex - * @return {string|boolean} false when failed - */ - prototypeAccessors.jsonqlToken.get = function () { - var data = this.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - if (data && data[key]) { - this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex]); - return data[key][this.profileIndex] - } - return false - }; - - /** - * this one will use the sessionStore - * basically we hook this onto the token store and decode it to store here - * we only store one decoded user data at a time, but the token can be multiple - */ - prototypeAccessors.jsonqlUserdata.set = function (userdata) { - var obj; - - this.sset = ( obj = {}, obj[USERDATA_TABLE] = userdata, obj ); - }; - - /** - * this one store in the session store - * get login userdata decoded jwt - * 1.5.1 each userdata associate with the same profileIndex - * @return {object|null} - */ - prototypeAccessors.jsonqlUserdata.get = function () { - var data = this.sget; - return data ? data[USERDATA_TABLE] : false - }; - - /** - * Construct the auth header - * @return {object} header - */ - AuthClass.prototype.getAuthHeader = function getAuthHeader () { - var obj; - - var token = this.jsonqlToken; // only call the getter to get the default one - return token ? ( obj = {}, obj[this.opts.AUTH_HEADER] = (BEARER + " " + token), obj ) : {}; - }; - - /** - * return all the stored token and decode it - * @param {number} [idx=false] profile index - * @return {array|boolean|string} false not found or array - */ - AuthClass.prototype.getProfiles = function getProfiles (idx) { - if ( idx === void 0 ) idx = false; - - var self = this; // just in case the scope problem - var data = self.readProfile; - var key = CREDENTIAL_STORAGE_KEY; - if (data && data[key]) { - if (idx !== false && isNumber$1(idx)) { - return data[key][idx] || false - } - return data[key].map(self.decoder.bind(self)) - } - return false - }; - - /** - * call after the login - * @param {string} token return from server - * @return {object} decoded token to userdata object - */ - AuthClass.prototype.postLoginAction = function postLoginAction (token) { - this.jsonqlToken = token; - return token - }; - - /** - * call after the logout @TODO - */ - AuthClass.prototype.postLogoutAction = function postLogoutAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - console.info("postLogoutAction", args); - }; - - Object.defineProperties( AuthClass.prototype, prototypeAccessors ); - - return AuthClass; - }(ContractClass)); - - // this the core of the internal storage management - - // This class will only focus on the storage system - var JsonqlBaseClient = /*@__PURE__*/(function (AuthCls) { - function JsonqlBaseClient(fly, opts) { - // change at 1.4.10 pass it directly without init it - this.fly = fly; - AuthCls.call(this, opts); - } - - if ( AuthCls ) JsonqlBaseClient.__proto__ = AuthCls; - JsonqlBaseClient.prototype = Object.create( AuthCls && AuthCls.prototype ); - JsonqlBaseClient.prototype.constructor = JsonqlBaseClient; - - var prototypeAccessors = { jsonqlEndpoint: { configurable: true } }; - - /** - * construct the end point - * @return {string} the end point to call - */ - prototypeAccessors.jsonqlEndpoint.get = function () { - var baseUrl = this.opts.hostname || ''; - return [baseUrl, this.opts.jsonqlPath].join('/') - }; - - /** - * simple log - */ - JsonqlBaseClient.prototype.log = function log () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - if (this.opts.debugOn === true) { - var fns = ['info', 'error']; - var idx = (args[0] === LOG_ERROR_SWITCH) ? 1 : 0; - Reflect.apply(console[fns[idx]], console, args.splice(0, idx)); - } - }; - - Object.defineProperties( JsonqlBaseClient.prototype, prototypeAccessors ); - - return JsonqlBaseClient; - }(AuthClass)); - - // export interface - - /** - * using just the map reduce to chain multiple functions together - * @param {function} mainFn the init function - * @param {array} moreFns as many as you want to take the last value and return a new one - * @return {function} accept value for the mainFn - */ - var chainFns = function (mainFn) { - var moreFns = [], len = arguments.length - 1; - while ( len-- > 0 ) moreFns[ len ] = arguments[ len + 1 ]; - - return ( - function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return ( - moreFns.reduce(function (value, nextFn) { return ( - // change here to check if the return value is array then we spread it - Reflect.apply(nextFn, null, toArray(value)) - ); }, Reflect.apply(mainFn, null, args)) - ); - } - ); - }; - - /** - * check if the object has name property - * @param {object} obj the object to check - * @param {string} name the prop name - * @return {*} the value or undefined - */ - function objHasProp(obj, name) { - var prop = Object.getOwnPropertyDescriptor(obj, name); - return prop !== undefined && prop.value ? prop.value : prop; - } - - /** - * 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 {string} name the name of the object to get inject also for checking - * @param {object} data to inject into the function static interface - * @param {boolean} [overwrite=false] if we want to overwrite the existing data - * @return {function} added property resolver - */ - function injectToFn(resolver, name, data, overwrite) { - if ( overwrite === void 0 ) overwrite = false; - - var check = objHasProp(resolver, name); - if (overwrite === false && check !== undefined) { - // console.info(`NOT INJECTED`) - return resolver; - } - /* this will throw error! - if (overwrite === true && check !== undefined) { - delete resolver[name] // delete this property - } - */ - // console.info(`INJECTED`) - Object.defineProperty(resolver, name, { - value: data, - writable: overwrite // if its set to true then we should able to overwrite it - }); - - return resolver; - } - - // breaking out the inner methods generator in here - - /** - * generate authorisation specific methods - * @param {object} jsonqlInstance instance of this - * @param {string} name of method - * @param {object} opts configuration - * @param {object} contract to match - * @return {function} for use - */ - var authMethodGenerator = function (jsonqlInstance, name, opts, contract) { - return function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var params = contract.auth[name].params; - var values = params.map(function (p, i) { return args[i]; }); - var header = args[params.length] || {}; - return validateAsync$1(args, params) - .then(function () { return jsonqlInstance - .query - .apply(jsonqlInstance, [name, values, header]); } - ) - .catch(finalCatch) - } - }; - - /** - * Break up the different type each - create query methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createQueryMethods = function (obj, jsonqlInstance, ee, config, contract) { - var query = {}; - var loop = function ( queryFn ) { - // to keep it clean we use a param to id the auth method - // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; - // generate the query method - query = injectToFn(query, queryFn, function queryFnHandler() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var params = contract.query[queryFn].params; - var _args = params.map(function (param, i) { return args[i]; }); - // debug('query', queryFn, _params); - // @TODO this need to change to a different way to add an extra header - var header = {}; - // @TODO validate against the type - return validateAsync$1(_args, params) - .then(function () { return jsonqlInstance - .query - .apply(jsonqlInstance, [queryFn, _args, header]); } - ) - .catch(finalCatch) - }); - }; - - for (var queryFn in contract.query) loop( queryFn ); - obj.query = query; - // create an alias to the helloWorld method - obj.helloWorld = query.helloWorld; - return [ obj, jsonqlInstance, ee, config, contract ] - }; - - /** - * create mutation methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createMutationMethods = function (obj, jsonqlInstance, ee, config, contract) { - var mutation = {}; - // process the mutation, the reason the mutation has a fixed number of parameters - // there is only the payload, and conditions parameters - // plus a header at the end - var loop = function ( mutationFn ) { - mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header) { - if ( header === void 0 ) header = {}; - - var args = [payload, conditions]; - var params = contract.mutation[mutationFn].params; - return validateAsync$1(args, params) - .then(function () { return jsonqlInstance - .mutation - .apply(jsonqlInstance, [mutationFn, payload, conditions, header]); } - ) - .catch(finalCatch) - }); - }; - - for (var mutationFn in contract.mutation) loop( mutationFn ); - obj.mutation = mutation; - return [ obj, jsonqlInstance, ee, config, contract ] - }; - - /** - * create auth methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op - */ - var createAuthMethods = function (obj, jsonqlInstance, ee, config, contract) { - if (config.enableAuth && contract.auth) { - var auth = {}; // v1.3.1 add back the auth prop name in contract - var loginHandlerName = config.loginHandlerName; - var logoutHandlerName = config.logoutHandlerName; - if (contract.auth[loginHandlerName]) { - // changing to the name the config specify - auth[loginHandlerName] = function loginHandlerFn() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract); - return fn.apply(null, args) - .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance)) - .then(function (token) { - ee.$trigger(LOGIN_NAME, token); - return token; - }) - }; - } - // @TODO allow to logout one particular profile or all of them - if (contract.auth[logoutHandlerName]) { - auth[logoutHandlerName] = function logoutHandlerFn() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract); - return fn.apply(null, args) - .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance)) - .then(function (r) { - ee.$trigger(LOGOUT_NAME, r); - return r; - }) - }; - } else { - auth[logoutHandlerName] = function logoutHandlerFn() { - jsonqlInstance.postLogoutAction(KEY_WORD); - ee.$trigger(LOGOUT_NAME, KEY_WORD); - }; - } - obj.auth = auth; - } - - return obj; - }; - - /** - * Here just generate the methods calls - * @param {object} jsonqlInstance what it said - * @param {object} ee event emitter - * @param {object} config configuration - * @param {object} contract the map - * @return {object} with mapped methods - */ - function methodsGenerator(jsonqlInstance, ee, config, contract) { - var obj = {}; - var executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods); - return executor(obj, jsonqlInstance, ee, config, contract) - } - - // Generate the resolver for developer to use - - /** - * @param {object} jsonqlInstance jsonql class instance - * @param {object} config options - * @param {object} contract the contract - * @param {object} ee eventEmitter - * @return {object} constructed functions call - */ - var generator = function (jsonqlInstance, config, contract, ee) { - // V1.3.0 - now everything wrap inside this method - var client = methodsGenerator(jsonqlInstance, ee, config, contract); - // create the rest of the methods - if (config.enableAuth) { - /** - * new method to allow retrieve the current login user data - * @TODO allow to pass an id to switch to different userdata - * @return {*} userdata - */ - client.userdata = function () { return jsonqlInstance.jsonqlUserdata; }; - // allow getting the token for valdiate agains the socket - // if it's not require auth there is no point of calling getToken - client.getToken = function (idx) { - if ( idx === void 0 ) idx = false; - - return jsonqlInstance.rawAuthToken(idx); - }; - // switch profile or read back what is the currenct index - client.profileIndex = function (idx) { - if ( idx === void 0 ) idx = false; - - if (idx === false) { - return jsonqlInstance.profileIndex - } - jsonqlInstance.profileIndex = idx; - }; - // new in 1.5.1 to return different profiles - client.getProfiles = function (idx) { - if ( idx === void 0 ) idx = false; - - return jsonqlInstance.getProfiles(idx); - }; - } - // this will pass to the ws-client if needed - // client.eventEmitter = ee; - // this will require a param - if (config.exposeContract) { - // 1.4.0 change from the get (raw) to the getContract cache and raw version - client.getContract = function () { return jsonqlInstance.getContract(); }; - } - // allow developer to access the store api - if (config.exposeStore) { - // @TODO in 1.5.2 - client.tmpSave = function (data) {}; - client.tmpGet = function (key) { - }; - client.tmpDel = function (key) { - }; - - client.persistSave = function (data) {}; - client.persistGet = function (key) { - }; - client.persistDel = function (key) { - }; - } - // this is for the ws to use later - but this could be dangerous because it's expose the internal - client.eventEmitter = ee; - client.version = '1.5.1'; - // use this method then we can hook into the debugOn at the same time - client.log = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return Reflect.apply(jsonqlInstance.log, jsonqlInstance, ['[DEV DEBUG]'].concat(args)); - }; - // output - return client; - }; - - // all the client configuration options here - var constProps = { - contract: false, - MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong? - CONTENT_TYPE: CONTENT_TYPE, - BEARER: BEARER, - AUTH_HEADER: AUTH_HEADER - }; - - // grab the localhost name and put into the hostname as default - var getHostName = function () { - try { - return [window.location.protocol, window.location.host].join('//') - } catch(e) { - return null - } - }; - - var appProps$1 = { - - hostname: createConfig$1(getHostName(), [STRING_TYPE]), // required the hostname - jsonqlPath: createConfig$1(JSONQL_PATH, [STRING_TYPE]), // The path on the server - - loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), - logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), - // add to koa v1.3.0 - this might remove in the future - enableJsonp: createConfig$1(false, [BOOLEAN_TYPE]), - enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), - // enable useJwt by default @TODO replace with something else and remove them later - useJwt: createConfig$1(true, [BOOLEAN_TYPE]), - // when true then store infinity or pass a time in seconds then we check against - // the token date of creation - persistToken: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE]), - // the header - // v1.2.0 we are using this option during the dev - // so it won't save anything to the localstorage and fetch a new contract - // whenever the browser reload - useLocalstorage: createConfig$1(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage - storageKey: createConfig$1(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage - authKey: createConfig$1(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage - contractExpired: createConfig$1(0, [NUMBER_TYPE]),// -1 always fetch contract, - // 0 never expired, - // > 0 then compare the timestamp with the current one to see if we need to get contract again - // useful during development - keepContract: createConfig$1(true, [BOOLEAN_TYPE]), - exposeContract: createConfig$1(false, [BOOLEAN_TYPE]), - exposeStore: createConfig$1(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn - // @1.2.1 new option for the contract-console to fetch the contract with description - showContractDesc: createConfig$1(false, [BOOLEAN_TYPE]), - contractKey: createConfig$1(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this - contractKeyName: createConfig$1(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs - enableTimeout: createConfig$1(false, [BOOLEAN_TYPE]), // @TODO - timeout: createConfig$1(5000, [NUMBER_TYPE]), // 5 seconds - returnInstance: createConfig$1(false, [BOOLEAN_TYPE]), - allowReturnRawToken: createConfig$1(false, [BOOLEAN_TYPE]), - debugOn: createConfig$1(false, [BOOLEAN_TYPE]) - }; - - // we must ensure the user passing the correct options - - function checkOptionsAsync$1(config) { - var contract = config.contract; - return checkConfigAsync$1(config, appProps$1, constProps) - .then(function (opts) { - opts.contract = contract; - return opts; - }) - } - - // export interface - /** - * 1.5.0 overload the orginal functions to pass over the check - */ - function checkOptionsAsync$2(config) { - return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsync$1(config) - } - - // this is new for the flyio and normalize the name from now on - - /** - * Main interface for jsonql fetch api - * @param {object} ee EventEmitter - * @param {object} config - * @param {object} fly this is really pain in the backside ... long story - * @return {object} jsonql client - */ - function jsonqlAsync(ee, config, fly) { - if ( config === void 0 ) config = {}; - - return checkOptionsAsync$2(config) - .then(function (opts) { return ( - { - baseClient: new JsonqlBaseClient(fly, opts), - opts: opts - } - ); }) - .then( function (ref) { - var baseClient = ref.baseClient; - var opts = ref.opts; - - return ( - getContractFromConfig(baseClient, opts.contract) - .then(function (contract) { return generator(baseClient, opts, contract, ee); }) - ); - } - ) - } - - var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); - var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); - - // making all the functionality on it's own - // import { WatchClass } from './watch' - - var SuspendClass = function SuspendClass() { - // suspend, release and queue - this.__suspend__ = null; - this.queueStore = new Set(); - /* - this.watch('suspend', function(value, prop, oldValue) { - this.logger(`${prop} set from ${oldValue} to ${value}`) - // it means it set the suspend = true then release it - if (oldValue === true && value === false) { - // we want this happen after the return happens - setTimeout(() => { - this.release() - }, 1) - } - return value; // we need to return the value to store it - }) - */ - }; - - var prototypeAccessors$1 = { $suspend: { configurable: true },$queues: { configurable: true } }; - - /** - * setter to set the suspend and check if it's boolean value - * @param {boolean} value to trigger - */ - prototypeAccessors$1.$suspend.set = function (value) { - var this$1 = this; - - if (typeof value === 'boolean') { - var lastValue = this.__suspend__; - this.__suspend__ = value; - this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); - if (lastValue === true && value === false) { - setTimeout(function () { - this$1.release(); - }, 1); - } - } else { - throw new Error("$suspend only accept Boolean value!") - } - }; - - /** - * queuing call up when it's in suspend mode - * @param {any} value - * @return {Boolean} true when added or false when it's not - */ - SuspendClass.prototype.$queue = function $queue () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - if (this.__suspend__ === true) { - this.logger('($queue)', 'added to $queue', args); - // there shouldn't be any duplicate ... - this.queueStore.add(args); - } - return this.__suspend__; - }; - - /** - * a getter to get all the store queue - * @return {array} Set turn into Array before return - */ - prototypeAccessors$1.$queues.get = function () { - var size = this.queueStore.size; - this.logger('($queues)', ("size: " + size)); - if (size > 0) { - return Array.from(this.queueStore) - } - return [] - }; - - /** - * Release the queue - * @return {int} size if any - */ - SuspendClass.prototype.release = function release () { - var this$1 = this; - - var size = this.queueStore.size; - this.logger('(release)', ("Release was called " + size)); - if (size > 0) { - var queue = Array.from(this.queueStore); - this.queueStore.clear(); - this.logger('queue', queue); - queue.forEach(function (args) { - this$1.logger(args); - Reflect.apply(this$1.$trigger, this$1, args); - }); - this.logger(("Release size " + (this.queueStore.size))); - } - }; - - Object.defineProperties( SuspendClass.prototype, prototypeAccessors$1 ); - - // break up the main file because its getting way too long - - var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { - function NbEventServiceBase(config) { - if ( config === void 0 ) config = {}; - - SuspendClass.call(this); - if (config.logger && typeof config.logger === 'function') { - this.logger = config.logger; - } - this.keep = config.keep; - // for the $done setter - this.result = config.keep ? [] : null; - // we need to init the store first otherwise it could be a lot of checking later - this.normalStore = new Map(); - this.lazyStore = new Map(); - } - - if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; - NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); - NbEventServiceBase.prototype.constructor = NbEventServiceBase; - - var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; - - /** - * validate the event name(s) - * @param {string[]} evt event name - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validateEvt = function validateEvt () { - var this$1 = this; - var evt = [], len = arguments.length; - while ( len-- ) evt[ len ] = arguments[ len ]; - - evt.forEach(function (e) { - if (typeof e !== 'string') { - this$1.logger('(validateEvt)', e); - throw new Error("event name must be string type!") - } - }); - return true; - }; - - /** - * Simple quick check on the two main parameters - * @param {string} evt event name - * @param {function} callback function to call - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validate = function validate (evt, callback) { - if (this.validateEvt(evt)) { - if (typeof callback === 'function') { - return true; - } - } - throw new Error("callback required to be function type!") - }; - - /** - * Check if this type is correct or not added in V1.5.0 - * @param {string} type for checking - * @return {boolean} true on OK - */ - NbEventServiceBase.prototype.validateType = function validateType (type) { - var types = ['on', 'only', 'once', 'onlyOnce']; - return !!types.filter(function (t) { return type === t; }).length; - }; - - /** - * Run the callback - * @param {function} callback function to execute - * @param {array} payload for callback - * @param {object} ctx context or null - * @return {void} the result store in $done - */ - NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { - this.logger('(run)', callback, payload, ctx); - this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); - }; - - /** - * Take the content out and remove it from store id by the name - * @param {string} evt event name - * @param {string} [storeName = lazyStore] name of store - * @return {object|boolean} content or false on not found - */ - NbEventServiceBase.prototype.takeFromStore = function takeFromStore (evt, storeName) { - if ( storeName === void 0 ) storeName = 'lazyStore'; - - var store = this[storeName]; // it could be empty at this point - if (store) { - this.logger('(takeFromStore)', storeName, store); - if (store.has(evt)) { - var content = store.get(evt); - this.logger('(takeFromStore)', ("has " + evt), content); - store.delete(evt); - return content; - } - return false; - } - throw new Error((storeName + " is not supported!")) - }; - - /** - * The add to store step is similar so make it generic for resuse - * @param {object} store which store to use - * @param {string} evt event name - * @param {spread} args because the lazy store and normal store store different things - * @return {array} store and the size of the store - */ - NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { - var args = [], len = arguments.length - 2; - while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; - - var fnSet; - if (store.has(evt)) { - this.logger('(addToStore)', (evt + " existed")); - fnSet = store.get(evt); - } else { - this.logger('(addToStore)', ("create new Set for " + evt)); - // this is new - fnSet = new Set(); - } - // lazy only store 2 items - this is not the case in V1.6.0 anymore - // we need to check the first parameter is string or not - if (args.length > 2) { - if (Array.isArray(args[0])) { // lazy store - // check if this type of this event already register in the lazy store - var t = args[2]; - if (!this.checkTypeInLazyStore(evt, t)) { - fnSet.add(args); - } - } else { - if (!this.checkContentExist(args, fnSet)) { - this.logger('(addToStore)', "insert new", args); - fnSet.add(args); - } - } - } else { // add straight to lazy store - fnSet.add(args); - } - store.set(evt, fnSet); - return [store, fnSet.size] - }; - - /** - * @param {array} args for compare - * @param {object} fnSet A Set to search from - * @return {boolean} true on exist - */ - NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { - var list = Array.from(fnSet); - return !!list.filter(function (l) { - var hash = l[0]; - if (hash === args[0]) { - return true; - } - return false; - }).length; - }; - - /** - * get the existing type to make sure no mix type add to the same store - * @param {string} evtName event name - * @param {string} type the type to check - * @return {boolean} true you can add, false then you can't add this type - */ - NbEventServiceBase.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { - this.validateEvt(evtName, type); - var all = this.$get(evtName, true); - if (all === false) { - // pristine it means you can add - return true; - } - // it should only have ONE type in ONE event store - return !all.filter(function (list) { - var t = list[3]; - return type !== t; - }).length; - }; - - /** - * This is checking just the lazy store because the structure is different - * therefore we need to use a new method to check it - */ - NbEventServiceBase.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { - this.validateEvt(evtName, type); - var store = this.lazyStore.get(evtName); - this.logger('(checkTypeInLazyStore)', store); - if (store) { - return !!Array - .from(store) - .filter(function (l) { - var t = l[2]; - return t !== type; - }).length - } - return false; - }; - - /** - * wrapper to re-use the addToStore, - * V1.3.0 add extra check to see if this type can add to this evt - * @param {string} evt event name - * @param {string} type on or once - * @param {function} callback function - * @param {object} context the context the function execute in or null - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { - if ( context === void 0 ) context = null; - - this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); - // @TODO we need to check the existing store for the type first! - if (this.checkTypeInStore(evt, type)) { - this.logger('(addToNormalStore)', (type + " can add to " + evt + " normal store")); - var key = this.hashFnToKey(callback); - var args = [this.normalStore, evt, key, callback, context, type]; - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.normalStore = _store; - return size; - } - return false; - }; - - /** - * Add to lazy store this get calls when the callback is not register yet - * so we only get a payload object or even nothing - * @param {string} evt event name - * @param {array} payload of arguments or empty if there is none - * @param {object} [context=null] the context the callback execute in - * @param {string} [type=false] register a type so no other type can add to this evt - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - // this is add in V1.6.0 - // when there is type then we will need to check if this already added in lazy store - // and no other type can add to this lazy store - var args = [this.lazyStore, evt, this.toArray(payload), context]; - if (type) { - args.push(type); - } - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.lazyStore = _store; - return size; - }; - - /** - * make sure we store the argument correctly - * @param {*} arg could be array - * @return {array} make sured - */ - NbEventServiceBase.prototype.toArray = function toArray (arg) { - return Array.isArray(arg) ? arg : [arg]; - }; - - /** - * setter to store the Set in private - * @param {object} obj a Set - */ - prototypeAccessors.normalStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); - }; - - /** - * @return {object} Set object - */ - prototypeAccessors.normalStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) - }; - - /** - * setter to store the Set in lazy store - * @param {object} obj a Set - */ - prototypeAccessors.lazyStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); - }; - - /** - * @return {object} the lazy store Set - */ - prototypeAccessors.lazyStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) - }; - - /** - * generate a hashKey to identify the function call - * The build-in store some how could store the same values! - * @param {function} fn the converted to string function - * @return {string} hashKey - */ - NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { - return hashCode(fn.toString()) + ''; - }; - - Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); - - return NbEventServiceBase; - }(SuspendClass)); - - // The top level - // export - var EventService = /*@__PURE__*/(function (NbStoreService) { - function EventService(config) { - if ( config === void 0 ) config = {}; - - NbStoreService.call(this, config); - } - - if ( NbStoreService ) EventService.__proto__ = NbStoreService; - EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); - EventService.prototype.constructor = EventService; - - var prototypeAccessors = { $done: { configurable: true } }; - - /** - * logger function for overwrite - */ - EventService.prototype.logger = function logger () {}; - - ////////////////////////// - // PUBLIC METHODS // - ////////////////////////// - - /** - * Register your evt handler, note we don't check the type here, - * we expect you to be sensible and know what you are doing. - * @param {string} evt name of event - * @param {function} callback bind method --> if it's array or not - * @param {object} [context=null] to execute this call in - * @return {number} the size of the store - */ - EventService.prototype.$on = function $on (evt , callback , context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - var type = 'on'; - this.validate(evt, callback); - // first need to check if this evt is in lazy store - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register first then call later - if (lazyStoreContent === false) { - this.logger('($on)', (evt + " callback is not in lazy store")); - // @TODO we need to check if there was other listener to this - // event and are they the same type then we could solve that - // register the different type to the same event name - - return this.addToNormalStore(evt, type, callback, context) - } - this.logger('($on)', (evt + " found in lazy store")); - // this is when they call $trigger before register this callback - var size = 0; - lazyStoreContent.forEach(function (content) { - var payload = content[0]; - var ctx = content[1]; - var t = content[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.logger("($on)", ("call run on " + evt)); - this$1.run(callback, payload, context || ctx); - size += this$1.addToNormalStore(evt, type, callback, context || ctx); - }); - return size; - }; - - /** - * once only registered it once, there is no overwrite option here - * @NOTE change in v1.3.0 $once can add multiple listeners - * but once the event fired, it will remove this event (see $only) - * @param {string} evt name - * @param {function} callback to execute - * @param {object} [context=null] the handler execute in - * @return {boolean} result - */ - EventService.prototype.$once = function $once (evt , callback , context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'once'; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (lazyStoreContent === false) { - this.logger('($once)', (evt + " not in the lazy store")); - // v1.3.0 $once now allow to add multiple listeners - return this.addToNormalStore(evt, type, callback, context) - } else { - // now this is the tricky bit - // there is a potential bug here that cause by the developer - // if they call $trigger first, the lazy won't know it's a once call - // so if in the middle they register any call with the same evt name - // then this $once call will be fucked - add this to the documentation - this.logger('($once)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.logger('($once)', ("call run for " + evt)); - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - }; - - /** - * This one event can only bind one callbackback - * @param {string} evt event name - * @param {function} callback event handler - * @param {object} [context=null] the context the event handler execute in - * @return {boolean} true bind for first time, false already existed - */ - EventService.prototype.$only = function $only (evt, callback, context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'only'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($only)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($only)', (evt + " found data in lazy store to execute")); - var list = Array.from(lazyStoreContent); - // $only allow to trigger this multiple time on the single handler - list.forEach( function (l) { - var payload = l[0]; - var ctx = l[1]; - var t = l[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.logger("($only)", ("call run for " + evt)); - this$1.run(callback, payload, context || ctx); - }); - } - return added; - }; - - /** - * $only + $once this is because I found a very subtile bug when we pass a - * resolver, rejecter - and it never fire because that's OLD added in v1.4.0 - * @param {string} evt event name - * @param {function} callback to call later - * @param {object} [context=null] exeucte context - * @return {void} - */ - EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'onlyOnce'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($onlyOnce)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($onlyOnce)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== 'onlyOnce') { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.logger("($onlyOnce)", ("call run for " + evt)); - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - return added; - }; - - /** - * This is a shorthand of $off + $on added in V1.5.0 - * @param {string} evt event name - * @param {function} callback to exeucte - * @param {object} [context = null] or pass a string as type - * @param {string} [type=on] what type of method to replace - * @return {} - */ - EventService.prototype.$replace = function $replace (evt, callback, context, type) { - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = 'on'; - - if (this.validateType(type)) { - this.$off(evt); - var method = this['$' + type]; - this.logger("($replace)", evt, callback); - return Reflect.apply(method, this, [evt, callback, context]) - } - throw new Error((type + " is not supported!")) - }; - - /** - * trigger the event - * @param {string} evt name NOT allow array anymore! - * @param {mixed} [payload = []] pass to fn - * @param {object|string} [context = null] overwrite what stored - * @param {string} [type=false] if pass this then we need to add type to store too - * @return {number} if it has been execute how many times - */ - EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - this.validateEvt(evt); - var found = 0; - // first check the normal store - var nStore = this.normalStore; - this.logger('($trigger)', 'normalStore', nStore); - if (nStore.has(evt)) { - // @1.8.0 to add the suspend queue - var added = this.$queue(evt, payload, context, type); - this.logger('($trigger)', evt, 'found; add to queue: ', added); - if (added === true) { - this.logger('($trigger)', evt, 'not executed. Exit now.'); - return false; // not executed - } - var nSet = Array.from(nStore.get(evt)); - var ctn = nSet.length; - var hasOnce = false; - for (var i=0; i < ctn; ++i) { - ++found; - // this.logger('found', found) - var ref = nSet[i]; - var _ = ref[0]; - var callback = ref[1]; - var ctx = ref[2]; - var type$1 = ref[3]; - this.logger("($trigger)", ("call run for " + evt)); - this.run(callback, payload, context || ctx); - if (type$1 === 'once' || type$1 === 'onlyOnce') { - hasOnce = true; - } - } - if (hasOnce) { - nStore.delete(evt); - } - return found; - } - // now this is not register yet - this.addToLazyStore(evt, payload, context, type); - return found; - }; - - /** - * this is an alias to the $trigger - * @NOTE breaking change in V1.6.0 we swap the parameter around - * @param {string} evt event name - * @param {*} params pass to the callback - * @param {string} type of call - * @param {object} context what context callback execute in - * @return {*} from $trigger - */ - EventService.prototype.$call = function $call (evt, params, type, context) { - if ( type === void 0 ) type = false; - if ( context === void 0 ) context = null; - - var args = [evt, params, context, type]; - return Reflect.apply(this.$trigger, this, args) - }; - - /** - * remove the evt from all the stores - * @param {string} evt name - * @return {boolean} true actually delete something - */ - EventService.prototype.$off = function $off (evt) { - var this$1 = this; - - this.validateEvt(evt); - var stores = [ this.lazyStore, this.normalStore ]; - var found = false; - stores.forEach(function (store) { - if (store.has(evt)) { - found = true; - this$1.logger('($off)', evt); - store.delete(evt); - } - }); - return found; - }; - - /** - * return all the listener from the event - * @param {string} evtName event name - * @param {boolean} [full=false] if true then return the entire content - * @return {array|boolean} listerner(s) or false when not found - */ - EventService.prototype.$get = function $get (evt, full) { - if ( full === void 0 ) full = false; - - this.validateEvt(evt); - var store = this.normalStore; - if (store.has(evt)) { - return Array - .from(store.get(evt)) - .map( function (l) { - if (full) { - return l; - } - var key = l[0]; - var callback = l[1]; - return callback; - }) - } - return false; - }; - - /** - * store the return result from the run - * @param {*} value whatever return from callback - */ - prototypeAccessors.$done.set = function (value) { - this.logger('($done)', 'value: ', value); - if (this.keep) { - this.result.push(value); - } else { - this.result = value; - } - }; - - /** - * @TODO is there any real use with the keep prop? - * getter for $done - * @return {*} whatever last store result - */ - prototypeAccessors.$done.get = function () { - if (this.keep) { - this.logger('(get $done)', this.result); - return this.result[this.result.length - 1] - } - return this.result; - }; - - Object.defineProperties( EventService.prototype, prototypeAccessors ); - - return EventService; - }(NbEventServiceBase)); - - // default - - // this will generate a event emitter and will be use everywhere - // output - function getEventEmitter(debugOn) { - var logger = debugOn ? function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - args.unshift('[NBS]'); - console.log.apply(null, args); - }: undefined; - return new EventService({ logger: logger }) - } - - // main export interface - /** - * When pass a static contract then it return a static interface - * otherwise it will become the async interface - * @param {object} fly the http engine - already init object not the class! - * @param {object} config configuration - * @return {object} jsonqlClient - */ - function jsonqlClient(fly, config) { - var ee = getEventEmitter(config.debugOn); - return jsonqlAsync(ee, config, fly) - } - - // this one will bring the fly.js in - - function full(config) { - if ( config === void 0 ) config = {}; - - return jsonqlClient(new Fly(), config) - } - - return full; - -}))); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClient=e()}(this,(function(){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r,n=e((function(t,e){var r;r=function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=2)}([function(t,e,r){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};t.exports={type:function(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()},isObject:function(t,e){return e?"object"===this.type(t):t&&"object"===(void 0===t?"undefined":n(t))},isFormData:function(t){return"undefined"!=typeof FormData&&t instanceof FormData},trim:function(t){return t.replace(/(^\s*)|(\s*$)/g,"")},encode:function(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")},formatParams:function(t){var e="",r=!0,n=this;return this.isObject(t)?(function t(o,i){var a=n.encode,u=n.type(o);if("array"==u)o.forEach((function(e,r){n.isObject(e)||(r=""),t(e,i+"%5B"+r+"%5D")}));else if("object"==u)for(var c in o)t(o[c],i?i+"%5B"+a(c)+"%5D":a(c));else r||(e+="&"),r=!1,e+=i+"="+a(o)}(t,""),e):t},merge:function(t,e){for(var r in e)t.hasOwnProperty(r)?this.isObject(e[r],1)&&this.isObject(t[r],1)&&this.merge(t[r],e[r]):t[r]=e[r];return t}}},,function(t,e,r){var n=function(){function t(t,e){for(var r=0;r0&&(t+=(-1===t.indexOf("?")?"?":"&")+w.join("&")),a.open(r.method,t);try{a.withCredentials=!!r.withCredentials,a.timeout=r.timeout||0,"stream"!==y&&(a.responseType=y)}catch(t){}var j=r.headers[u]||r.headers[c],S="application/x-www-form-urlencoded";for(var O in o.trim((j||"").toLowerCase())===S?e=o.formatParams(e):o.isFormData(e)||-1===["object","array"].indexOf(o.type(e))||(S="application/json;charset=utf-8",e=JSON.stringify(e)),j||b||(r.headers[u]=S),r.headers)if(O===u&&o.isFormData(e))delete r.headers[O];else try{a.setRequestHeader(O,r.headers[O])}catch(t){}function k(t,e,n){v(l.p,(function(){if(t){n&&(e.request=r);var o=t.call(l,e,Promise);e=void 0===o?e:o}d(e)||(e=Promise[0===n?"resolve":"reject"](e)),e.then((function(t){s(t)})).catch((function(t){h(t)}))}))}function E(t){t.engine=a,k(l.onerror,t,-1)}function A(t,e){this.message=t,this.status=e}a.onload=function(){try{var t=a.response||a.responseText;t&&r.parseJson&&-1!==(a.getResponseHeader(u)||"").indexOf("json")&&!o.isObject(t)&&(t=JSON.parse(t));var e=a.responseHeaders;if(!e){e={};var n=(a.getAllResponseHeaders()||"").split("\r\n");n.pop(),n.forEach((function(t){if(t){var r=t.split(":")[0];e[r]=a.getResponseHeader(r)}}))}var i=a.status,c=a.statusText,s={data:t,headers:e,status:i,statusText:c};if(o.merge(s,a._response),i>=200&&i<300||304===i)s.engine=a,s.request=r,k(l.handler,s,0);else{var f=new A(c,i);f.response=s,E(f)}}catch(f){E(new A(f.msg,a.status))}},a.onerror=function(t){E(new A(t.msg||"Network Error",0))},a.ontimeout=function(){E(new A("timeout [ "+a.timeout+"ms ]",1))},a._options=r,setTimeout((function(){a.send(b?null:e)}),0)}(n):s(n)}),(function(t){h(t)}))}))}));return h.engine=a,h}},{key:"all",value:function(t){return Promise.all(t)}},{key:"spread",value:function(t){return function(e){return t.apply(null,e)}}}]),t}();a.default=a,["get","post","put","patch","head","delete"].forEach((function(t){a.prototype[t]=function(e,r,n){return this.request(e,r,o.merge({method:t},n))}})),["lock","unlock","clear"].forEach((function(t){a.prototype[t]=function(){this.interceptors.request[t]()}})),t.exports=a}])},t.exports=r()})),o=(r=n)&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r,i="application/vnd.api+json",a={Accept:i,"Content-Type":[i,"charset=utf-8"].join(";")},u="query",c="mutation",s="socket",f="payload",l="condition",p="TS",h=["POST","PUT"],d="type",v="optional",g="enumv",y="args",b="checker",m="alias",_="__checked__",w={desc:"y"},j="No message",S=Array.isArray,O="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},k="object"==typeof O&&O&&O.Object===Object&&O,E="object"==typeof self&&self&&self.Object===Object&&self,A=k||E||Function("return this")(),x=A.Symbol,T=Object.prototype,P=T.hasOwnProperty,q=T.toString,C=x?x.toStringTag:void 0;var $=Object.prototype.toString;var z="[object Null]",N="[object Undefined]",R=x?x.toStringTag:void 0;function M(t){return null==t?void 0===t?N:z:R&&R in Object(t)?function(t){var e=P.call(t,C),r=t[C];try{t[C]=void 0;var n=!0}catch(t){}var o=q.call(t);return n&&(e?t[C]=r:delete t[C]),o}(t):function(t){return $.call(t)}(t)}function F(t,e){return function(r){return t(e(r))}}var I=F(Object.getPrototypeOf,Object);function J(t){return null!=t&&"object"==typeof t}var D="[object Object]",U=Function.prototype,H=Object.prototype,L=U.toString,B=H.hasOwnProperty,K=L.call(Object);function G(t){if(!J(t)||M(t)!=D)return!1;var e=I(t);if(null===e)return!0;var r=B.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&L.call(r)==K}function V(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&nt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var mt=function(t){return S(t)?t:[t]},_t=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),xt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),Pt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),qt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Ct=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),$t=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),zt=Object.freeze({__proto__:null,Jsonql406Error:wt,Jsonql500Error:jt,JsonqlForbiddenError:St,JsonqlAuthorisationError:Ot,JsonqlContractAuthError:kt,JsonqlResolverAppError:Et,JsonqlResolverNotFoundError:At,JsonqlEnumError:xt,JsonqlTypeError:Tt,JsonqlCheckerError:Pt,JsonqlValidationError:qt,JsonqlError:Ct,JsonqlServerError:$t}),Nt=Ct,Rt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function Mt(t){if(Rt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||j,a=e.detail||e;if(o&&zt[o])throw new zt[r](i,a);throw new Nt(i,a)}return t}function Ft(t){if(Array.isArray(t))throw new qt("",t);var e=t.message||j,r=t.detail||t;switch(!0){case t instanceof wt:throw new wt(e,r);case t instanceof jt:throw new jt(e,r);case t instanceof St:throw new St(e,r);case t instanceof Ot:throw new Ot(e,r);case t instanceof kt:throw new kt(e,r);case t instanceof Et:throw new Et(e,r);case t instanceof At:throw new At(e,r);case t instanceof xt:throw new xt(e,r);case t instanceof Tt:throw new Tt(e,r);case t instanceof Pt:throw new Pt(e,r);case t instanceof qt:throw new qt(e,r);case t instanceof $t:throw new $t(e,r);default:throw new Ct(e,r)}}function It(t){return!!function(t){return G(t)&&(_t(t,u)||_t(t,c)||_t(t,s))}(t)&&t}function Jt(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var Dt=function(t,e){return void 0===e&&(e={}),It(e)?Promise.resolve(e):t.getContract()},Ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function Ht(t){this.message=t}Ht.prototype=new Error,Ht.prototype.name="InvalidCharacterError";var Lt="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new Ht("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=Ut.indexOf(n);return a};var Bt=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Lt(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return Lt(e)}};function Kt(t){this.message=t}Kt.prototype=new Error,Kt.prototype.name="InvalidTokenError";var Gt=function(t,e){if("string"!=typeof t)throw new Kt("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(Bt(t.split(".")[r]))}catch(t){throw new Kt("Invalid token specified: "+t.message)}},Vt=Kt;Gt.InvalidTokenError=Vt;var Wt="[object String]";function Yt(t){return"string"==typeof t||!S(t)&&J(t)&&M(t)==Wt}var Qt=function(t){return""!==bt(t)&&Yt(t)},Xt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Zt(t){if(Qt(t))return function(t){var e=t.iat||Xt(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Ct("Token has expired on "+r,t)}return t}(Gt(t));throw new Ct("Token must be a string!")}var te=function(t){return!!S(t)||null!=t&&""!==bt(t)},ee="[object Number]";function re(t){return function(t){return"number"==typeof t||J(t)&&M(t)==ee}(t)&&t!=+t}var ne=function(t){return!Yt(t)&&!re(parseFloat(t))},oe=function(t){return null!=t&&"boolean"==typeof t},ie=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==bt(t)&&(!1===e||!0===e&&null!==t)},ae=d,ue=v,ce=g,se=y,fe=b,le=m,pe="continue",he=function(t){switch(t){case"number":return ne;case"string":return Qt;case"boolean":return oe;default:return ie}},de=function(t,e){return void 0===e&&(e=""),!!S(t)&&(""===e||""===bt(e)||!(t.filter((function(t){return!he(e)(t)})).length>0))},ve=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ge=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!he(e)(t)})).length)})).length:e.length>e.filter((function(t){return!de(r,t)})).length};var ye,be=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[ye?a:++n];if(!1===e(o[u],u,o))break}return t};var me="[object Arguments]";function _e(t){return J(t)&&M(t)==me}var we=Object.prototype,je=we.hasOwnProperty,Se=we.propertyIsEnumerable,Oe=_e(function(){return arguments}())?_e:function(t){return J(t)&&je.call(t,"callee")&&!Se.call(t,"callee")};var ke="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ee=ke&&"object"==typeof module&&module&&!module.nodeType&&module,Ae=Ee&&Ee.exports===ke?A.Buffer:void 0,xe=(Ae?Ae.isBuffer:void 0)||function(){return!1},Te=9007199254740991,Pe=/^(?:0|[1-9]\d*)$/;function qe(t,e){var r=typeof t;return!!(e=null==e?Te:e)&&("number"==r||"symbol"!=r&&Pe.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=Ce}var ze={};ze["[object Float32Array]"]=ze["[object Float64Array]"]=ze["[object Int8Array]"]=ze["[object Int16Array]"]=ze["[object Int32Array]"]=ze["[object Uint8Array]"]=ze["[object Uint8ClampedArray]"]=ze["[object Uint16Array]"]=ze["[object Uint32Array]"]=!0,ze["[object Arguments]"]=ze["[object Array]"]=ze["[object ArrayBuffer]"]=ze["[object Boolean]"]=ze["[object DataView]"]=ze["[object Date]"]=ze["[object Error]"]=ze["[object Function]"]=ze["[object Map]"]=ze["[object Number]"]=ze["[object Object]"]=ze["[object RegExp]"]=ze["[object Set]"]=ze["[object String]"]=ze["[object WeakMap]"]=!1;var Ne,Re="object"==typeof exports&&exports&&!exports.nodeType&&exports,Me=Re&&"object"==typeof module&&module&&!module.nodeType&&module,Fe=Me&&Me.exports===Re&&k.process,Ie=function(){try{var t=Me&&Me.require&&Me.require("util").types;return t||Fe&&Fe.binding&&Fe.binding("util")}catch(t){}}(),Je=Ie&&Ie.isTypedArray,De=Je?(Ne=Je,function(t){return Ne(t)}):function(t){return J(t)&&$e(t.length)&&!!ze[M(t)]},Ue=Object.prototype.hasOwnProperty;function He(t,e){var r=S(t),n=!r&&Oe(t),o=!r&&!n&&xe(t),i=!r&&!n&&!o&&De(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},ar.prototype.set=function(t,e){var r=this.__data__,n=or(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var ur,cr=A["__core-js_shared__"],sr=(ur=/[^.]+$/.exec(cr&&cr.keys&&cr.keys.IE_PROTO||""))?"Symbol(src)_1."+ur:"";var fr=Function.prototype.toString;function lr(t){if(null!=t){try{return fr.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var pr=/^\[object .+?Constructor\]$/,hr=Function.prototype,dr=Object.prototype,vr=hr.toString,gr=dr.hasOwnProperty,yr=RegExp("^"+vr.call(gr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function br(t){return!(!Ve(t)||function(t){return!!sr&&sr in t}(t))&&(Ze(t)?yr:pr).test(lr(t))}function mr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return br(r)?r:void 0}var _r=mr(A,"Map"),wr=mr(Object,"create");var jr="__lodash_hash_undefined__",Sr=Object.prototype.hasOwnProperty;var Or=Object.prototype.hasOwnProperty;var kr="__lodash_hash_undefined__";function Er(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&Nr?new Cr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=ve(t))?!ge({arg:r},e):!he(t)(r))})).length)})).length}return!1},ro=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(eo,null,a);case"array"===t:return!de(e.arg);case!1!==(r=ve(t)):return!ge(e,r);default:return!he(t)(e.arg)}},no=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},oo=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!de(e))throw new Ct("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!de(t))throw new Ct("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?no(t,a):t,index:r,param:a,optional:i}}));default:throw new Ct("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!te(e)&&!(r.type.length>r.type.filter((function(e){return ro(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return ro(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},io=function(){try{var t=mr(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function ao(t,e,r){"__proto__"==e&&io?io(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function uo(t,e,r){(void 0===r||nr(t[e],r))&&(void 0!==r||e in t)||ao(t,e,r)}var co="object"==typeof exports&&exports&&!exports.nodeType&&exports,so=co&&"object"==typeof module&&module&&!module.nodeType&&module,fo=so&&so.exports===co?A.Buffer:void 0,lo=fo?fo.allocUnsafe:void 0;function po(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new Mr(n).set(new Mr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var ho=Object.create,vo=function(){function t(){}return function(e){if(!Ve(e))return{};if(ho)return ho(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function go(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var yo=Object.prototype.hasOwnProperty;function bo(t,e,r){var n=t[e];yo.call(t,e)&&nr(n,r)&&(void 0!==r||e in t)||ao(t,e,r)}var mo=Object.prototype.hasOwnProperty;function _o(t){if(!Ve(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Be(t),r=[];for(var n in t)("constructor"!=n||!e&&mo.call(t,n))&&r.push(n);return r}function wo(t){return tr(t)?He(t,!0):_o(t)}function jo(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=xo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Ao);function Co(t,e){return qo(function(t,e,r){return e=Eo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Eo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=$o.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!Ve(r))return!1;var n=typeof e;return!!("number"==n?tr(r)&&qe(e,r.length):"string"==n&&e in r)&&nr(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=0;e--){var r=Ri().key(e);t(Mi(r),r)}},remove:function(t){return Ri().removeItem(t)},clearAll:function(){return Ri().clear()}};function Ri(){return zi.localStorage}function Mi(t){return Ri().getItem(t)}var Fi=bi.trim,Ii={name:"cookieStorage",read:function(t){if(!t||!Hi(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Ji.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Ji.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Di,remove:Ui,clearAll:function(){Di((function(t,e){Ui(e)}))}},Ji=bi.Global.document;function Di(t){for(var e=Ji.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Fi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Ui(t){t&&Hi(t)&&(Ji.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Hi(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Ji.cookie)}var Li=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Bi=bi.bind,Ki=bi.each,Gi=bi.create,Vi=bi.slice,Wi=function(){var t=Gi(Yi,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Bi(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Bi(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),Ki(r,(function(e,r){t.fire(r,void 0,e)}))}}};var Yi={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Bi(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Vi(arguments,1);Ki(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},Qi=e((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),Xi=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=Qi.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=Qi.compress(this._serialize(r));t(e,n)}}};var Zi=[Ni,Ii],ta=[Li,Wi,Xi],ea=qi.createStore(Zi,ta),ra=bi.Global;function na(){return ra.sessionStorage}function oa(t){return na().getItem(t)}var ia=[{name:"sessionStorage",read:oa,write:function(t,e){return na().setItem(t,e)},each:function(t){for(var e=na().length-1;e>=0;e--){var r=na().key(e);t(oa(r),r)}},remove:function(t){return na().removeItem(t)},clearAll:function(){return na().clear()}},Ii],aa=[Li,Xi],ua=qi.createStore(ia,aa),ca=ea,sa=ua,fa=function(t){var e;return(e={}).args=t,e};function la(t,e){var r;return(r={})[t]=e,r[p]=[hi()],r}var pa=function(t){return _t(t,"data")&&!_t(t,"error")?t.data:t},ha=function(t){this.opts=t,this.instanceKey=Jt(this.opts.hostname)+"",this.localStore=ca,this.sessionStore=sa},da={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};ha.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?zo({},o,e):e,r))},ha.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},ha.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},ha.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},da.lset.set=function(t){return this.__setMethod("localStore",t)},da.lget.get=function(){return this.__getMethod("localStore")},ha.prototype.ldel=function(t){return this.__delMethod("localStore",t)},ha.prototype.lclear=function(){return this.__clearMethod("localStore")},da.sset.set=function(t){return this.__setMethod("sessionStore",t)},da.sget.get=function(){return this.__getMethod("sessionStore")},ha.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},ha.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(ha.prototype,da);var va=h[0],ga=h[1],ya=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Zt)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(si(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new qt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&si(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!It(t))throw new qt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=It(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={headers:{configurable:!0}};return r.headers.set=function(t){this.extraHeader=t},e.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=zo({},{_cb:hi()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=zo({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=zo({},{method:va,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},e.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},e.prototype.processJsonp=function(t){return pa(t)},e.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=ci(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):pa(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new $t("Server side error",r)}))},e.prototype.getHeaders=function(){return this.opts.enableAuth?zo({},a,this.getAuthHeader(),this.extraHeader):zo({},a,this.extraHeader)},e.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},e.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=zo({},this.extraParams,w)),this.request({},{method:"GET"},this.contractHeader).then(Mt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new $t("getRemoteContract",e)}))},e.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Yt(t)&&S(e)){var n=fa(e);return!0===r?n:la(t,n)}throw new qt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(Mt)},e.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[f]=e,o[l]=r,!0===n)return o;if(Yt(t))return la(t,o);throw new qt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:ga}).then(Mt)},Object.defineProperties(e.prototype,r),e}(ha)))),ba=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,mt(t))}),Reflect.apply(t,null,r))}};function ma(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function _a(t,e,r,n){void 0===n&&(n=!1);var o=ma(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var wa=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return fi(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch(Ft)}},ja=function(t,e,r,n,o){var i={},a=function(t){i=_a(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return fi(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch(Ft)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},Sa=function(t,e,r,n,o){var i={},a=function(t){i=_a(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return fi(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch(Ft)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Oa=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=wa(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=wa(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var ka=function(t,e,r,n){var o=function(t,e,r,n){return ba(ja,Sa,Oa)({},t,e,r,n)}(t,n,e,r);return e.enableAuth&&(o.userdata=function(){return t.jsonqlUserdata},o.getToken=function(e){return void 0===e&&(e=!1),t.rawAuthToken(e)},o.profileIndex=function(e){if(void 0===e&&(e=!1),!1===e)return t.profileIndex;t.profileIndex=e},o.getProfiles=function(e){return void 0===e&&(e=!1),t.getProfiles(e)}),e.exposeContract&&(o.getContract=function(){return t.getContract()}),e.exposeStore&&(o.tmpSave=function(t){},o.tmpGet=function(t){},o.tmpDel=function(t){},o.persistSave=function(t){},o.persistGet=function(t){},o.persistDel=function(t){}),o.eventEmitter=n,o.version="1.5.2",o.log=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return Reflect.apply(t.log,t,["[DEV DEBUG]"].concat(e))},o},Ea={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:i,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Aa={hostname:li(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:li("jsonql",["string"]),loginHandlerName:li("login",["string"]),logoutHandlerName:li("logout",["string"]),enableJsonp:li(!1,["boolean"]),enableAuth:li(!1,["boolean"]),useJwt:li(!0,["boolean"]),persistToken:li(!1,["boolean","number"]),useLocalstorage:li(!0,["boolean"]),storageKey:li("jsonqlstore",["string"]),authKey:li("jsonqlauthkey",["string"]),contractExpired:li(0,["number"]),keepContract:li(!0,["boolean"]),exposeContract:li(!1,["boolean"]),exposeStore:li(!1,["boolean"]),showContractDesc:li(!1,["boolean"]),contractKey:li(!1,["boolean"]),contractKeyName:li("X-JSONQL-CV-KEY",["string"]),enableTimeout:li(!1,["boolean"]),timeout:li(5e3,["number"]),returnInstance:li(!1,["boolean"]),allowReturnRawToken:li(!1,["boolean"]),debugOn:li(!1,["boolean"])};function xa(t){return ma(t,_)?Promise.resolve(t):function(t){var e=t.contract;return pi(t,Aa,Ea).then((function(t){return t.contract=e,t}))}(t)}var Ta=new WeakMap,Pa=new WeakMap,qa=function(){this.__suspend__=null,this.queueStore=new Set},Ca={$suspend:{configurable:!0},$queues:{configurable:!0}};Ca.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},qa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ca.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},qa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(qa.prototype,Ca);var $a=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Ta.set(this,t)},r.normalStore.get=function(){return Ta.get(this)},r.lazyStore.set=function(t){Pa.set(this,t)},r.lazyStore.get=function(){return Pa.get(this)},e.prototype.hashFnToKey=function(t){return Jt(t.toString())+""},Object.defineProperties(e.prototype,r),e}(qa));function za(t,e){var r;return function(t,e,r){return void 0===e&&(e={}),xa(e).then((function(t){return{baseClient:new ya(r,t),opts:t}})).then((function(e){var r=e.baseClient,n=e.opts;return Dt(r,n.contract).then((function(e){return ka(r,n,e,t)}))}))}((r=e.debugOn,new $a({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),e,t)}return function(t){return void 0===t&&(t={}),za(new o,t)}})); //# sourceMappingURL=jsonql-client.umd.js.map diff --git a/packages/http-client/dist/jsonql-client.umd.js.map b/packages/http-client/dist/jsonql-client.umd.js.map index 4061c1e2..6f743419 100644 --- a/packages/http-client/dist/jsonql-client.umd.js.map +++ b/packages/http-client/dist/jsonql-client.umd.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client.umd.js","sources":["../node_modules/lodash-es/isArray.js","../node_modules/rollup-plugin-node-globals/src/global.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/lodash-es/_arrayMap.js","../node_modules/lodash-es/_baseSlice.js","../node_modules/lodash-es/_baseFindIndex.js","../node_modules/lodash-es/_baseIsNaN.js","../node_modules/lodash-es/_strictIndexOf.js","../node_modules/lodash-es/_asciiToArray.js","../node_modules/lodash-es/_hasUnicode.js","../node_modules/lodash-es/_unicodeToArray.js","../node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-errors/src/resolver-not-found-error.js","../node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-errors/src/index.js","../node_modules/jsonql-errors/src/client-errors-handler.js","../node_modules/jsonql-utils/src/contract.js","../node_modules/nb-event-service/src/hash-code.js","../src/utils.js","../node_modules/jwt-decode/lib/atob.js","../node_modules/jsonql-params-validator/src/string.js","../node_modules/jsonql-jwt/src/client/decode-token/decode-token.js","../node_modules/jsonql-params-validator/src/number.js","../node_modules/jsonql-params-validator/src/boolean.js","../node_modules/jsonql-params-validator/src/any.js","../node_modules/jsonql-params-validator/src/constants.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/_listCacheClear.js","../node_modules/lodash-es/eq.js","../node_modules/lodash-es/_stackDelete.js","../node_modules/lodash-es/_stackGet.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-params-validator/src/validator.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/negate.js","../node_modules/lodash-es/_baseFindKey.js","../node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-params-validator/src/options/check-options-async.js","../node_modules/jsonql-params-validator/src/options/construct-config.js","../node_modules/jsonql-params-validator/src/options/index.js","../node_modules/jsonql-params-validator/index.js","../node_modules/jsonql-utils/src/timestamp.js","../node_modules/store/plugins/defaults.js","../src/stores/local-store.js","../src/stores/session-store.js","../src/stores/index.js","../node_modules/jsonql-utils/src/params-api.js","../node_modules/jsonql-utils/src/results.js","../src/base/store-cls.js","../src/base/http-cls.js","../src/base/contract-cls.js","../src/base/auth-cls.js","../src/base/base-cls.js","../src/base/index.js","../src/core/methods-generator.js","../src/core/jsonql-api-generator.js","../src/options/base-options.js","../src/options/check-options-async.js","../src/options/index.js","../src/jsonql-async.js","../node_modules/nb-event-service/src/suspend.js","../node_modules/nb-event-service/src/store-service.js","../node_modules/nb-event-service/src/event-service.js","../node_modules/nb-event-service/index.js","../src/ee.js","../index.js","../full.js"],"sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length;\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg];\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @return {*} json object on success\n */\nconst parse = function(n) {\n try {\n return JSON.parse(n)\n } catch(e) {\n return n;\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false;\n /*\n console.info('obj', obj)\n console.error(e)\n throw new Error(e)\n */\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = (n) => {\n if (typeof n === 'string') {\n return parse(n)\n }\n return JSON.parse(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== '';\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n","/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error)\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","/**\n * This is a custom error to throw when could not find the resolver\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class JsonqlResolverNotFoundError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlResolverNotFoundError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlResolverNotFoundError);\n }\n }\n\n static get statusCode() {\n return 404;\n }\n\n static get name() {\n return 'JsonqlResolverNotFoundError';\n }\n}\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError);\n }\n }\n\n static get name() {\n return 'JsonqlEnumError';\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlTypeError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError);\n }\n }\n\n static get name() {\n return 'JsonqlTypeError';\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args)\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError)\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError';\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError';\n }\n}\n","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message)\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// server side\nimport Jsonql406Error from './406-error'\nimport Jsonql500Error from './500-error'\n\nimport JsonqlForbiddenError from './forbidden-error'\nimport JsonqlAuthorisationError from './authorisation-error'\nimport JsonqlContractAuthError from './contract-auth-error'\nimport JsonqlResolverAppError from './resolver-app-error'\nimport JsonqlResolverNotFoundError from './resolver-not-found-error'\n\n// check options error\nimport JsonqlEnumError from './enum-error'\nimport JsonqlTypeError from './type-error'\nimport JsonqlCheckerError from './checker-error'\n// share\nimport JsonqlValidationError from './validation-error'\nimport JsonqlError from './error'\n\nimport JsonqlServerError from './server-error'\n\nexport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlForbiddenError,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n};\n","// this will add directly to the then call in each http call\n\nimport * as errors from './index'\nimport getErrorByStatus from './get-error-by-status'\nimport { NO_ERROR_MSG } from 'jsonql-constants'\nconst { JsonqlError } = errors\n\n/**\n * We can not just check something like result.data what if the result if false?\n * @param {object} obj the result object\n * @param {string} key we want to check if its exist or not\n * @return {boolean} true on found\n */\nconst isObjectHasKey = (obj, key) => {\n const keys = Object.keys(obj)\n return !!keys.filter(k => key === k).length;\n}\n\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nexport default function clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n","// split the contract into the node side and the generic side\nimport { isObjectHasKey } from './generic'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n SOCKET_NAME,\n QUERY_ARG_NAME,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlResolverNotFoundError } from 'jsonql-errors'\n/**\n * Check if the json is a contract file or not\n * @param {object} contract json object\n * @return {boolean} true\n */\nexport function checkIsContract(contract) {\n return isPlainObject(contract)\n && (\n isObjectHasKey(contract, QUERY_NAME)\n || isObjectHasKey(contract, MUTATION_NAME)\n || isObjectHasKey(contract, SOCKET_NAME)\n )\n}\n\n/**\n * Wrapper method that check if it's contract then return the contract or false\n * @param {object} contract the object to check\n * @return {boolean | object} false when it's not\n */\nexport function isContract(contract) {\n return checkIsContract(contract) ? contract : false;\n}\n\n/**\n * Ported from jsonql-params-validator but different\n * if we don't find the socket part then return false\n * @param {object} contract the contract object\n * @return {object|boolean} false on failed\n */\nexport function extractSocketPart(contract) {\n if (isObjectHasKey(contract, 'socket')) {\n return contract.socket;\n }\n return false;\n}\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @param {boolean} [fallback=false] this is a fall back option for old code\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport function groupByNamespace(contract, fallback = false) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n if (fallback) {\n return contract; // just return the whole contract\n }\n throw new JsonqlError(`socket not found in contract!`)\n }\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\n}\n\n/**\n * @NOTE ported from jsonql-ws-client\n * Got to make sure the connection order otherwise\n * it will hang\n * @param {object} nspSet contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspSet, publicNamespace) {\n let names = []; // need to make sure the order!\n for (let namespace in nspSet) {\n if (namespace === publicNamespace) {\n names[1] = namespace;\n } else {\n names[0] = namespace;\n }\n }\n return names;\n}\n\n\n/**\n * Extract the args from the payload\n * @param {object} payload to work with\n * @param {string} type of call\n * @return {array} args\n */\nexport function extractArgsFromPayload(payload, type) {\n switch (type) {\n case QUERY_NAME:\n return payload[QUERY_ARG_NAME];\n case MUTATION_NAME:\n return [\n payload[PAYLOAD_PARAM_NAME],\n payload[CONDITION_PARAM_NAME]\n ];\n default:\n throw new JsonqlError(`Unknown ${type} to extract argument from!`)\n }\n}\n\n/**\n * Like what the name said\n * @param {object} contract the contract json\n * @param {string} type query|mutation\n * @param {string} name of the function\n * @return {object} the params part of the contract\n */\nexport function extractParamsFromContract(contract, type, name) {\n try {\n const result = contract[type][name];\n // debug('extractParamsFromContract', result)\n if (!result) {\n // debug(name, type, contract)\n throw new JsonqlResolverNotFoundError(name, type)\n }\n return result;\n } catch(e) {\n throw new JsonqlResolverNotFoundError(name, e)\n }\n}\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport default function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n","// take only the module part which is what we use here\n// and export it again to use through out the client\n// this way we avoid those that we don't want node.js module got build into the code\nimport { isContract } from 'jsonql-utils/src/contract'\nimport hashCodeFn from 'nb-event-service/src/hash-code'\n/**\n * @param {object} jsonqlInstance the init instance of jsonql client\n * @param {object} contract the static contract\n * @return {object} contract may be from server\n */\nconst getContractFromConfig = function(jsonqlInstance, contract = {}) {\n if (isContract(contract)) {\n return Promise.resolve(contract)\n }\n return jsonqlInstance.getContract()\n}\n// wrapper method to make sure it's a string\nconst hashCode = str => hashCodeFn(str) + ''\n\n// simple util to check if an object has any properties\n// const hasProp = obj => isObject(obj) && Object.keys(obj).length\n\n// export some constants as well\n// since it's only use here there is no point of adding it to the constants module\n// or may be we add it back later\nconst ENDPOINT_TABLE = 'endpoint' // not in use anymore delete later @TODO\nconst USERDATA_TABLE = 'userdata'\nconst CLS_LOCAL_STORE_NAME = 'localStore'\nconst CLS_SESS_STORE_NAME = 'sessionStore'\nconst CLS_CONTRACT_NAME = 'contract'\nconst CLS_PROFILE_IDX = 'prof_idx'\nconst LOG_ERROR_SWITCH = '__error__'\nconst ZERO_IDX = 0\n// export\nexport {\n hashCode,\n getContractFromConfig,\n ENDPOINT_TABLE,\n USERDATA_TABLE,\n CLS_LOCAL_STORE_NAME,\n CLS_SESS_STORE_NAME,\n CLS_CONTRACT_NAME,\n CLS_PROFILE_IDX,\n LOG_ERROR_SWITCH,\n ZERO_IDX\n}\n","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\nfunction polyfill (input) {\n var str = String(input).replace(/=+$/, '');\n if (str.length % 4 == 1) {\n throw new InvalidCharacterError(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = '';\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n return output;\n}\n\n\nmodule.exports = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill;\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false;\n}\n\nexport default checkIsString\n","// when the user is login with the jwt\n// we use call this to decode the token and then add the payload\n// to the resolver so the user can call ResolverName.userdata\n// and get back the payload\nimport jwt_decode from 'jwt-decode'\nimport isString from 'jsonql-params-validator/src/string'\nimport JsonqlError from 'jsonql-errors/src/error'\n\nconst timestamp = function (sec = false) {\n var time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n\n/**\n * We only check the nbf and exp\n * @param {object} token for checking\n * @return {object} token on success\n */\nfunction validate(token) {\n const start = token.iat || timestamp(true)\n // we only check the exp for the time being\n if (token.exp) {\n if (start >= token.exp) {\n const expired = new Date(token.exp).toISOString()\n throw new JsonqlError(`Token has expired on ${expired}`, token)\n }\n }\n return token;\n}\n\n/**\n * The browser client version it has far fewer options and it doesn't verify it\n * because it couldn't this is the job for the server\n * @TODO we need to add some extra proessing here to check for the exp field\n * @param {string} token to decrypted\n * @return {object} decrypted object\n */\nexport default function jwtDecode(token) {\n if (isString(token)) {\n const t = jwt_decode(token)\n return validate(t)\n }\n throw new JsonqlError('Token must be a string!')\n}\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nexport const ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\n","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber;\n case STRING_TYPE:\n return checkIsString;\n case BOOLEAN_TYPE:\n return checkIsBoolean;\n default:\n return checkIsAny;\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false;\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false;\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p;\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length;\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length;\n}\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport filter from 'lodash-es/filter'\n\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true;\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (_value !== undefined) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true;\n }).length)\n }).length;\n }\n }\n return false;\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p;\n let _args = [arg];\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return Reflect.apply(checkIsObject, null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\n\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n checkIsObject,\n combineFn,\n notEmpty\n} from './index'\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params;\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false;\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (arg !== undefined) {\n return arg;\n }\n return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ))\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ))\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ))\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length:\n let ctn = params.length;\n // this happens when we have those array. type\n let _type = [ DEFAULT_TYPE ]\n // we only looking at the first one, this might be a @BUG\n /*\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n } */\n // if we use the params as guide then the rest will get throw out\n // which is not what we want, instead, anything without the param\n // will get a any type and optional flag\n return args.map((arg, i) => {\n let optional = i >= ctn ? true : !!params[i].optional\n let param = params[i] || { type: _type, name: `_${i}` }\n return {\n arg: optional ? getOptionalValue(arg, param) : arg,\n index: i,\n param,\n optional\n }\n })\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n // v1.4.4 this fixed the problem, the root level optional is from the last fn\n if (p.optional === true || p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length;\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport isFunction from 'lodash-es/isFunction'\nimport merge from 'lodash-es/merge'\nimport mapValues from 'lodash-es/mapValues'\n\nimport JsonqlEnumError from 'jsonql-errors/src/enum-error'\nimport JsonqlTypeError from 'jsonql-errors/src/type-error'\nimport JsonqlCheckerError from 'jsonql-errors/src/checker-error'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true;\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // log('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n // log(ENUM_KEY, value[ENUM_KEY])\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n // log(CHECKER_KEY, value[CHECKER_KEY])\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args;\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","/// this is port back from the client to share across all projects\n\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:check-options-async')\n\n/**\n * Quick transform\n * @param {object} config that one\n * @param {object} appProps mutation configuration options\n * @return {object} put that arg into the args\n */\nconst configToArgs = (config, appProps) => {\n return Promise.resolve(\n prepareArgsForValidation(config, appProps)\n )\n}\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return configToArgs(config, appProps)\n .then(args1 => runValidation(args1, cb))\n // next if every thing good then pass to final merging\n .then(args2 => merge({}, args2, constProps))\n}\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\nimport checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n };\n if (optional === true) {\n base[OPTIONAL_KEY] = true;\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv;\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker;\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias;\n }\n return base;\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__';\n\n/**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n checkConfigAsync,\n checkConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nexport const inArray = isInArray;\nexport const isObjectHasKey = isObjectHasKeyFn;\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n","module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n","// sort of persist on the user side\nimport engine from 'store/src/store-engine'\n\nimport localStorage from 'store/storages/localStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// @1.5.0 stop using the expired plugin, and deal with it ourself\n// import expiredPlugin from 'store/plugins/expire'\nimport eventsPlugin from 'store/plugins/events'\nimport compressionPlugin from 'store/plugins/compression'\n\nconst storages = [localStorage, cookieStorage]\nconst plugins = [defaultPlugin, eventsPlugin, compressionPlugin]\n\nconst localStore = engine.createStore(storages, plugins)\n\nexport default localStore\n","// session store with watch\nimport engine from 'store/src/store-engine'\n\nimport sessionStorage from 'store/storages/sessionStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// start using compression in 1.5.0 \nimport compressionPlugin from 'store/plugins/compression'\n// @1.5.0 stop using the expired plugin and deal it ourself\n// import expiredPlugin from 'store/plugins/expire'\n\nconst storages = [sessionStorage, cookieStorage]\nconst plugins = [defaultPlugin, compressionPlugin]\n\nconst sessionStore = engine.createStore(storages, plugins)\n\nexport default sessionStore\n","// export store interface\n// @TODO need to figure out how to make this as a outside dependencies instead of built into it\nimport localStoreEngine from './local-store'\nimport sessionStoreEngine from './session-store'\n\n// export back the raw version for development purposes\nexport const localStore = localStoreEngine\nexport const sessionStore = sessionStoreEngine\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport isString from 'lodash-es/isString'\n\nimport { timestamp } from './timestamp'\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? JSON.parse(payload) : payload;\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName\n * @param {*} payload\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload) {\n return {\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload;\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload;\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getNameFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: payload[TIMESTAMP_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// break up from node-middleware\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n API_REQUEST_METHODS,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME ,\n QUERY_ARG_NAME,\n DATA_KEY,\n ERROR_KEY,\n INDEX_KEY,\n EXT,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport { isObjectHasKey } from './generic'\nimport { timestamp } from './timestamp'\nimport isArray from 'lodash-es/isArray'\nimport merge from 'lodash-es/merge'\n/**\n * getting what is calling after the above check\n * @param {string} method of call\n * @return {mixed} false on failed\n */\nexport const getCallMethod = method => {\n const [ POST, PUT ] = API_REQUEST_METHODS;\n switch (true) {\n case method === POST:\n return QUERY_NAME;\n case method === PUT:\n return MUTATION_NAME;\n default:\n return false;\n }\n}\n\n/**\n * wrapper method\n * @param {mixed} result of fn return\n * @param {boolean|array} [ts=false] when pass this then we append a new value to the end\n * @return {string} stringify data\n */\nexport const packResult = function(result, ts = false) {\n let payload = { [DATA_KEY]: result }\n if (ts && isArray(ts)) {\n ts.push(timestamp())\n payload[TIMESTAMP_PARAM_NAME] = ts\n }\n return JSON.stringify(payload)\n}\n\n/**\n * Check if the error object contain out custom key\n * @param {*} e object\n * @return {boolean} true\n */\nexport const isJsonqlErrorObj = e => {\n const searchFields = ['detail', 'className']\n const test = !!searchFields.filter(field => isObjectHasKey(e, field)).length\n if (test) {\n return ['className', 'message', 'statusCode']\n .filter(field => isObjectHasKey(e, field))\n .map(field => (\n {\n [field]: typeof e[field] === 'object' ? e[field].toString() : e[field]\n }\n ))\n .reduce(merge, {detail: e.toString()}) // can only get as much as possible\n }\n return false;\n}\n\n/**\n * wrapper method - the output is trying to match up the structure of the Error sub class\n * @param {mixed} detail of fn error\n * @param {string} [className=JsonqlError] the errorName\n * @param {number} [statusCode=500] the original error code\n * @return {string} stringify error\n */\nexport const packError = function(detail, className = 'JsonqlError', statusCode = 0, message = '') {\n let errorObj = { detail, className, statusCode, message }\n // we need to check the detail object to see if it has detail, className and message\n // if it has then we should merge the object instead\n return JSON.stringify({\n [ERROR_KEY]: isJsonqlErrorObj(detail) || errorObj,\n [TIMESTAMP_PARAM_NAME]: timestamp()\n })\n}\n\n// ported from http-client\n\n/**\n * handle the return data\n * @TODO how to handle the return timestamp and calculate the diff?\n * @param {object} result return from server\n * @return {object} strip the data part out, or if the error is presented\n */\nexport const resultHandler = result => (\n (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result\n)\n","// new 1.5.0\n// create a class method to handle all the saving and retriving data\n// using the instanceKey to id the data hence allow to use multiple instance\nimport merge from 'lodash-es/merge'\nimport { localStore, sessionStore } from '../stores'\nimport { CLS_SESS_STORE_NAME, CLS_LOCAL_STORE_NAME, hashCode } from '../utils'\n\n// this becomes the base class instead of the HttpCls\nexport default class StoreClass {\n\n constructor(opts) {\n this.opts = opts\n // make it a string\n this.instanceKey = hashCode(this.opts.hostname)\n // pass this store for use later\n this.localStore = localStore\n this.sessionStore = sessionStore\n /*\n if (this.opts.debugOn) { // reuse this to clear out the data\n this.log('clear all stores')\n localStore.clearAll()\n sessionStore.clearAll()\n\n localStore.set('TEST', Date.now())\n sessionStore.set('TEST', Date.now())\n }\n */\n }\n // store in local storage id by the instanceKey\n // values should be an object so with key so we just merge\n // into the existing store without going through the keys\n __setMethod(storeType, values) {\n let store = this[storeType]\n let data = this.__getMethod(storeType)\n const skey = this.opts.storageKey\n const ikey = this.instanceKey\n store.set(skey, {\n [ikey]: data ? merge({}, data, values) : values\n })\n }\n // return the data id by the instaceKey\n __getMethod(storeType) {\n let store = this[storeType]\n let data = store.get(this.opts.storageKey)\n return data ? data[this.instanceKey] : false\n }\n // remove from local store id by instanceKey\n __delMethod(storeType, key) {\n let data = this.__getMethod(storeType)\n if (data) {\n let store = {}\n for (let k in data) {\n if (k !== key) {\n store[k] = data[k]\n }\n }\n this.__setMethod(storeType, store)\n }\n }\n // clear everything by this instanceKey\n __clearMethod(storeKey) {\n const skey = this.opts.storageKey\n const store = this[storeKey]\n let data = store.get(skey)\n if (data) {\n let _store = {}\n for (let k in data) {\n if (k !== this.instanceKey) {\n _store[k] = data[k]\n }\n }\n store.set(skey, _store)\n }\n }\n // Alias for different store\n set lset(values) {\n return this.__setMethod(CLS_LOCAL_STORE_NAME, values)\n }\n\n get lget() {\n return this.__getMethod(CLS_LOCAL_STORE_NAME)\n }\n\n ldel(key) {\n return this.__delMethod(CLS_LOCAL_STORE_NAME, key)\n }\n\n lclear() {\n return this.__clearMethod(CLS_LOCAL_STORE_NAME)\n }\n\n // store in session store id by the instanceKey\n set sset(values) {\n // this.log('--- sset ---', values)\n return this.__setMethod(CLS_SESS_STORE_NAME, values)\n }\n\n get sget() {\n return this.__getMethod(CLS_SESS_STORE_NAME)\n }\n\n sdel(key) {\n return this.__delMethod(CLS_SESS_STORE_NAME, key)\n }\n\n sclear() {\n return this.__clearMethod(CLS_SESS_STORE_NAME)\n }\n\n\n}\n","// base HttpClass\nimport merge from 'lodash-es/merge'\nimport {\n createQuery,\n createMutation,\n getNameFromPayload\n} from 'jsonql-utils/src/params-api'\nimport { cacheBurst, urlParams } from 'jsonql-utils/src/urls'\nimport { resultHandler } from 'jsonql-utils/src/results'\nimport { isObject, isString } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlServerError,\n JsonqlError,\n clientErrorsHandler\n} from 'jsonql-errors'\nimport {\n API_REQUEST_METHODS,\n DEFAULT_HEADER,\n JSONP_CALLBACK_NAME,\n SHOW_CONTRACT_DESC_PARAM\n} from 'jsonql-constants'\nimport { LOG_ERROR_SWITCH } from '../utils'\n\n// extract the one we need\nconst [ POST, PUT ] = API_REQUEST_METHODS\n\nimport StoreClass from './store-cls'\n\nexport default class HttpClass extends StoreClass {\n /**\n * The opts has been check at the init stage\n * @param {object} opts configuration options\n */\n constructor(opts) {\n super(opts)\n // change the way how we init Fly\n // flyio now become external depedencies and it makes it easier to switch\n // @BUG should we run test to check if we have the windows object?\n // this.log(opts)\n // this.fly = opts.Fly ? new opts.Fly() : new Fly()\n // to a different environment like WeChat mini app\n\n this.extraHeader = {};\n // @1.2.1 for adding query to the call on the fly\n this.extraParams = {};\n // this.log('start up opts', opts);\n this.reqInterceptor()\n this.resInterceptor()\n }\n\n // set headers for that one call\n set headers(header) {\n this.extraHeader = header;\n }\n\n /**\n * Create the reusage request method\n * @param {object} payload jsonql payload\n * @param {object} options extra options add the request\n * @param {object} headers extra headers add to the call\n * @return {object} the fly request instance\n */\n request(payload, options = {}, headers = {}) {\n this.headers = headers;\n let params = merge({}, cacheBurst(), this.extraParams)\n // @TODO need to add a jsonp url and payload\n if (this.opts.enableJsonp) {\n let resolverName = getNameFromPayload(payload)\n params = merge({}, params, {[JSONP_CALLBACK_NAME]: resolverName})\n payload = payload[resolverName]\n }\n // double up the url param and see what happen @TODO remove later\n const reqParams = merge({}, { method: POST, params }, options)\n this.log('request params', reqParams, this.jsonqlEndpoint)\n\n return this.fly.request(this.jsonqlEndpoint, payload, reqParams)\n }\n\n /**\n * This will replace the create baseRequest method\n *\n */\n reqInterceptor() {\n this.fly.interceptors.request.use(\n req => {\n const headers = this.getHeaders()\n this.log('request interceptor call', headers)\n\n for (let key in headers) {\n req.headers[key] = headers[key]\n }\n return req;\n }\n )\n }\n\n // @TODO\n processJsonp(result) {\n return resultHandler(result)\n }\n\n /**\n * This will be replacement of the first then call\n *\n */\n resInterceptor() {\n const self = this;\n const jsonp = self.opts.enableJsonp;\n this.fly.interceptors.response.use(\n res => {\n this.log('response interceptor call', res)\n self.cleanUp()\n // now more processing here\n // there is a problem if we throw the result.error here\n // the original data is lost, so we need to do what we did before\n // deal with that error in the first then instead\n const result = isString(res.data) ? JSON.parse(res.data) : res.data;\n if (jsonp) {\n return self.processJsonp(result)\n }\n return resultHandler(result)\n },\n // this get call when it's not 200\n err => {\n self.cleanUp()\n this.log(LOG_ERROR_SWITCH, err)\n throw new JsonqlServerError('Server side error', err)\n }\n )\n }\n\n /**\n * Get the headers inject into the call\n * @return {object} headers\n */\n getHeaders() {\n if (this.opts.enableAuth) {\n return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader)\n }\n return merge({}, DEFAULT_HEADER, this.extraHeader)\n }\n\n /**\n * Post http call operation to clean up things we need\n */\n cleanUp() {\n this.extraHeader = {}\n this.extraParams = {}\n }\n\n /**\n * GET for contract only\n * @return {promise} resolve the contract\n */\n getRemoteContract() {\n if (this.opts.showContractDesc) {\n this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM)\n }\n return this.request({}, {method: 'GET'}, this.contractHeader)\n .then(clientErrorsHandler)\n .then(result => {\n this.log('get contract result', result)\n // when refresh the window the result is different!\n // @TODO need to check the Koa side about why is that\n // also it should set a flag if we want the description or not\n if (result.cache && result.contract) {\n return result.contract;\n }\n // just the normal result\n return result\n })\n .catch(err => {\n this.log(LOG_ERROR_SWITCH, 'getRemoteContract err', err)\n throw new JsonqlServerError('getRemoteContract', err)\n })\n }\n\n /**\n * POST to server - query\n * @param {object} name of the resolver\n * @param {array} args arguments\n * @return {object} promise resolve to the resolver return\n */\n query(name, args = []) {\n return this.request(createQuery(name, args))\n .then(clientErrorsHandler)\n }\n\n /**\n * PUT to server - mutation\n * @param {string} name of resolver\n * @param {object} payload what it said\n * @param {object} conditions what it said\n * @return {object} promise resolve to the resolver return\n */\n mutation(name, payload = {}, conditions = {}) {\n return this.request(createMutation(name, payload, conditions), {method: PUT})\n .then(clientErrorsHandler)\n }\n\n}\n","// all the contract related methods will be here\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { timestamp } from 'jsonql-utils/src/timestamp'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { ENDPOINT_TABLE, CLS_CONTRACT_NAME } from '../utils'\nimport { localStore } from '../stores'\nimport HttpClass from './http-cls'\n\n// export\nexport default class ContractClass extends HttpClass {\n\n constructor(opts) {\n super(opts)\n }\n\n /**\n * return the contract public api\n * @return {object} contract\n */\n getContract() {\n const contract = this.readContract()\n this.log('getContract first call', contract)\n return contract ? Promise.resolve(contract)\n : this.getRemoteContract().then(this.storeContract.bind(this))\n }\n\n /**\n * We are changing the way how to auth to get the contract.json\n * Instead of in the url, we will be putting that key value in the header\n * @return {object} header\n */\n get contractHeader() {\n let base = {};\n if (this.opts.contractKey !== false) {\n base[this.opts.contractKeyName] = this.opts.contractKey;\n }\n return base;\n }\n\n /**\n * Save the contract to local store\n * @param {object} contract to save\n * @return {object|boolean} false when its not a contract or contract on OK\n */\n storeContract(contract) {\n // first need to check if the contract is a contract\n if (!isContract(contract)) {\n throw new JsonqlValidationError(`Contract is malformed!`)\n }\n this.lset = {[CLS_CONTRACT_NAME]: contract}\n // return it\n this.log('storeContract return result', contract)\n return contract;\n }\n\n /**\n * return the contract from options or localStore\n * @return {object|boolean} false on not found\n */\n readContract() {\n let contract = isContract(this.opts.contract)\n if (contract !== false) {\n return contract;\n }\n let data = this.lget\n if (data) {\n return data[CLS_CONTRACT_NAME]\n }\n return false;\n }\n}\n","// this is the new auth class that integrate with the jsonql-jwt\n// all the auth related methods will be here\nimport { decodeToken } from 'jsonql-jwt/src/client'\nimport { isNumber } from 'jsonql-params-validator'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { CREDENTIAL_STORAGE_KEY, AUTH_HEADER, BEARER } from 'jsonql-constants'\nimport { CLS_PROFILE_IDX, ZERO_IDX, USERDATA_TABLE } from '../utils'\nimport ContractClass from './contract-cls'\n// export\nexport default class AuthClass extends ContractClass {\n\n constructor(opts) {\n super(opts)\n if (opts.enableAuth) {\n this.setDecoder = decodeToken;\n }\n }\n\n /**\n * for overwrite\n * @param {string} token stored token\n * @return {string} token\n */\n decoder(token) {\n return token;\n }\n\n /**\n * set the profile index\n * @param {number} idx\n */\n set profileIndex(idx) {\n const key = CLS_PROFILE_IDX\n if (isNumber(idx)) {\n this[key] = idx;\n if (this.opts.persistToken) {\n this.lset = {[key]: idx}\n }\n return;\n }\n throw new JsonqlValidationError('profileIndex', `Expect idx to be number but got ${typeof idx}`)\n }\n\n /**\n * get the profile index\n * @return {number} idx\n */\n get profileIndex() {\n const key = CLS_PROFILE_IDX\n if (this.opts.persistToken) {\n const data = this.lget;\n if (data[key]) {\n return data[key]\n }\n }\n return this[key] ? this[key] : ZERO_IDX\n }\n\n /**\n * Return the token from session store\n * @param {number} [idx=false] profile index\n * @return {string} token\n */\n rawAuthToken(idx = false) {\n if (idx !== false) {\n this.profileIndex = idx;\n }\n // this should return from the base\n return this.jsonqlToken; // see base-cls\n }\n\n /**\n * Setter to add a decoder when retrieve user token\n * @param {function} d a decoder\n */\n set setDecoder(d) {\n if (typeof d === 'function') {\n this.decoder = d;\n }\n }\n\n /**\n * getter to return the session or local store set method\n * @param {*} data to save\n * @return {object} set method\n */\n set saveProfile(data) {\n if (this.opts.persistToken) {\n // this.log('--- saveProfile lset ---', data)\n this.lset = data\n } else {\n // this.log('--- saveProfile sset ---', data)\n this.sset = data\n }\n }\n\n /**\n * getter to return the session or local store get method\n * @return {object} get method\n */\n get readProfile() {\n return this.opts.persistToken ? this.lget : this.sget\n }\n\n // these were in the base class before but it should be here\n /**\n * save token\n * @param {string} token to store\n * @return {string|boolean} false on failed\n */\n set jsonqlToken(token) {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n // @TODO also have to make sure the token is not already existed!\n let tokens = (data && data[key]) ? data[key] : []\n tokens.push(token)\n this.saveProfile = {[key]: tokens}\n // store the userdata\n this.jsonqlUserdata = this.decoder(token)\n }\n\n /**\n * Jsonql token getter\n * 1.5.1 each token associate with the same profileIndex\n * @return {string|boolean} false when failed\n */\n get jsonqlToken() {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex])\n return data[key][this.profileIndex]\n }\n return false\n }\n\n /**\n * this one will use the sessionStore\n * basically we hook this onto the token store and decode it to store here\n * we only store one decoded user data at a time, but the token can be multiple\n */\n set jsonqlUserdata(userdata) {\n this.sset = {[USERDATA_TABLE]: userdata}\n }\n\n /**\n * this one store in the session store\n * get login userdata decoded jwt\n * 1.5.1 each userdata associate with the same profileIndex\n * @return {object|null}\n */\n get jsonqlUserdata() {\n const data = this.sget\n return data ? data[USERDATA_TABLE] : false\n }\n\n /**\n * Construct the auth header\n * @return {object} header\n */\n getAuthHeader() {\n const token = this.jsonqlToken // only call the getter to get the default one\n return token ? {[this.opts.AUTH_HEADER]: `${BEARER} ${token}`} : {};\n }\n\n /**\n * return all the stored token and decode it\n * @param {number} [idx=false] profile index\n * @return {array|boolean|string} false not found or array\n */\n getProfiles(idx = false) {\n const self = this; // just in case the scope problem\n const data = self.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n if (idx !== false && isNumber(idx)) {\n return data[key][idx] || false\n }\n return data[key].map(self.decoder.bind(self))\n }\n return false\n }\n\n /**\n * call after the login\n * @param {string} token return from server\n * @return {object} decoded token to userdata object\n */\n postLoginAction(token) {\n this.jsonqlToken = token\n return token\n }\n\n /**\n * call after the logout @TODO\n */\n postLogoutAction(...args) {\n console.info(`postLogoutAction`, args)\n }\n}\n","// this the core of the internal storage management\nimport { CREDENTIAL_STORAGE_KEY } from 'jsonql-constants'\n// import { isObject, isArray } from 'jsonql-params-validator'\n// import { JsonqlValidationError } from 'jsonql-errors'\n// import { timestamp } from 'jsonql-utils/src/timestamp'\n// import { inArray } from 'jsonql-utils/src/generic'\nimport { USERDATA_TABLE, LOG_ERROR_SWITCH } from '../utils'\nimport AuthCls from './auth-cls'\n\n// This class will only focus on the storage system\nexport default class JsonqlBaseClient extends AuthCls {\n // change the order of the interface in 1.4.10 to match up the top level\n constructor(fly, opts) {\n // change at 1.4.10 pass it directly without init it\n this.fly = fly;\n super(opts)\n }\n\n /**\n * construct the end point\n * @return {string} the end point to call\n */\n get jsonqlEndpoint() {\n const baseUrl = this.opts.hostname || ''\n return [baseUrl, this.opts.jsonqlPath].join('/')\n }\n\n /**\n * simple log\n */\n log(...args) {\n if (this.opts.debugOn === true) {\n const fns = ['info', 'error']\n const idx = (args[0] === LOG_ERROR_SWITCH) ? 1 : 0\n Reflect.apply(console[fns[idx]], console, args.splice(0, idx))\n }\n }\n\n}\n","// export interface\n// @public\nimport JsonqlBaseClient from './base-cls'\n\nexport default JsonqlBaseClient\n","// breaking out the inner methods generator in here\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { LOGOUT_NAME, LOGIN_NAME, KEY_WORD } from 'jsonql-constants'\nimport { chainFns } from 'jsonql-utils/src/chain-fns'\nimport { injectToFn } from 'jsonql-utils/src/obj-define-props'\n\n/**\n * generate authorisation specific methods\n * @param {object} jsonqlInstance instance of this\n * @param {string} name of method\n * @param {object} opts configuration\n * @param {object} contract to match\n * @return {function} for use\n */\nconst authMethodGenerator = (jsonqlInstance, name, opts, contract) => {\n return (...args) => {\n const params = contract.auth[name].params;\n const values = params.map((p, i) => args[i])\n const header = args[params.length] || {};\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [name, values, header])\n )\n .catch(finalCatch)\n }\n}\n\n/**\n * Break up the different type each - create query methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let query = {}\n for (let queryFn in contract.query) {\n // to keep it clean we use a param to id the auth method\n // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn;\n // generate the query method\n query = injectToFn(query, queryFn, function queryFnHandler(...args) {\n const params = contract.query[queryFn].params;\n const _args = params.map((param, i) => args[i])\n // debug('query', queryFn, _params);\n // @TODO this need to change to a different way to add an extra header\n const header = {}\n // @TODO validate against the type\n return validateAsync(_args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [queryFn, _args, header])\n )\n .catch(finalCatch)\n })\n }\n obj.query = query;\n // create an alias to the helloWorld method\n obj.helloWorld = query.helloWorld;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create mutation methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let mutation = {}\n // process the mutation, the reason the mutation has a fixed number of parameters\n // there is only the payload, and conditions parameters\n // plus a header at the end\n for (let mutationFn in contract.mutation) {\n mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header = {}) {\n const args = [payload, conditions];\n const params = contract.mutation[mutationFn].params;\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .mutation\n .apply(jsonqlInstance, [mutationFn, payload, conditions, header])\n )\n .catch(finalCatch)\n })\n }\n obj.mutation = mutation;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create auth methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createAuthMethods = (obj, jsonqlInstance, ee, config, contract) => {\n if (config.enableAuth && contract.auth) {\n let auth = {} // v1.3.1 add back the auth prop name in contract\n const { loginHandlerName, logoutHandlerName } = config;\n if (contract.auth[loginHandlerName]) {\n // changing to the name the config specify\n auth[loginHandlerName] = function loginHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance))\n .then(token => {\n ee.$trigger(LOGIN_NAME, token)\n return token;\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) {\n auth[logoutHandlerName] = function logoutHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance))\n .then(r => {\n ee.$trigger(LOGOUT_NAME, r)\n return r;\n })\n }\n } else {\n auth[logoutHandlerName] = function logoutHandlerFn() {\n jsonqlInstance.postLogoutAction(KEY_WORD)\n ee.$trigger(LOGOUT_NAME, KEY_WORD)\n }\n }\n obj.auth = auth;\n }\n\n return obj;\n}\n\n/**\n * Here just generate the methods calls\n * @param {object} jsonqlInstance what it said\n * @param {object} ee event emitter\n * @param {object} config configuration\n * @param {object} contract the map\n * @return {object} with mapped methods\n */\nexport function methodsGenerator(jsonqlInstance, ee, config, contract) {\n let obj = {}\n const executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods)\n return executor(obj, jsonqlInstance, ee, config, contract)\n}\n","// Generate the resolver for developer to use\n\n// @TODO when enableAuth we need to add one extra check\n// before the resolver call make it to the core\n// which is checking the login state, if the developer\n// is calling a private method without logging in\n// then we should throw the JsonqlForbiddenError at this point\n// instead of making a round trip to the server\nimport { LOGOUT_NAME, ISSUER_NAME, KEY_WORD } from 'jsonql-constants'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\n\nimport { methodsGenerator } from './methods-generator'\n\n/**\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} config options\n * @param {object} contract the contract\n * @param {object} ee eventEmitter\n * @return {object} constructed functions call\n */\nconst generator = (jsonqlInstance, config, contract, ee) => {\n // V1.3.0 - now everything wrap inside this method\n let client = methodsGenerator(jsonqlInstance, ee, config, contract)\n // create the rest of the methods\n if (config.enableAuth) {\n /**\n * new method to allow retrieve the current login user data\n * @TODO allow to pass an id to switch to different userdata\n * @return {*} userdata\n */\n client.userdata = () => jsonqlInstance.jsonqlUserdata;\n // allow getting the token for valdiate agains the socket\n // if it's not require auth there is no point of calling getToken\n client.getToken = (idx = false) => jsonqlInstance.rawAuthToken(idx);\n // switch profile or read back what is the currenct index\n client.profileIndex = (idx = false) => {\n if (idx === false) {\n return jsonqlInstance.profileIndex\n }\n jsonqlInstance.profileIndex = idx\n }\n // new in 1.5.1 to return different profiles\n client.getProfiles = (idx = false) => jsonqlInstance.getProfiles(idx);\n }\n // this will pass to the ws-client if needed\n // client.eventEmitter = ee;\n // this will require a param\n if (config.exposeContract) {\n // 1.4.0 change from the get (raw) to the getContract cache and raw version\n client.getContract = () => jsonqlInstance.getContract()\n }\n // allow developer to access the store api\n if (config.exposeStore) {\n // @TODO in 1.5.2\n client.tmpSave = data => {}\n client.tmpGet = (key = false) => {}\n client.tmpDel = (key = false) => {}\n\n client.persistSave = data => {}\n client.persistGet = (key = false) => {}\n client.persistDel = (key = false) => {}\n }\n // this is for the ws to use later - but this could be dangerous because it's expose the internal\n client.eventEmitter = ee;\n client.version = '__VERSION__';\n // use this method then we can hook into the debugOn at the same time\n client.log = (...args) => Reflect.apply(jsonqlInstance.log, jsonqlInstance, ['[DEV DEBUG]'].concat(args))\n // output\n return client;\n}\n// export\nexport default generator\n","// all the client configuration options here\nimport {\n JSONQL_PATH,\n CONTENT_TYPE,\n BEARER,\n CLIENT_STORAGE_KEY,\n CLIENT_AUTH_KEY,\n CONTRACT_KEY_NAME,\n AUTH_HEADER,\n ISSUER_NAME,\n LOGOUT_NAME,\n BOOLEAN_TYPE,\n STRING_TYPE,\n NUMBER_TYPE,\n DEFAULT_HEADER\n} from 'jsonql-constants'\nimport { createConfig } from 'jsonql-params-validator'\nexport const constProps = {\n contract: false,\n MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong?\n CONTENT_TYPE,\n BEARER,\n AUTH_HEADER\n}\n\n// grab the localhost name and put into the hostname as default\nconst getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n return null\n }\n}\n\nexport const appProps = {\n\n hostname: createConfig(getHostName(), [STRING_TYPE]), // required the hostname\n jsonqlPath: createConfig(JSONQL_PATH, [STRING_TYPE]), // The path on the server\n\n loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]),\n logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]),\n // add to koa v1.3.0 - this might remove in the future\n enableJsonp: createConfig(false, [BOOLEAN_TYPE]),\n enableAuth: createConfig(false, [BOOLEAN_TYPE]),\n // enable useJwt by default @TODO replace with something else and remove them later\n useJwt: createConfig(true, [BOOLEAN_TYPE]),\n // when true then store infinity or pass a time in seconds then we check against\n // the token date of creation\n persistToken: createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE]),\n // the header\n // v1.2.0 we are using this option during the dev\n // so it won't save anything to the localstorage and fetch a new contract\n // whenever the browser reload\n useLocalstorage: createConfig(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage\n storageKey: createConfig(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage\n authKey: createConfig(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage\n contractExpired: createConfig(0, [NUMBER_TYPE]),// -1 always fetch contract,\n // 0 never expired,\n // > 0 then compare the timestamp with the current one to see if we need to get contract again\n // useful during development\n keepContract: createConfig(true, [BOOLEAN_TYPE]),\n exposeContract: createConfig(false, [BOOLEAN_TYPE]),\n exposeStore: createConfig(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn \n // @1.2.1 new option for the contract-console to fetch the contract with description\n showContractDesc: createConfig(false, [BOOLEAN_TYPE]),\n contractKey: createConfig(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this\n contractKeyName: createConfig(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs\n enableTimeout: createConfig(false, [BOOLEAN_TYPE]), // @TODO\n timeout: createConfig(5000, [NUMBER_TYPE]), // 5 seconds\n returnInstance: createConfig(false, [BOOLEAN_TYPE]),\n allowReturnRawToken: createConfig(false, [BOOLEAN_TYPE]),\n debugOn: createConfig(false, [BOOLEAN_TYPE])\n}\n","// we must ensure the user passing the correct options\n// therefore we need to validate against the properties as well\n\nimport { appProps, constProps } from './base-options'\nimport { checkConfigAsync } from 'jsonql-params-validator'\n\nexport default function checkOptionsAsync(config) {\n let { contract } = config;\n return checkConfigAsync(config, appProps, constProps)\n .then(opts => {\n opts.contract = contract;\n return opts;\n })\n}\n","// export interface\nimport checkOptionsAsyncLocal from './check-options-async'\nimport checkOptionsLocal from './check-options'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport { objHasProp } from 'jsonql-utils/src/obj-define-props'\n/**\n * 1.5.0 overload the orginal functions to pass over the check\n */\nfunction checkOptionsAsync(config) {\n return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsyncLocal(config)\n}\n\n// sync version without needing the promise\nfunction checkOptions(config) {\n return objHasProp(config, CHECKED_KEY) ? config : checkOptionsLocal(config)\n}\n\nexport {\n checkOptionsAsync,\n checkOptions\n}\n","// this is new for the flyio and normalize the name from now on\nimport JsonqlBaseClient from './base'\nimport generator from './core/jsonql-api-generator'\nimport { checkOptionsAsync } from './options'\nimport { getContractFromConfig } from './utils'\n\n/**\n * Main interface for jsonql fetch api\n * @param {object} ee EventEmitter\n * @param {object} config\n * @param {object} fly this is really pain in the backside ... long story\n * @return {object} jsonql client\n */\nexport default function(ee, config = {}, fly) {\n return checkOptionsAsync(config)\n .then(opts => (\n {\n baseClient: new JsonqlBaseClient(fly, opts),\n opts: opts\n }\n ))\n .then( ({baseClient, opts}) => (\n getContractFromConfig(baseClient, opts.contract)\n .then(contract => generator(baseClient, opts, contract, ee))\n )\n )\n}\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n\nexport default class SuspendClass {\n\n constructor() {\n // suspend, release and queue\n this.__suspend__ = null;\n this.queueStore = new Set()\n /*\n this.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n })\n */\n }\n\n /**\n * setter to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n set $suspend(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend__;\n this.__suspend__ = value;\n this.logger('($suspend)', `Change from ${lastValue} --> ${value}`)\n if (lastValue === true && value === false) {\n setTimeout(() => {\n this.release()\n }, 1)\n }\n } else {\n throw new Error(`$suspend only accept Boolean value!`)\n }\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {any} value\n * @return {Boolean} true when added or false when it's not\n */\n $queue(...args) {\n if (this.__suspend__ === true) {\n this.logger('($queue)', 'added to $queue', args)\n // there shouldn't be any duplicate ...\n this.queueStore.add(args)\n }\n return this.__suspend__;\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size;\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n release() {\n let size = this.queueStore.size\n this.logger('(release)', `Release was called ${size}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('queue', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport genHaskKey from './hash-code'\nimport SuspendClass from './suspend'\n\nexport default class NbEventServiceBase extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger;\n }\n this.keep = config.keep;\n // for the $done setter\n this.result = config.keep ? [] : null;\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (typeof e !== 'string') {\n this.logger('(validateEvt)', e)\n throw new Error(`event name must be string type!`)\n }\n })\n return true;\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n return true;\n }\n }\n throw new Error(`callback required to be function type!`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n const types = ['on', 'only', 'once', 'onlyOnce']\n return !!types.filter(t => type === t).length;\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run)', callback, payload, ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName]; // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger('(takeFromStore)', `has ${evt}`, content)\n store.delete(evt)\n return content;\n }\n return false;\n }\n throw new Error(`${storeName} is not supported!`)\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n let fnSet;\n if (store.has(evt)) {\n this.logger('(addToStore)', `${evt} existed`)\n fnSet = store.get(evt)\n } else {\n this.logger('(addToStore)', `create new Set for ${evt}`)\n // this is new\n fnSet = new Set()\n }\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args;\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger('(addToStore)', `insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(l => {\n let [hash,] = l;\n if (hash === args[0]) {\n return true;\n }\n return false;\n }).length;\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true;\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list;\n return type !== t;\n }).length;\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n this.logger('(checkTypeInLazyStore)', store)\n if (store) {\n return !!Array\n .from(store)\n .filter(l => {\n let [,,t] = l;\n return t !== type;\n }).length\n }\n return false;\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger('(addToNormalStore)', evt, type, 'try to add to normal store')\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n this.logger('(addToNormalStore)', `${type} can add to ${evt} normal store`)\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store;\n return size;\n }\n return false;\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store;\n return size;\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg];\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n return genHaskKey(fn.toString()) + '';\n }\n}\n","// The top level\nimport NbStoreService from './store-service'\n// export\nexport default class EventService extends NbStoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on';\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger('($on)', `${evt} callback is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger('($on)', `${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0;\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($on)`, `call run on ${evt}`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n return size;\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n const type = 'once';\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (lazyStoreContent === false) {\n this.logger('($once)', `${evt} not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, type, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger('($once)', `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'only';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($only)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($only)', `${evt} found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( l => {\n const [ payload, ctx, t ] = l;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($only)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n })\n }\n return added;\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD added in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'onlyOnce';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== 'onlyOnce') {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($onlyOnce)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added;\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {}\n */\n $replace(evt, callback, context = null, type = 'on') {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n this.logger(`($replace)`, evt, callback)\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0;\n // first check the normal store\n let nStore = this.normalStore;\n this.logger('($trigger)', 'normalStore', nStore)\n if (nStore.has(evt)) {\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n this.logger('($trigger)', evt, 'found; add to queue: ', added)\n if (added === true) {\n this.logger('($trigger)', evt, 'not executed. Exit now.')\n return false; // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length;\n let hasOnce = false;\n let hasOnly = false;\n for (let i=0; i < ctn; ++i) {\n ++found;\n // this.logger('found', found)\n let [ _, callback, ctx, type ] = nSet[i]\n this.logger(`($trigger)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\n if (type === 'once' || type === 'onlyOnce') {\n hasOnce = true;\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found;\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found;\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter around\n * @param {string} evt event name\n * @param {*} params pass to the callback\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, params, type = false, context = null) {\n let args = [evt, params, context, type]\n return Reflect.apply(this.$trigger, this, args)\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n let found = false;\n stores.forEach(store => {\n if (store.has(evt)) {\n found = true;\n this.logger('($off)', evt)\n store.delete(evt)\n }\n })\n return found;\n }\n\n /**\n * return all the listener from the event\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n this.validateEvt(evt)\n let store = this.normalStore;\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l;\n }\n let [key, callback, ] = l;\n return callback;\n })\n }\n return false;\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done)', 'value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value;\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n if (this.keep) {\n this.logger('(get $done)', this.result)\n return this.result[this.result.length - 1]\n }\n return this.result;\n }\n\n\n}\n","// default\nimport NBEventService from './src/event-service'\n\nexport default NBEventService\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// output\nexport default function(debugOn) {\n let logger = debugOn ? (...args) => {\n args.unshift('[NBS]')\n console.log.apply(null, args)\n }: undefined;\n return new NBEventService({ logger })\n}\n","// main export interface\nimport {\n jsonqlAsync,\n ee as getEventEmitter\n} from './src'\n/**\n * When pass a static contract then it return a static interface\n * otherwise it will become the async interface\n * @param {object} fly the http engine - already init object not the class!\n * @param {object} config configuration\n * @return {object} jsonqlClient\n */\nexport default function jsonqlClient(fly, config) {\n const ee = getEventEmitter(config.debugOn)\n return jsonqlAsync(ee, config, fly)\n}\n","// this one will bring the fly.js in\n// also the built jsonql-client.umd.js together\n// init it @TODO placeholder this Fly import and switch using the NODE_ENV\n// because we are going to create one for wechat and one for node\n\nimport Fly from 'flyio/dist/npm/fly'\nimport jsonqlClient from './index'\n\nexport default function(config = {}) {\n return jsonqlClient(new Fly(), config)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;CCAA;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;CCAA;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CCAA;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;CCAA;;;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"jsonql-client.umd.js","sources":["../node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"y88CAAA"} \ No newline at end of file diff --git a/packages/http-client/static.js b/packages/http-client/static.js index ae8b23c5..1a55e1c2 100644 --- a/packages/http-client/static.js +++ b/packages/http-client/static.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClientStatic=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b="onResult",_="onError",m=Array.isArray,w="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},j="object"==typeof w&&w&&w.Object===Object&&w,S="object"==typeof self&&self&&self.Object===Object&&self,O=j||S||Function("return this")(),k=O.Symbol,E=Object.prototype,A=E.hasOwnProperty,T=E.toString,x=k?k.toStringTag:void 0;var P=Object.prototype.toString;var q="[object Null]",C="[object Undefined]",$=k?k.toStringTag:void 0;function z(t){return null==t?void 0===t?C:q:$&&$ in Object(t)?function(t){var e=A.call(t,x),r=t[x];try{t[x]=void 0;var n=!0}catch(t){}var o=T.call(t);return n&&(e?t[x]=r:delete t[x]),o}(t):function(t){return P.call(t)}(t)}function N(t,e){return function(r){return t(e(r))}}var M=N(Object.getPrototypeOf,Object);function R(t){return null!=t&&"object"==typeof t}var F="[object Object]",I=Function.prototype,J=Object.prototype,U=I.toString,H=J.hasOwnProperty,L=U.call(Object);function D(t){if(!R(t)||z(t)!=F)return!1;var e=M(t);if(null===e)return!0;var r=H.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&U.call(r)==L}function K(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&tt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var gt=function(t){return m(t)?t:[t]},yt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},bt=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},_t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),mt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),xt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Pt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),qt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),Ct=Object.freeze({__proto__:null,Jsonql406Error:_t,Jsonql500Error:mt,JsonqlForbiddenError:wt,JsonqlAuthorisationError:jt,JsonqlContractAuthError:St,JsonqlResolverAppError:Ot,JsonqlResolverNotFoundError:kt,JsonqlEnumError:Et,JsonqlTypeError:At,JsonqlCheckerError:Tt,JsonqlValidationError:xt,JsonqlError:Pt,JsonqlServerError:qt}),$t=Pt,zt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function Nt(t){if(zt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&Ct[o])throw new Ct[r](i,a);throw new $t(i,a)}return t}var Mt=function(t){return!!m(t)||null!=t&&""!==vt(t)},Rt="[object Number]";function Ft(t){return function(t){return"number"==typeof t||R(t)&&z(t)==Rt}(t)&&t!=+t}var It="[object String]";function Jt(t){return"string"==typeof t||!m(t)&&R(t)&&z(t)==It}var Ut=function(t){return!Jt(t)&&!Ft(parseFloat(t))},Ht=function(t){return""!==vt(t)&&Jt(t)},Lt=function(t){return null!=t&&"boolean"==typeof t},Dt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==vt(t)&&(!1===e||!0===e&&null!==t)},Kt=s,Bt=f,Vt=l,Gt=p,Wt=h,Yt=d,Qt="continue",Xt=function(t){switch(t){case"number":return Ut;case"string":return Ht;case"boolean":return Lt;default:return Dt}},Zt=function(t,e){return void 0===e&&(e=""),!!m(t)&&(""===e||""===vt(e)||!(t.filter((function(t){return!Xt(e)(t)})).length>0))},te=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},ee=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!Xt(e)(t)})).length)})).length:e.length>e.filter((function(t){return!Zt(r,t)})).length};var re,ne=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[re?a:++n];if(!1===e(o[u],u,o))break}return t};var oe="[object Arguments]";function ie(t){return R(t)&&z(t)==oe}var ae=Object.prototype,ue=ae.hasOwnProperty,ce=ae.propertyIsEnumerable,se=ie(function(){return arguments}())?ie:function(t){return R(t)&&ue.call(t,"callee")&&!ce.call(t,"callee")};var fe="object"==typeof exports&&exports&&!exports.nodeType&&exports,le=fe&&"object"==typeof module&&module&&!module.nodeType&&module,pe=le&&le.exports===fe?O.Buffer:void 0,he=(pe?pe.isBuffer:void 0)||function(){return!1},de=9007199254740991,ve=/^(?:0|[1-9]\d*)$/;function ge(t,e){var r=typeof t;return!!(e=null==e?de:e)&&("number"==r||"symbol"!=r&&ve.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=ye}var _e={};_e["[object Float32Array]"]=_e["[object Float64Array]"]=_e["[object Int8Array]"]=_e["[object Int16Array]"]=_e["[object Int32Array]"]=_e["[object Uint8Array]"]=_e["[object Uint8ClampedArray]"]=_e["[object Uint16Array]"]=_e["[object Uint32Array]"]=!0,_e["[object Arguments]"]=_e["[object Array]"]=_e["[object ArrayBuffer]"]=_e["[object Boolean]"]=_e["[object DataView]"]=_e["[object Date]"]=_e["[object Error]"]=_e["[object Function]"]=_e["[object Map]"]=_e["[object Number]"]=_e["[object Object]"]=_e["[object RegExp]"]=_e["[object Set]"]=_e["[object String]"]=_e["[object WeakMap]"]=!1;var me,we="object"==typeof exports&&exports&&!exports.nodeType&&exports,je=we&&"object"==typeof module&&module&&!module.nodeType&&module,Se=je&&je.exports===we&&j.process,Oe=function(){try{var t=je&&je.require&&je.require("util").types;return t||Se&&Se.binding&&Se.binding("util")}catch(t){}}(),ke=Oe&&Oe.isTypedArray,Ee=ke?(me=ke,function(t){return me(t)}):function(t){return R(t)&&be(t.length)&&!!_e[z(t)]},Ae=Object.prototype.hasOwnProperty;function Te(t,e){var r=m(t),n=!r&&se(t),o=!r&&!n&&he(t),i=!r&&!n&&!o&&Ee(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},Ke.prototype.set=function(t,e){var r=this.__data__,n=Le(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var Be,Ve=O["__core-js_shared__"],Ge=(Be=/[^.]+$/.exec(Ve&&Ve.keys&&Ve.keys.IE_PROTO||""))?"Symbol(src)_1."+Be:"";var We=Function.prototype.toString;function Ye(t){if(null!=t){try{return We.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Qe=/^\[object .+?Constructor\]$/,Xe=Function.prototype,Ze=Object.prototype,tr=Xe.toString,er=Ze.hasOwnProperty,rr=RegExp("^"+tr.call(er).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function nr(t){return!(!$e(t)||function(t){return!!Ge&&Ge in t}(t))&&(Fe(t)?rr:Qe).test(Ye(t))}function or(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return nr(r)?r:void 0}var ir=or(O,"Map"),ar=or(Object,"create");var ur="__lodash_hash_undefined__",cr=Object.prototype.hasOwnProperty;var sr=Object.prototype.hasOwnProperty;var fr="__lodash_hash_undefined__";function lr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&mr?new yr:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=te(t))?!ee({arg:r},e):!Xt(t)(r))})).length)})).length}return!1},Un=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Jn,null,a);case"array"===t:return!Zt(e.arg);case!1!==(r=te(t)):return!ee(e,r);default:return!Xt(t)(e.arg)}},Hn=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Ln=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!Zt(e))throw new Pt("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!Zt(t))throw new Pt("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Hn(t,a):t,index:r,param:a,optional:i}}));default:throw new Pt("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Mt(e)&&!(r.type.length>r.type.filter((function(e){return Un(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Un(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Dn=function(){try{var t=or(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function Kn(t,e,r){"__proto__"==e&&Dn?Dn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function Bn(t,e,r){(void 0===r||He(t[e],r))&&(void 0!==r||e in t)||Kn(t,e,r)}var Vn="object"==typeof exports&&exports&&!exports.nodeType&&exports,Gn=Vn&&"object"==typeof module&&module&&!module.nodeType&&module,Wn=Gn&&Gn.exports===Vn?O.Buffer:void 0,Yn=Wn?Wn.allocUnsafe:void 0;function Qn(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new jr(n).set(new jr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var Xn=Object.create,Zn=function(){function t(){}return function(e){if(!$e(e))return{};if(Xn)return Xn(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function to(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var eo=Object.prototype.hasOwnProperty;function ro(t,e,r){var n=t[e];eo.call(t,e)&&He(n,r)&&(void 0!==r||e in t)||Kn(t,e,r)}var no=Object.prototype.hasOwnProperty;function oo(t){if(!$e(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=Pe(t),r=[];for(var n in t)("constructor"!=n||!e&&no.call(t,n))&&r.push(n);return r}function io(t){return Ie(t)?Te(t,!0):oo(t)}function ao(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=po)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(lo);function yo(t,e){return go(function(t,e,r){return e=fo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=fo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=bo.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!$e(r))return!1;var n=typeof e;return!!("number"==n?Ie(r)&&ge(e,r.length):"string"==n&&e in r)&&He(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,gt(t))}),Reflect.apply(t,null,r))}};function Lo(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function Do(t,e,r,n){void 0===n&&(n=!1);var o=Lo(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var Ko=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return Io(r,i).then((function(){return t.query.apply(t,[e,a,u])}))}},Bo=function(t,e,r,n,o){var i={},a=function(t){i=Do(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return Io(a,i).then((function(){return e.query.apply(e,[t,a,u])}))}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},Vo=function(t,e,r,n,o){var i={},a=function(t){i=Do(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return Io(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])}))}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Go=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Ko(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Ko(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var Wo=function(t,e){return function(r){for(var n=[],o=arguments.length-1;o-- >0;)n[o]=arguments[o+1];return new Promise((function(o,i){t.$only(bt(e,r,b),o),t.$only(bt(e,r,_),i),t.$trigger(e,{resolverName:r,args:n})}))}},Yo=function(t,e,r){var n=t.$queues,o=r.debugOn;o&&console.info("(validateRegisteredEvents)","storedEvt",n),n.forEach((function(t){var r=t[0],n=t[1].resolverName;if(o&&console.info("(validateRegisteredEvents)",r,n),!e[r][n])throw new Error(r+"."+n+" not existed in contract!")}))};function Qo(t,e,r,n){var o=function(t,e,r,n){return Ho(Bo,Vo,Go)({},t,e,r,n)}(t,e,r,n);Yo(e,n,r);var i=function(t){e.$only(t,(function(r){var n=r.resolverName,i=r.args;o[t][n]?Reflect.apply(o[t][n],null,i).then((function(r){e.$trigger(bt(t,n,b),r)})).catch((function(r){e.$trigger(bt(t,n,_),r)})):console.error(n+" is not defined in the contract!")}))};for(var a in o)i(a);setTimeout((function(){e.$suspend=!1}),1)}var Xo=function(t,e,r,n){n.$suspend=!0,r.then((function(r){Qo(t,n,e,r)}));var o={query:Wo(n,"query"),mutation:Wo(n,"mutation"),auth:Wo(n,"auth"),getToken:function(){return t.rawAuthToken}};return e.exposeContract&&(o.getContract=function(){return t.get()}),e.enableAuth&&(o.userdata=function(){return t.userdata}),o.version="1.5.1",o};function Zo(t){return!!function(t){return D(t)&&(yt(t,r)||yt(t,n)||yt(t,o))}(t)&&t}function ti(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var ei=function(t,e){return void 0===e&&(e={}),Zo(e)?Promise.resolve(e):t.getContract()},ri="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function ni(t){this.message=t}ni.prototype=new Error,ni.prototype.name="InvalidCharacterError";var oi="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new ni("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=ri.indexOf(n);return a};var ii=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(oi(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return oi(e)}};function ai(t){this.message=t}ai.prototype=new Error,ai.prototype.name="InvalidTokenError";var ui=function(t,e){if("string"!=typeof t)throw new ai("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(ii(t.split(".")[r]))}catch(t){throw new ai("Invalid token specified: "+t.message)}},ci=ai;ui.InvalidTokenError=ci;var si,fi,li,pi,hi,di,vi,gi,yi,bi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function _i(t){if(Ht(t))return function(t){var e=t.iat||bi(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Pt("Token has expired on "+r,t)}return t}(ui(t));throw new Pt("Token must be a string!")}Jo("HS256",["string"]),Jo(!1,["boolean","number","string"],((si={})[d]="exp",si[f]=!0,si)),Jo(!1,["boolean","number","string"],((fi={})[d]="nbf",fi[f]=!0,fi)),Jo(!1,["boolean","string"],((li={})[d]="iss",li[f]=!0,li)),Jo(!1,["boolean","string"],((pi={})[d]="sub",pi[f]=!0,pi)),Jo(!1,["boolean","string"],((hi={})[d]="iss",hi[f]=!0,hi)),Jo(!1,["boolean"],((di={})[f]=!0,di)),Jo(!1,["boolean","string"],((vi={})[f]=!0,vi)),Jo(!1,["boolean","string"],((gi={})[f]=!0,gi)),Jo(!1,["boolean"],((yi={})[f]=!0,yi));var mi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},wi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var ji=Object.assign?Object.assign:function(t,e,r,n){for(var o=arguments,i=1;i=0;e--){var r=Di().key(e);t(Ki(r),r)}},remove:function(t){return Di().removeItem(t)},clearAll:function(){return Di().clear()}};function Di(){return Hi.localStorage}function Ki(t){return Di().getItem(t)}var Bi=Ei.trim,Vi={name:"cookieStorage",read:function(t){if(!t||!Qi(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Gi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Gi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Wi,remove:Yi,clearAll:function(){Wi((function(t,e){Yi(e)}))}},Gi=Ei.Global.document;function Wi(t){for(var e=Gi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Bi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Yi(t){t&&Qi(t)&&(Gi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Qi(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Gi.cookie)}var Xi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var Zi=Ei.bind,ta=Ei.each,ea=Ei.create,ra=Ei.slice,na=function(){var t=ea(oa,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,Zi(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,Zi(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),ta(r,(function(e,r){t.fire(r,void 0,e)}))}}};var oa={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,Zi(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=ra(arguments,1);ta(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},ia=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),aa=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=ia.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=ia.compress(this._serialize(r));t(e,n)}}};var ua=[Li,Vi],ca=[Xi,na,aa],sa=Ii.createStore(ua,ca),fa=Ei.Global;function la(){return fa.sessionStorage}function pa(t){return la().getItem(t)}var ha=[{name:"sessionStorage",read:pa,write:function(t,e){return la().setItem(t,e)},each:function(t){for(var e=la().length-1;e>=0;e--){var r=la().key(e);t(pa(r),r)}},remove:function(t){return la().removeItem(t)},clearAll:function(){return la().clear()}},Vi],da=[Xi,aa],va=Ii.createStore(ha,da),ga=sa,ya=va,ba=function(t){var e;return(e={}).args=t,e};function _a(t,e){var r;return(r={})[t]=e,r[u]=[mi()],r}var ma=function(t){return yt(t,"data")&&!yt(t,"error")?t.data:t},wa=function(t){this.opts=t,this.instanceKey=ti(this.opts.hostname)+"",this.localStore=ga,this.sessionStore=ya},ja={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};wa.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?_o({},o,e):e,r))},wa.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},wa.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},wa.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},ja.lset.set=function(t){return this.__setMethod("localStore",t)},ja.lget.get=function(){return this.__getMethod("localStore")},wa.prototype.ldel=function(t){return this.__delMethod("localStore",t)},wa.prototype.lclear=function(){return this.__clearMethod("localStore")},ja.sset.set=function(t){return this.__setMethod("sessionStore",t)},ja.sget.get=function(){return this.__getMethod("sessionStore")},wa.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},wa.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(wa.prototype,ja);var Sa=c[0],Oa=c[1],ka=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=_i)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(Fo(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new xt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&Fo(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!Zo(t))throw new xt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=Zo(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=_o({},{_cb:mi()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=_o({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=_o({},{method:Sa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return ma(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=Ro(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):ma(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new qt("Server side error",r)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?_o({},e,this.getAuthHeader(),this.extraHeader):_o({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=_o({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(Nt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new qt("getRemoteContract",e)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Jt(t)&&m(e)){var n=ba(e);return!0===r?n:_a(t,n)}throw new xt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(Nt)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Jt(t))return _a(t,o);throw new xt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:Oa}).then(Nt)},Object.defineProperties(r.prototype,n),r}(wa)))),Ea={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Aa={hostname:Jo(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:Jo("jsonql",["string"]),loginHandlerName:Jo("login",["string"]),logoutHandlerName:Jo("logout",["string"]),enableJsonp:Jo(!1,["boolean"]),enableAuth:Jo(!1,["boolean"]),useJwt:Jo(!0,["boolean"]),persistToken:Jo(!1,["boolean","number"]),useLocalstorage:Jo(!0,["boolean"]),storageKey:Jo("jsonqlstore",["string"]),authKey:Jo("jsonqlauthkey",["string"]),contractExpired:Jo(0,["number"]),keepContract:Jo(!0,["boolean"]),exposeContract:Jo(!1,["boolean"]),exposeStore:Jo(!1,["boolean"]),showContractDesc:Jo(!1,["boolean"]),contractKey:Jo(!1,["boolean"]),contractKeyName:Jo("X-JSONQL-CV-KEY",["string"]),enableTimeout:Jo(!1,["boolean"]),timeout:Jo(5e3,["number"]),returnInstance:Jo(!1,["boolean"]),allowReturnRawToken:Jo(!1,["boolean"]),debugOn:Jo(!1,["boolean"])};function Ta(t){return Lo(t,v)?t:function(t){return Uo(t,Aa,Ea)}(t)}var xa=new WeakMap,Pa=new WeakMap,qa=function(){this.__suspend__=null,this.queueStore=new Set},Ca={$suspend:{configurable:!0},$queues:{configurable:!0}};Ca.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},qa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},Ca.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},qa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(qa.prototype,Ca);var $a=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){xa.set(this,t)},r.normalStore.get=function(){return xa.get(this)},r.lazyStore.set=function(t){Pa.set(this,t)},r.lazyStore.get=function(){return Pa.get(this)},e.prototype.hashFnToKey=function(t){return ti(t.toString())+""},Object.defineProperties(e.prototype,r),e}(qa));return function(t,e){void 0===e&&(e={});var r,n=e.contract,o=Ta(e),i=new ka(t,o),a=ei(i,n),u=(r=o.debugOn,new $a({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),c=Xo(i,o,a,u);return c.eventEmitter=u,c}})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlClientStatic=e()}(this,(function(){"use strict";var t="application/vnd.api+json",e={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},r="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",d="alias",v="__checked__",g={desc:"y"},y="No message",b="onResult",_="onError",m=Array.isArray,w="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},j="object"==typeof w&&w&&w.Object===Object&&w,S="object"==typeof self&&self&&self.Object===Object&&self,O=j||S||Function("return this")(),k=O.Symbol,E=Object.prototype,A=E.hasOwnProperty,T=E.toString,x=k?k.toStringTag:void 0;var P=Object.prototype.toString;var q="[object Null]",C="[object Undefined]",$=k?k.toStringTag:void 0;function z(t){return null==t?void 0===t?C:q:$&&$ in Object(t)?function(t){var e=A.call(t,x),r=t[x];try{t[x]=void 0;var n=!0}catch(t){}var o=T.call(t);return n&&(e?t[x]=r:delete t[x]),o}(t):function(t){return P.call(t)}(t)}function N(t,e){return function(r){return t(e(r))}}var M=N(Object.getPrototypeOf,Object);function R(t){return null!=t&&"object"==typeof t}var F="[object Object]",I=Function.prototype,J=Object.prototype,U=I.toString,H=J.hasOwnProperty,L=U.call(Object);function D(t){if(!R(t)||z(t)!=F)return!1;var e=M(t);if(null===e)return!0;var r=H.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&U.call(r)==L}function K(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&tt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var gt=function(t){return m(t)?t:[t]},yt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},bt=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},_t=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),mt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),wt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 403},r.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(e,r),e}(Error),jt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),St=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),Ot=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),kt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(Error),Et=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),At=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),Tt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),xt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Pt=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error),qt=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error),Ct=Object.freeze({__proto__:null,Jsonql406Error:_t,Jsonql500Error:mt,JsonqlForbiddenError:wt,JsonqlAuthorisationError:jt,JsonqlContractAuthError:St,JsonqlResolverAppError:Ot,JsonqlResolverNotFoundError:kt,JsonqlEnumError:Et,JsonqlTypeError:At,JsonqlCheckerError:Tt,JsonqlValidationError:xt,JsonqlError:Pt,JsonqlServerError:qt}),$t=Pt,zt=function(t,e){return!!Object.keys(t).filter((function(t){return e===t})).length};function Nt(t){if(zt(t,"error")){var e=t.error,r=e.className,n=e.name,o=r||n,i=e.message||y,a=e.detail||e;if(o&&Ct[o])throw new Ct[r](i,a);throw new $t(i,a)}return t}function Mt(t){if(Array.isArray(t))throw new xt("",t);var e=t.message||y,r=t.detail||t;switch(!0){case t instanceof _t:throw new _t(e,r);case t instanceof mt:throw new mt(e,r);case t instanceof wt:throw new wt(e,r);case t instanceof jt:throw new jt(e,r);case t instanceof St:throw new St(e,r);case t instanceof Ot:throw new Ot(e,r);case t instanceof kt:throw new kt(e,r);case t instanceof Et:throw new Et(e,r);case t instanceof At:throw new At(e,r);case t instanceof Tt:throw new Tt(e,r);case t instanceof xt:throw new xt(e,r);case t instanceof qt:throw new qt(e,r);default:throw new Pt(e,r)}}var Rt=function(t){return!!m(t)||null!=t&&""!==vt(t)},Ft="[object Number]";function It(t){return function(t){return"number"==typeof t||R(t)&&z(t)==Ft}(t)&&t!=+t}var Jt="[object String]";function Ut(t){return"string"==typeof t||!m(t)&&R(t)&&z(t)==Jt}var Ht=function(t){return!Ut(t)&&!It(parseFloat(t))},Lt=function(t){return""!==vt(t)&&Ut(t)},Dt=function(t){return null!=t&&"boolean"==typeof t},Kt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==vt(t)&&(!1===e||!0===e&&null!==t)},Bt=s,Vt=f,Gt=l,Wt=p,Yt=h,Qt=d,Xt="continue",Zt=function(t){switch(t){case"number":return Ht;case"string":return Lt;case"boolean":return Dt;default:return Kt}},te=function(t,e){return void 0===e&&(e=""),!!m(t)&&(""===e||""===vt(e)||!(t.filter((function(t){return!Zt(e)(t)})).length>0))},ee=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},re=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!Zt(e)(t)})).length)})).length:e.length>e.filter((function(t){return!te(r,t)})).length};var ne,oe=function(t,e,r){for(var n=-1,o=Object(t),i=r(t),a=i.length;a--;){var u=i[ne?a:++n];if(!1===e(o[u],u,o))break}return t};var ie="[object Arguments]";function ae(t){return R(t)&&z(t)==ie}var ue=Object.prototype,ce=ue.hasOwnProperty,se=ue.propertyIsEnumerable,fe=ae(function(){return arguments}())?ae:function(t){return R(t)&&ce.call(t,"callee")&&!se.call(t,"callee")};var le="object"==typeof exports&&exports&&!exports.nodeType&&exports,pe=le&&"object"==typeof module&&module&&!module.nodeType&&module,he=pe&&pe.exports===le?O.Buffer:void 0,de=(he?he.isBuffer:void 0)||function(){return!1},ve=9007199254740991,ge=/^(?:0|[1-9]\d*)$/;function ye(t,e){var r=typeof t;return!!(e=null==e?ve:e)&&("number"==r||"symbol"!=r&&ge.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=be}var me={};me["[object Float32Array]"]=me["[object Float64Array]"]=me["[object Int8Array]"]=me["[object Int16Array]"]=me["[object Int32Array]"]=me["[object Uint8Array]"]=me["[object Uint8ClampedArray]"]=me["[object Uint16Array]"]=me["[object Uint32Array]"]=!0,me["[object Arguments]"]=me["[object Array]"]=me["[object ArrayBuffer]"]=me["[object Boolean]"]=me["[object DataView]"]=me["[object Date]"]=me["[object Error]"]=me["[object Function]"]=me["[object Map]"]=me["[object Number]"]=me["[object Object]"]=me["[object RegExp]"]=me["[object Set]"]=me["[object String]"]=me["[object WeakMap]"]=!1;var we,je="object"==typeof exports&&exports&&!exports.nodeType&&exports,Se=je&&"object"==typeof module&&module&&!module.nodeType&&module,Oe=Se&&Se.exports===je&&j.process,ke=function(){try{var t=Se&&Se.require&&Se.require("util").types;return t||Oe&&Oe.binding&&Oe.binding("util")}catch(t){}}(),Ee=ke&&ke.isTypedArray,Ae=Ee?(we=Ee,function(t){return we(t)}):function(t){return R(t)&&_e(t.length)&&!!me[z(t)]},Te=Object.prototype.hasOwnProperty;function xe(t,e){var r=m(t),n=!r&&fe(t),o=!r&&!n&&de(t),i=!r&&!n&&!o&&Ae(t),a=r||n||o||i,u=a?function(t,e){for(var r=-1,n=Array(t);++r-1},Be.prototype.set=function(t,e){var r=this.__data__,n=De(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var Ve,Ge=O["__core-js_shared__"],We=(Ve=/[^.]+$/.exec(Ge&&Ge.keys&&Ge.keys.IE_PROTO||""))?"Symbol(src)_1."+Ve:"";var Ye=Function.prototype.toString;function Qe(t){if(null!=t){try{return Ye.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Xe=/^\[object .+?Constructor\]$/,Ze=Function.prototype,tr=Object.prototype,er=Ze.toString,rr=tr.hasOwnProperty,nr=RegExp("^"+er.call(rr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function or(t){return!(!ze(t)||function(t){return!!We&&We in t}(t))&&(Ie(t)?nr:Xe).test(Qe(t))}function ir(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return or(r)?r:void 0}var ar=ir(O,"Map"),ur=ir(Object,"create");var cr="__lodash_hash_undefined__",sr=Object.prototype.hasOwnProperty;var fr=Object.prototype.hasOwnProperty;var lr="__lodash_hash_undefined__";function pr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=r&wr?new br:void 0;for(i.set(t,e),i.set(e,t);++fe.type.filter((function(t){var e;return void 0===r||(!1!==(e=ee(t))?!re({arg:r},e):!Zt(t)(r))})).length)})).length}return!1},Hn=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Un,null,a);case"array"===t:return!te(e.arg);case!1!==(r=ee(t)):return!re(e,r);default:return!Zt(t)(e.arg)}},Ln=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Dn=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!te(e))throw new Pt("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!te(t))throw new Pt("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?Ln(t,a):t,index:r,param:a,optional:i}}));default:throw new Pt("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Rt(e)&&!(r.type.length>r.type.filter((function(e){return Hn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Hn(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Kn=function(){try{var t=ir(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function Bn(t,e,r){"__proto__"==e&&Kn?Kn(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}function Vn(t,e,r){(void 0===r||Le(t[e],r))&&(void 0!==r||e in t)||Bn(t,e,r)}var Gn="object"==typeof exports&&exports&&!exports.nodeType&&exports,Wn=Gn&&"object"==typeof module&&module&&!module.nodeType&&module,Yn=Wn&&Wn.exports===Gn?O.Buffer:void 0,Qn=Yn?Yn.allocUnsafe:void 0;function Xn(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new Sr(n).set(new Sr(r)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var Zn=Object.create,to=function(){function t(){}return function(e){if(!ze(e))return{};if(Zn)return Zn(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function eo(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ro=Object.prototype.hasOwnProperty;function no(t,e,r){var n=t[e];ro.call(t,e)&&Le(n,r)&&(void 0!==r||e in t)||Bn(t,e,r)}var oo=Object.prototype.hasOwnProperty;function io(t){if(!ze(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=qe(t),r=[];for(var n in t)("constructor"!=n||!e&&oo.call(t,n))&&r.push(n);return r}function ao(t){return Je(t)?xe(t,!0):io(t)}function uo(t){return function(t,e,r,n){var o=!r;r||(r={});for(var i=-1,a=e.length;++i0){if(++e>=ho)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(po);function bo(t,e){return yo(function(t,e,r){return e=lo(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=lo(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=_o.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!ze(r))return!1;var n=typeof e;return!!("number"==n?Je(r)&&ye(e,r.length):"string"==n&&e in r)&&Le(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,gt(t))}),Reflect.apply(t,null,r))}};function Do(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function Ko(t,e,r,n){void 0===n&&(n=!1);var o=Do(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}var Bo=function(t,e,r,n){return function(){for(var r=[],o=arguments.length;o--;)r[o]=arguments[o];var i=n.auth[e].params,a=i.map((function(t,e){return r[e]})),u=r[i.length]||{};return Jo(r,i).then((function(){return t.query.apply(t,[e,a,u])})).catch(Mt)}},Vo=function(t,e,r,n,o){var i={},a=function(t){i=Ko(i,t,(function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,e){return r[e]})),u={};return Jo(a,i).then((function(){return e.query.apply(e,[t,a,u])})).catch(Mt)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,e,r,n,o]},Go=function(t,e,r,n,o){var i={},a=function(t){i=Ko(i,t,(function(r,n,i){void 0===i&&(i={});var a=[r,n],u=o.mutation[t].params;return Jo(a,u).then((function(){return e.mutation.apply(e,[t,r,n,i])})).catch(Mt)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,e,r,n,o]},Wo=function(t,e,r,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Bo(e,a,0,o);return i.apply(null,t).then(e.postLoginAction.bind(e)).then((function(t){return r.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Bo(e,u,0,o);return i.apply(null,t).then(e.postLogoutAction.bind(e)).then((function(t){return r.$trigger("logout",t),t}))}:i[u]=function(){e.postLogoutAction("continue"),r.$trigger("logout","continue")},t.auth=i}return t};var Yo=function(t,e){return function(r){for(var n=[],o=arguments.length-1;o-- >0;)n[o]=arguments[o+1];return new Promise((function(o,i){t.$only(bt(e,r,b),o),t.$only(bt(e,r,_),i),t.$trigger(e,{resolverName:r,args:n})}))}},Qo=function(t,e,r){var n=t.$queues,o=r.debugOn;o&&console.info("(validateRegisteredEvents)","storedEvt",n),n.forEach((function(t){var r=t[0],n=t[1].resolverName;if(o&&console.info("(validateRegisteredEvents)",r,n),!e[r][n])throw new Error(r+"."+n+" not existed in contract!")}))};function Xo(t,e,r,n){var o=function(t,e,r,n){return Lo(Vo,Go,Wo)({},t,e,r,n)}(t,e,r,n);Qo(e,n,r);var i=function(t){e.$only(t,(function(r){var n=r.resolverName,i=r.args;o[t][n]?Reflect.apply(o[t][n],null,i).then((function(r){e.$trigger(bt(t,n,b),r)})).catch((function(r){e.$trigger(bt(t,n,_),r)})):console.error(n+" is not defined in the contract!")}))};for(var a in o)i(a);setTimeout((function(){e.$suspend=!1}),1)}var Zo=function(t,e,r,n){n.$suspend=!0,r.then((function(r){Xo(t,n,e,r)}));var o={query:Yo(n,"query"),mutation:Yo(n,"mutation"),auth:Yo(n,"auth"),getToken:function(){return t.rawAuthToken}};return e.exposeContract&&(o.getContract=function(){return t.get()}),e.enableAuth&&(o.userdata=function(){return t.userdata}),o.version="1.5.2",o};function ti(t){return!!function(t){return D(t)&&(yt(t,r)||yt(t,n)||yt(t,o))}(t)&&t}function ei(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}var ri=function(t,e){return void 0===e&&(e={}),ti(e)?Promise.resolve(e):t.getContract()},ni="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function oi(t){this.message=t}oi.prototype=new Error,oi.prototype.name="InvalidCharacterError";var ii="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new oi("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,o=0,i=0,a="";n=e.charAt(i++);~n&&(r=o%4?64*r+n:n,o++%4)?a+=String.fromCharCode(255&r>>(-2*o&6)):0)n=ni.indexOf(n);return a};var ai=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(ii(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return ii(e)}};function ui(t){this.message=t}ui.prototype=new Error,ui.prototype.name="InvalidTokenError";var ci=function(t,e){if("string"!=typeof t)throw new ui("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(ai(t.split(".")[r]))}catch(t){throw new ui("Invalid token specified: "+t.message)}},si=ui;ci.InvalidTokenError=si;var fi,li,pi,hi,di,vi,gi,yi,bi,_i=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function mi(t){if(Lt(t))return function(t){var e=t.iat||_i(!0);if(t.exp&&e>=t.exp){var r=new Date(t.exp).toISOString();throw new Pt("Token has expired on "+r,t)}return t}(ci(t));throw new Pt("Token must be a string!")}Uo("HS256",["string"]),Uo(!1,["boolean","number","string"],((fi={})[d]="exp",fi[f]=!0,fi)),Uo(!1,["boolean","number","string"],((li={})[d]="nbf",li[f]=!0,li)),Uo(!1,["boolean","string"],((pi={})[d]="iss",pi[f]=!0,pi)),Uo(!1,["boolean","string"],((hi={})[d]="sub",hi[f]=!0,hi)),Uo(!1,["boolean","string"],((di={})[d]="iss",di[f]=!0,di)),Uo(!1,["boolean"],((vi={})[f]=!0,vi)),Uo(!1,["boolean","string"],((gi={})[f]=!0,gi)),Uo(!1,["boolean","string"],((yi={})[f]=!0,yi)),Uo(!1,["boolean"],((bi={})[f]=!0,bi));var wi=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},ji="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var Si=Object.assign?Object.assign:function(t,e,r,n){for(var o=arguments,i=1;i=0;e--){var r=Ki().key(e);t(Bi(r),r)}},remove:function(t){return Ki().removeItem(t)},clearAll:function(){return Ki().clear()}};function Ki(){return Li.localStorage}function Bi(t){return Ki().getItem(t)}var Vi=Ai.trim,Gi={name:"cookieStorage",read:function(t){if(!t||!Xi(t))return null;var e="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Wi.cookie.replace(new RegExp(e),"$1"))},write:function(t,e){if(!t)return;Wi.cookie=escape(t)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Yi,remove:Qi,clearAll:function(){Yi((function(t,e){Qi(e)}))}},Wi=Ai.Global.document;function Yi(t){for(var e=Wi.cookie.split(/; ?/g),r=e.length-1;r>=0;r--)if(Vi(e[r])){var n=e[r].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Qi(t){t&&Xi(t)&&(Wi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Xi(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Wi.cookie)}var Zi=function(){var t={};return{defaults:function(e,r){t=r},get:function(e,r){var n=e();return void 0!==n?n:t[r]}}};var ta=Ai.bind,ea=Ai.each,ra=Ai.create,na=Ai.slice,oa=function(){var t=ra(ia,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(e,r,n){return t.on(r,ta(this,n))},unwatch:function(e,r){t.off(r)},once:function(e,r,n){t.once(r,ta(this,n))},set:function(e,r,n){var o=this.get(r);e(),t.fire(r,n,o)},remove:function(e,r){var n=this.get(r);e(),t.fire(r,void 0,n)},clearAll:function(e){var r={};this.each((function(t,e){r[e]=t})),e(),ea(r,(function(e,r){t.fire(r,void 0,e)}))}}};var ia={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,e){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=e,this._subSignals[this._id]=t,this._id},off:function(t){var e=this._subSignals[t];delete this._subCallbacks[e][t],delete this._subSignals[t]},once:function(t,e){var r=this.on(t,ta(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=na(arguments,1);ea(this._subCallbacks[t],(function(t){t.apply(this,e)}))}},aa=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=function(){var t=String.fromCharCode,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,e){if(!n[t]){n[t]={};for(var r=0;r>>8,r[2*n+1]=a%256}return r},decompressFromUint8Array:function(e){if(null==e)return i.decompress(e);for(var r=new Array(e.length/2),n=0,o=r.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,g==e-1){d.push(r(v));break}g++}return d.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(e){return t.charCodeAt(e)}))},_decompress:function(e,r,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,d=3,v="",g=[],y={val:n(0),position:r,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,g.push(f);;){if(y.index>e)return"";for(a=0,c=Math.pow(2,d),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=r,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return g.join("")}if(0==p&&(p=Math.pow(2,d),d++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}g.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,d),d++)}}};return i}();null!=t&&(t.exports=e)})),ua=function(){return{get:function(t,e){var r=t(e);if(!r)return r;var n=aa.decompress(r);return null==n?r:this._deserialize(n)},set:function(t,e,r){var n=aa.compress(this._serialize(r));t(e,n)}}};var ca=[Di,Gi],sa=[Zi,oa,ua],fa=Ji.createStore(ca,sa),la=Ai.Global;function pa(){return la.sessionStorage}function ha(t){return pa().getItem(t)}var da=[{name:"sessionStorage",read:ha,write:function(t,e){return pa().setItem(t,e)},each:function(t){for(var e=pa().length-1;e>=0;e--){var r=pa().key(e);t(ha(r),r)}},remove:function(t){return pa().removeItem(t)},clearAll:function(){return pa().clear()}},Gi],va=[Zi,ua],ga=Ji.createStore(da,va),ya=fa,ba=ga,_a=function(t){var e;return(e={}).args=t,e};function ma(t,e){var r;return(r={})[t]=e,r[u]=[wi()],r}var wa=function(t){return yt(t,"data")&&!yt(t,"error")?t.data:t},ja=function(t){this.opts=t,this.instanceKey=ei(this.opts.hostname)+"",this.localStore=ya,this.sessionStore=ba},Sa={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};ja.prototype.__setMethod=function(t,e){var r,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((r={})[a]=o?mo({},o,e):e,r))},ja.prototype.__getMethod=function(t){var e=this[t].get(this.opts.storageKey);return!!e&&e[this.instanceKey]},ja.prototype.__delMethod=function(t,e){var r=this.__getMethod(t);if(r){var n={};for(var o in r)o!==e&&(n[o]=r[o]);this.__setMethod(t,n)}},ja.prototype.__clearMethod=function(t){var e=this.opts.storageKey,r=this[t],n=r.get(e);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);r.set(e,o)}},Sa.lset.set=function(t){return this.__setMethod("localStore",t)},Sa.lget.get=function(){return this.__getMethod("localStore")},ja.prototype.ldel=function(t){return this.__delMethod("localStore",t)},ja.prototype.lclear=function(){return this.__clearMethod("localStore")},Sa.sset.set=function(t){return this.__setMethod("sessionStore",t)},Sa.sget.get=function(){return this.__getMethod("sessionStore")},ja.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},ja.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(ja.prototype,Sa);var Oa=c[0],ka=c[1],Ea=function(t){function e(e,r){this.fly=e,t.call(this,r)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={jsonqlEndpoint:{configurable:!0}};return r.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},e.prototype.log=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(!0===this.opts.debugOn){var r=["info","error"],n="__error__"===t[0]?1:0;Reflect.apply(console[r[n]],console,t.splice(0,n))}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=mi)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.prototype.decoder=function(t){return t},r.profileIndex.set=function(t){var e;if(Io(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((e={}).prof_idx=t,e)));throw new xt("profileIndex","Expect idx to be number but got "+typeof t)},r.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var e=this.lget;if(e[t])return e[t]}return this[t]?this[t]:0},e.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},r.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},r.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},r.jsonqlToken.set=function(t){var e,r=this.readProfile,n="jsonqlcredential",o=r&&r[n]?r[n]:[];o.push(t),this.saveProfile=((e={})[n]=o,e),this.jsonqlUserdata=this.decoder(t)},r.jsonqlToken.get=function(){var t=this.readProfile,e="jsonqlcredential";return!(!t||!t[e])&&(this.log("-- jsonqlToken --",t[e],this.profileIndex,t[e][this.profileIndex]),t[e][this.profileIndex])},r.jsonqlUserdata.set=function(t){var e;this.sset=((e={}).userdata=t,e)},r.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},e.prototype.getAuthHeader=function(){var t,e=this.jsonqlToken;return e?((t={})[this.opts.AUTH_HEADER]="Bearer "+e,t):{}},e.prototype.getProfiles=function(t){void 0===t&&(t=!1);var e=this.readProfile,r="jsonqlcredential";return!(!e||!e[r])&&(!1!==t&&Io(t)?e[r][t]||!1:e[r].map(this.decoder.bind(this)))},e.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},e.prototype.postLogoutAction=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];console.info("postLogoutAction",t)},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={contractHeader:{configurable:!0}};return e.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},r.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},e.prototype.storeContract=function(t){var e;if(!ti(t))throw new xt("Contract is malformed!");return this.lset=((e={}).contract=t,e),this.log("storeContract return result",t),t},e.prototype.readContract=function(){var t=ti(this.opts.contract);if(!1!==t)return t;var e=this.lget;return!!e&&e.contract},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){t.call(this,e),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},r.prototype.request=function(t,e,r){var n;void 0===e&&(e={}),void 0===r&&(r={}),this.headers=r;var o=mo({},{_cb:wi()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=mo({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=mo({},{method:Oa,params:o},e);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},r.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(e){var r=t.getHeaders();for(var n in t.log("request interceptor call",r),r)e.headers[n]=r[n];return e}))},r.prototype.processJsonp=function(t){return wa(t)},r.prototype.resInterceptor=function(){var t=this,e=this,r=e.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),e.cleanUp();var o=Fo(n.data)?JSON.parse(n.data):n.data;return r?e.processJsonp(o):wa(o)}),(function(r){throw e.cleanUp(),t.log("__error__",r),new qt("Server side error",r)}))},r.prototype.getHeaders=function(){return this.opts.enableAuth?mo({},e,this.getAuthHeader(),this.extraHeader):mo({},e,this.extraHeader)},r.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},r.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=mo({},this.extraParams,g)),this.request({},{method:"GET"},this.contractHeader).then(Nt).then((function(e){return t.log("get contract result",e),e.cache&&e.contract?e.contract:e})).catch((function(e){throw t.log("__error__","getRemoteContract err",e),new qt("getRemoteContract",e)}))},r.prototype.query=function(t,e){return void 0===e&&(e=[]),this.request(function(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Ut(t)&&m(e)){var n=_a(e);return!0===r?n:ma(t,n)}throw new xt("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e)).then(Nt)},r.prototype.mutation=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),this.request(function(t,e,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[i]=e,o[a]=r,!0===n)return o;if(Ut(t))return ma(t,o);throw new xt("[createMutation] expect resolverName to be string!",{resolverName:t,payload:e,condition:r})}(t,e,r),{method:ka}).then(Nt)},Object.defineProperties(r.prototype,n),r}(ja)))),Aa={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Ta={hostname:Uo(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:Uo("jsonql",["string"]),loginHandlerName:Uo("login",["string"]),logoutHandlerName:Uo("logout",["string"]),enableJsonp:Uo(!1,["boolean"]),enableAuth:Uo(!1,["boolean"]),useJwt:Uo(!0,["boolean"]),persistToken:Uo(!1,["boolean","number"]),useLocalstorage:Uo(!0,["boolean"]),storageKey:Uo("jsonqlstore",["string"]),authKey:Uo("jsonqlauthkey",["string"]),contractExpired:Uo(0,["number"]),keepContract:Uo(!0,["boolean"]),exposeContract:Uo(!1,["boolean"]),exposeStore:Uo(!1,["boolean"]),showContractDesc:Uo(!1,["boolean"]),contractKey:Uo(!1,["boolean"]),contractKeyName:Uo("X-JSONQL-CV-KEY",["string"]),enableTimeout:Uo(!1,["boolean"]),timeout:Uo(5e3,["number"]),returnInstance:Uo(!1,["boolean"]),allowReturnRawToken:Uo(!1,["boolean"]),debugOn:Uo(!1,["boolean"])};function xa(t){return Do(t,v)?t:function(t){return Ho(t,Ta,Aa)}(t)}var Pa=new WeakMap,qa=new WeakMap,Ca=function(){this.__suspend__=null,this.queueStore=new Set},$a={$suspend:{configurable:!0},$queues:{configurable:!0}};$a.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},Ca.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},$a.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},Ca.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(Ca.prototype,$a);var za=function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(e,a,r||u),i+=n.addToNormalStore(t,"on",e,r||u)})),i},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(e,i,r||a),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(e,i,r||a)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(e,a,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(e,i)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Pa.set(this,t)},r.normalStore.get=function(){return Pa.get(this)},r.lazyStore.set=function(t){qa.set(this,t)},r.lazyStore.get=function(){return qa.get(this)},e.prototype.hashFnToKey=function(t){return ei(t.toString())+""},Object.defineProperties(e.prototype,r),e}(Ca));return function(t,e){void 0===e&&(e={});var r,n=e.contract,o=xa(e),i=new Ea(t,o),a=ri(i,n),u=(r=o.debugOn,new za({logger:r?function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})),c=Zo(i,o,a,u);return c.eventEmitter=u,c}})); //# sourceMappingURL=static.js.map diff --git a/packages/http-client/static.js.map b/packages/http-client/static.js.map index 3a9264e1..d8541a27 100644 --- a/packages/http-client/static.js.map +++ b/packages/http-client/static.js.map @@ -1 +1 @@ -{"version":3,"file":"static.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"u81CAAA"} \ No newline at end of file +{"version":3,"file":"static.js","sources":["node_modules/store/plugins/defaults.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n"],"names":[],"mappings":"sj3CAAA"} \ No newline at end of file -- Gitee