From e3d0e9a657e4979109343ed210d6d556f001d7a6 Mon Sep 17 00:00:00 2001 From: joelchu Date: Wed, 11 Dec 2019 14:00:50 +0800 Subject: [PATCH 1/3] fix the coding error in the on interface --- packages/@jsonql/client/package.json | 2 +- .../tests/dist/jsonql-client-ws.debug.js | 27 +++++++++++++------ .../tests/dist/jsonql-client-ws.debug.js.map | 2 +- .../client/tests/qunit/files/ws-basic-test.js | 20 +++++++++----- .../@jsonql/ws/src/core/ws-main-handler.js | 2 +- packages/ws-client-core/package.json | 2 +- packages/ws-client-core/src/api.js | 4 +-- packages/ws-client-core/src/core/generator.js | 23 ++++++---------- .../src/core/resolver-methods.js | 2 +- .../src/core/setup-callback-api.js | 6 ++++- packages/ws-client-core/tests/on.test.js | 18 ++++++------- .../ws-client-core/tests/test-node.test.js | 2 ++ 12 files changed, 63 insertions(+), 47 deletions(-) diff --git a/packages/@jsonql/client/package.json b/packages/@jsonql/client/package.json index 457167ce..4a9ea789 100644 --- a/packages/@jsonql/client/package.json +++ b/packages/@jsonql/client/package.json @@ -46,7 +46,7 @@ "license": "MIT", "dependencies": { "flyio": "^0.6.14", - "jsonql-client": "^1.5.5" + "jsonql-client": "^1.5.6" }, "optionalDependencies": { "@jsonql/ws": "^1.0.0" diff --git a/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js b/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js index bbb05dfe..4f398043 100644 --- a/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js +++ b/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js @@ -7710,6 +7710,8 @@ if (opts.enableAuth) { this.setDecoder = jwtDecode; } + // cache + this.__userdata__ = null; } if ( ContractClass ) AuthClass.__proto__ = ContractClass; @@ -7824,7 +7826,8 @@ tokens.push(token); this.saveProfile = ( obj = {}, obj[key] = tokens, obj ); // store the userdata - this.jsonqlUserdata = this.decoder(token); + this.__userdata__ = this.decoder(token); + this.jsonqlUserdata = this.__userdata__; }; /** @@ -7902,7 +7905,8 @@ */ AuthClass.prototype.postLoginAction = function postLoginAction (token) { this.jsonqlToken = token; - return token + + return { token: token, userdata: this.__userdata__ } }; /** @@ -8964,14 +8968,18 @@ var fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract); return fn.apply(null, args) .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance)) - .then(function (token) { + .then(function (ref) { + var token = ref.token; + var userdata = ref.userdata; + ee.$trigger(LOGIN_NAME, token); - return token; + // 1.5.6 return the decoded userdata instead + return userdata }) }; } // @TODO allow to logout one particular profile or all of them - if (contract.auth[logoutHandlerName]) { + if (contract.auth[logoutHandlerName]) { // this one has a server side logout auth[logoutHandlerName] = function logoutHandlerFn() { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; @@ -8984,9 +8992,12 @@ return r; }) }; - } else { - auth[logoutHandlerName] = function logoutHandlerFn() { - jsonqlInstance.postLogoutAction(KEY_WORD); + } else { // this is only for client side logout + // @TODO should allow to login particular profile + auth[logoutHandlerName] = function logoutHandlerFn(profileId) { + if ( profileId === void 0 ) profileId = null; + + jsonqlInstance.postLogoutAction(KEY_WORD, profileId); ee.$trigger(LOGOUT_NAME, KEY_WORD); }; } diff --git a/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js.map b/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js.map index 69e8c9ac..f88a4499 100644 --- a/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js.map +++ b/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client-ws.debug.js","sources":["../../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/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-utils/src/contract.js","../../node_modules/nb-event-service/src/hash-code.js","../../node_modules/jsonql-client/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/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","../../node_modules/jsonql-utils/src/timestamp.js","../../node_modules/store/plugins/defaults.js","../../node_modules/jsonql-client/src/stores/local-store.js","../../node_modules/jsonql-client/src/stores/session-store.js","../../node_modules/jsonql-client/src/stores/index.js","../../node_modules/jsonql-utils/src/params-api.js","../../node_modules/jsonql-utils/src/results.js","../../node_modules/jsonql-client/src/base/store-cls.js","../../node_modules/jsonql-client/src/base/http-cls.js","../../node_modules/jsonql-client/src/base/contract-cls.js","../../node_modules/jsonql-client/src/base/auth-cls.js","../../node_modules/jsonql-client/src/base/base-cls.js","../../node_modules/jsonql-client/src/base/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","../../node_modules/jsonql-client/src/ee.js","../../node_modules/jsonql-client/src/core/methods-generator.js","../../node_modules/jsonql-client/src/core/jsonql-api-generator.js","../../node_modules/jsonql-client/src/options/base-options.js","../../node_modules/jsonql-client/src/options/check-options-async.js","../../node_modules/jsonql-client/src/options/index.js","../../node_modules/jsonql-client/module.js","../../node_modules/jsonql-utils/src/chain-promises.js","../../node_modules/jsonql-utils/src/pre-config-check.js","../../node_modules/jsonql-client/opt.js","../../node_modules/jsonql-ws-client-core/src/options/constants.js","../../node_modules/jsonql-ws-client-core/src/utils/ee.js","../../node_modules/jsonql-ws-client-core/src/utils/process-contract.js","../../node_modules/jsonql-ws-client-core/src/utils/helpers.js","../../node_modules/jsonql-ws-client-core/src/core/respond-handler.js","../../node_modules/jsonql-ws-client-core/src/core/action-call.js","../../node_modules/jsonql-ws-client-core/src/core/setup-callback-api.js","../../node_modules/jsonql-ws-client-core/src/core/setup-resolver.js","../../node_modules/jsonql-ws-client-core/src/core/resolver-methods.js","../../node_modules/jsonql-ws-client-core/src/core/setup-auth-methods.js","../../node_modules/jsonql-ws-client-core/src/core/generator.js","../../node_modules/jsonql-ws-client-core/src/options/index.js","../../node_modules/jsonql-ws-client-core/src/api.js","../../node_modules/@jsonql/ws/src/options/index.js","../../node_modules/@jsonql/ws/src/core/create-ws-client.js","../../node_modules/jsonql-ws-client/src/options/constants.js","../../node_modules/jsonql-ws-client/src/share/create-nsp-client.js","../../node_modules/jsonql-ws-client/src/utils/helpers.js","../../node_modules/jsonql-ws-client/src/share/trigger-namespaces-on-error.js","../../node_modules/jsonql-ws-client/src/share/client-event-handler.js","../../node_modules/@jsonql/ws/src/core/extract-ws-payload.js","../../node_modules/@jsonql/ws/src/core/ws-main-handler.js","../../node_modules/@jsonql/ws/src/core/create-client.js","../../node_modules/@jsonql/ws/src/core/create-client-resolver.js","../../node_modules/@jsonql/ws/src/ws-client-resolver.js","../../node_modules/@jsonql/ws/index.js","../../node_modules/jsonql-ws-client/src/options/index.js","../../node_modules/@jsonql/ws/opt.js","../../ws.js"],"sourcesContent":["/**\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","/**\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","// 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","// 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 * construct the actual end user method, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfigAsync = function(validateSync) {\n /**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n/**\n * copy of above but it's sync, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n getCheckConfigAsync,\n getCheckConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\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// construct the final output 1.5.2\nexport const checkConfigAsync = jsonqlOptions.getCheckConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.getCheckConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/options/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","// 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","// 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 // 1.5.2 change it to a getter to return a method, pass a name to id which one is which\n client.getLogger = (name) => (...args) => Reflect.apply(jsonqlInstance.log, jsonqlInstance, [name].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","// new module interface for @jsonql/client\n// this will be use with the @jsonql/ws, @jsonql/socketio\nimport { SOCKET_NAME } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\nimport JsonqlBaseClient from './src/base'\nimport getEventEmitter from './src/ee'\nimport generator from './src/core/jsonql-api-generator'\nimport { checkOptionsAsync } from './src/options'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { isObjectHasKey } from 'jsonql-utils/src/generic'\nimport { getContractFromConfig } from './src/utils'\n\n/**\n * Check if the contract has socket field and the socket client is suplied\n * @param {object} client the http client\n * @param {object} contract the json\n * @param {object} config the checked configuration\n * @param {object} socketClient from the original config\n * @return {object} the completed client\n */\nfunction initSocketClient(client, contract, config, socketClient) {\n if (isObjectHasKey(contract, SOCKET_NAME)) {\n if (socketClient) {\n // pass the contract here one more time in case the constProps overwritten it\n config.log = client.getLogger(`jsonql-client:${config.serverType}`)\n config.contract = contract\n config.eventEmitter = client.eventEmitter\n return socketClient(config)\n .then(sc => {\n client[SOCKET_NAME] = sc\n return client\n })\n } else {\n throw new JsonqlError(`initSocketClient`, `socketClient is missing!`)\n }\n }\n return client\n}\n\n/**\n * Main interface for jsonql fetch api\n * @1.4.8 change this to named export to diff this from the other\n * and this is only use with the @jsonql/client to construct the client with ws\n * @param {object} Fly the http engine\n * @param {object} [config={}] configuration\n * @return {object} jsonqlClient\n */\nfunction jsonqlClientModule(fly, config = {}) {\n const { socketClient, debugOn } = config;\n const ee = getEventEmitter(debugOn)\n return checkOptionsAsync(config)\n .then(opts => (\n {\n opts,\n baseClient: new JsonqlBaseClient(fly, opts)\n }\n ))\n // make sure the contract is presented\n .then(({opts, baseClient}) => getContractFromConfig(baseClient, opts.contract)\n .then(contract => (\n {\n opts,\n contract,\n client: generator(baseClient, opts, contract, ee)\n }\n )\n )\n )\n // finally generate the websocket client if any\n .then(({opts, contract, client}) => (\n initSocketClient(client, contract, opts, socketClient)\n ))\n}\n// export it\nexport { jsonqlClientModule }\n","// break it out on its own because\n// it's building from the lodash-es from scratch\n// according to this discussion https://github.com/lodash/lodash/issues/3298\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport merge from 'lodash-es/merge'\n\n/**\n * previously we already make sure the order of the namespaces\n * and attach the auth client to it\n * @param {array} promises array of unresolved promises\n * @param {boolean} asObject if true then merge the result object\n * @return {object} promise resolved with the array of promises resolved results\n */\nexport function chainPromises(promises, asObject = false) {\n return promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResults => (\n currentTask.then(currentResult => (\n asObject === false ? [...chainResults, currentResult] : merge(chainResults, currentResult)\n ))\n ))\n ), Promise.resolve(\n asObject === false ? [] : (isPlainObject(asObject) ? asObject : {})\n ))\n}\n\n\n/**\n * This one return a different result from the chainPromises\n * it will be the same like chainFns that take one promise resolve as the next fn parameter\n * @param {function} initPromise a function that accept param and resolve result\n * @param {array} promises array of function pass that resolve promises\n * @return {promise} resolve the processed result\n */\nexport function chainProcessPromises(initPromise, ...promises) {\n return (...args) => (\n promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResult => (\n currentTask(chainResult)\n )\n )\n ), Reflect.apply(initPromise, null, args))\n )\n}\n","// this will replace the preConfigCheck in jsonql-koa\n// also this will get use in the client as well\n// basically this is just a wrapper method to load everything together\n// and then add the CHECKED_KEY to it\nimport { CHECKED_KEY } from 'jsonql-constants'\n\nimport { chainFns } from './chain-fns'\nimport { timestamp } from './timestamp'\nimport { injectToFn } from './obj-define-props'\n\n/**\n * the rest of the argument will be functions that\n * need to add to the process chain,\n * finally return a function to accept the config\n * @param {object} defaultOptions prepared before hand\n * @param {object} constProps prepare before hand\n * @param {array} fns arguments see description\n * @return {function} to perform the final configuration check\n */\nexport function preConfigCheck(defaultOptions, constProps, ...fns) {\n // should have just add the method to the last\n const finalFn = opt => injectToFn(opt, CHECKED_KEY, timestamp())\n // if there is more than one then chain it otherwise just return the zero idx one\n const fn = Reflect.apply(chainFns, null, fns.concat(finalFn))\n // 0.8.8 add a default property empty object\n return (config = {}) => fn(config, defaultOptions, constProps)\n}\n","// export the options for the pre-check to use\nimport { preConfigCheck } from 'jsonql-utils/module'\nimport { checkConfig } from 'jsonql-params-validator'\nimport merge from 'lodash-es/merge'\n\nimport { appProps, constProps } from './src/options/base-options'\n// just export the function here for use to save repeat coding\n\n/**\n * This will combine the socket client options and merge this one\n * then do a pre-check on both at the same time\n * @param {object} [extraProps = {}]\n * @param {object} [extraConstProps = {}]\n * @return {function} to process the developer options\n */\nexport function getPreConfigCheck(extraProps = {}, extraConstProps = {}) {\n const aProps = merge({}, appProps, extraProps)\n const cProps = merge({}, constProps, extraConstProps)\n\n return preConfigCheck(aProps, cProps, checkConfig)\n}\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME;\nconst WS = JS_WS_NAME;\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!';\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!';\n\nconst MISSING_PROP_ERR = 'Missing property in contract!';\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!';\n\nconst EMIT_EVT = EMIT_REPLY_TYPE;\n\nconst NAMESPACE_KEY = 'namespaceMap';\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!';\n\nconst NOT_ALLOW_OP = 'This operation is not allow!';\n\nconst MY_NAMESPACE = 'myNamespace'\n\nconst CB_FN_NAME = 'on'\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME\n}\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// create a clone version so we know which one we actually is using\nexport default class JsonqlWsEvt extends NBEventService {\n\n constructor(logger) {\n // this ee will always come with the logger\n // because we should take the ee from the configuration\n super({ logger })\n }\n\n get name() {\n return'jsonql-ws-client'\n }\n}\n","// mapping the resolver to their respective nsp\nimport { JSONQL_PATH, NSP_SET, PUBLIC_NAMESPACE } from 'jsonql-constants'\nimport { groupByNamespace, extractSocketPart } from 'jsonql-utils/module'\nimport { JsonqlResolverNotFoundError } from 'jsonql-errors'\n\nimport { MISSING_PROP_ERR } from '../options/constants'\n\n/**\n * Just make sure the object contain what we are looking for\n * @param {object} opts configuration from checkOptions\n * @return {object} the target content\n */\nconst getResolverList = contract => {\n const result = extractSocketPart(contract)\n if (result !== false) {\n return result\n }\n throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR)\n}\n\n/**\n * process the contract first\n * @param {object} opts configuration\n * @return {object} sorted list\n */\nexport default function processContract(opts) {\n const { contract, enableAuth } = opts;\n if (enableAuth) {\n return groupByNamespace(contract)\n }\n return {\n [NSP_SET]: { [JSONQL_PATH]: getResolverList(contract) },\n [PUBLIC_NAMESPACE]: JSONQL_PATH\n }\n}\n","// group all the small functions here\nimport { JS_WS_SOCKET_IO_NAME, JS_WS_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/src/generic'\n\n// we shouldn't do this anymore\nexport const fixWss = (url, serverType) => {\n // ws only allow ws:// path\n if (serverType === JS_WS_NAME) {\n return url.replace('http://', 'ws://')\n }\n return url;\n}\n\n/**\n * get a stock host name from browser\n */\nexport const getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n throw new JsonqlValidationError(e)\n }\n}\n\n/**\n * Unbind the event\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nexport const clearMainEmitEvt = (ee, namespace) => {\n let nsps = toArray(namespace)\n nsps.forEach(n => {\n ee.$off(createEvt(n, EMIT_REPLY_TYPE))\n })\n}\n\n/**\n * @param {object} nsps namespace as key\n * @param {string} type of server\n */\nexport const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => {\n try {\n // @TODO need to figure out a better way here?\n const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate';\n for (let namespace in nsps) {\n let nsp = nsps[namespace]\n if (nsp && nsp[method]) {\n Reflect.apply(nsp[method], null, [])\n }\n }\n } catch(e) {\n // socket.io throw a this.destroy of undefined?\n console.error('Disconnect call failed', e)\n }\n}\n","// breaking it up further to share between methods\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { UNKNOWN_RESULT } from '../options/constants'\nimport { isObjectHasKey } from '../utils'\n\n/**\n * break out to use in different places to handle the return from server\n * @param {object} data from server\n * @param {function} resolver NOT from promise\n * @param {function} rejecter NOT from promise\n * @return {void} nothing\n */\nexport function respondHandler(data, resolver, rejecter) {\n if (isObjectHasKey(data, ERROR_KEY)) {\n // debugFn('-- rejecter called --', data[ERROR_KEY])\n rejecter(data[ERROR_KEY])\n } else if (isObjectHasKey(data, DATA_KEY)) {\n // debugFn('-- resolver called --', data[DATA_KEY])\n resolver(data[DATA_KEY])\n } else {\n // debugFn('-- UNKNOWN_RESULT --', data)\n rejecter({message: UNKNOWN_RESULT, error: data})\n }\n}\n","// the actual trigger call method\nimport { ON_RESULT_PROP_NAME, RESULT_PROP_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { createEvt, toArray } from '../utils'\nimport { respondHandler } from './respond-handler'\n\n/**\n * just wrapper\n * @param {object} ee EventEmitter\n * @param {string} namespace where this belongs\n * @param {string} resolverName resolver\n * @param {boolean} useCallbackStyle use on or not\n * @param {array} args arguments\n * @return {void} nothing\n */\nexport function actionCall(ee, namespace, resolverName, useCallbackStyle, args = []) {\n const eventName = createEvt(namespace, EMIT_REPLY_TYPE)\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME\n // debugFn(`actionCall: ${eventName} --> ${resolverName}`, args)\n ee.$trigger(eventName, [resolverName, toArray(args)])\n // once we trigger there is nothing return from the resolve\n // @TODO if we need the next then call to have the result back\n // then we need to listen to the event callback here as well\n return new Promise((resolver, rejecter) => {\n ee.$on(\n createEvt(namespace, resolverName, RESULT_SUBFIX),\n function actionCallResultHandler(result) {\n // debugFn(`got the first result`, result)\n respondHandler(result, resolver, rejecter)\n }\n )\n })\n}\n","// @TODO using the obj.on syntax to do the same thing\n/*\nThe new callback style `useCallbackStyle` set to true then use this one\nclient.resolverName.on(EVENT_NAME, cb)\n*/\nimport { JsonqlValidationError, JsonqlError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME\n} from 'jsonql-constants'\nimport { CB_FN_NAME } from '../options/constants'\n\nimport { respondHandler } from './respond-handler'\nimport { chainFns, injectToFn, createEvt, toArray, isFunc, isString } from '../utils'\n\n/**\n * Add extra property to the resolver via the getter\n * @param {function} fn the resolver itself\n * @param {object} ee event emitter\n * @param {string} namespace the namespace this belongs to\n * @param {string} resolverName resolver namee\n * @param {object} params from the contract\n * @return {array} same as what goes in\n */\nexport function setupCallbackApi(fn, ee, namespace, resolverName, params) {\n return [\n injectToFn(fn, CB_FN_NAME, function(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch(evtName) {\n case RESULT_PROP_NAME:\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n // register the handler for this message event\n case MESSAGE_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME),\n function onMessageCallback(args) {\n respondHandler(args, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n case READY_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n callback\n )\n break;\n default:\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n new JsonqlError(resolverName, `Unknown event name ${evtName}!`)\n )\n }\n }\n }),\n ee,\n namespace,\n resolverName,\n params\n ]\n}\n","// break up the original setup resolver method here\nimport { JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\nimport { MY_NAMESPACE } from '../options/constants'\nimport { chainFns, objDefineProps, injectToFn, createEvt, toArray, isFunc } from '../utils'\n\nimport { respondHandler } from './respond-handler'\nimport { setupSend } from './setup-send'\nimport { setupCallbackApi } from './setup-callback-api'\n\n/**\n * The first one in the chain\n * @return {array}\n */\nconst setupNamespace = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n injectToFn(fn, MY_NAMESPACE, namespace),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// onResult handler\nconst setupOnResult = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_RESULT_PROP_NAME, function(resultCallback) {\n if (isFunc(resultCallback)) {\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, resultCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// we do need to add the send prop back because it's the only way to deal with\n// bi-directional data stream\nconst setupOnMessage = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_MESSAGE_PROP_NAME, function(messageCallback) {\n // we expect this to be a function\n if (isFunc(messageCallback)) {\n // did that add to the callback\n let onMessageCallback = (args) => {\n respondHandler(args, messageCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n // register the handler for this message event\n ee.$only(createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME), onMessageCallback)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// add an ON_ERROR_PROP_NAME handler\nconst setupOnError = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_ERROR_PROP_NAME, function(resolverErrorHandler) {\n if (isFunc(resolverErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n ee.$only(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), resolverErrorHandler)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n/**\n * Add extra property to the resolver\n * @param {string} namespace where this belongs\n * @param {string} resolverName name as event name\n * @param {object} params from contract\n * @param {function} fn resolver function\n * @param {object} ee EventEmitter\n * @param {boolean} useCallbackStyle new callback style\n * @return {function} resolver\n */\nexport function setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle) {\n // also need to setup a getter to get back the namespace of this resolver\n let args = [setupNamespace]\n useCallbackStyle ? args.push(setupCallbackApi) : args.push(setupOnResult, setupOnMessage, setupOnError)\n args.push(setupSend)\n // get the executor\n const executor = Reflect.apply(chainFns, null, args)\n\n return Reflect.apply(executor, null, [fn, ee, namespace, resolverName, params, useCallbackStyle])\n}\n","// put all the resolver related methods here to make it more clear\n\n// this will be a mini client server architect\n// The reason is when the enableAuth setup - the private route\n// might not be validated, but we need the callable point is ready\n// therefore this part will always take the contract and generate\n// callable api for the developer to setup their front end\n// the only thing is - when they call they might get an error or\n// NOT_LOGIN_IN and they can react to this error accordingly\nimport { JsonqlError, JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n ERROR_PROP_NAME,\n LOGIN_PROP_NAME,\n READY_PROP_NAME,\n ON_ERROR_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n ON_READY_PROP_NAME\n} from 'jsonql-constants'\nimport { actionCall } from './action-call'\nimport {\n createEvt,\n toArray,\n injectToFn,\n objDefineProps,\n chainFns,\n isString,\n isFunc,\n isObjectHasKey\n} from '../utils'\nimport { CB_FN_NAME } from '../options/constants'\n\n/**\n * create the actual function to send message to server\n * @param {object} ee EventEmitter instance\n * @param {string} namespace this resolver end point\n * @param {string} resolverName name of resolver as event name\n * @param {object} params from contract\n * @param {boolean} useCallbackStyle on style or not\n * @return {function} resolver\n */\nexport function createResolver(ee, namespace, resolverName, params, useCallbackStyle) {\n // note we pass the new withResult=true option\n return function(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => actionCall(ee, namespace, resolverName, useCallbackStyle, _args))\n .catch(finalCatch)\n }\n}\n\n/**\n * The problem is the namespace can have more than one\n * and we only have on onError message\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @param {boolean} useCallbackStyle use cb or not\n * @return {object} obj with onError prop\n */\nexport function createNamespaceErrorHandler(obj, ee, nspSet) {\n // using the onError as name\n // @TODO we should follow the convention earlier\n // make this a setter for the obj itself\n return objDefineProps(obj, ON_ERROR_PROP_NAME, function namespaceErrorCallbackHandler(namespaceErrorHandler) {\n if (isFunc(namespaceErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n for (let namespace in nspSet) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ON_ERROR_PROP_NAME), namespaceErrorHandler)\n }\n }\n })\n}\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @return {object} obj with onReady prop\n */\nexport function createOnReadyhandler(obj, ee, nspSet) {\n return objDefineProps(obj, ON_READY_PROP_NAME, function onReadyCallbackHandler(onReadyCallback) {\n if (isFunc(onReadyCallback)) {\n // reduce it down to just one flat level\n ee.$on(ON_READY_PROP_NAME, onReadyCallback)\n }\n })\n}\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * Plus this will check if it's the private namespace that fired the event\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} opts configuration\n * @return {object} obj with onLogin prop\n */\nexport function createOnLoginhandler(obj, ee, opts) {\n if (opts.enableAuth) {\n return objDefineProps(obj, ON_LOGIN_PROP_NAME, function onLoginCallbackHandler(onLoginCallback) {\n if (isFunc(onLoginCallback)) {\n // only one callback can registered with it, TBC\n ee.$only(ON_LOGIN_PROP_NAME, onLoginCallback)\n }\n })\n }\n // just skip it\n return obj\n}\n\n/**\n * when useCallbackStyle=true use this instead of the above method\n * @param {object} obj the base object to attach to\n * @param {object} ee EventEmitter\n * @param {object} nspSet the map\n * @param {object} opts configuration\n * @return {object} obj\n */\nexport function createCallbackHandler(obj, ee, nspSet, opts) {\n return injectToFn(obj, CB_FN_NAME, function onHandler(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch (evtName) {\n case ERROR_PROP_NAME:\n for (let namespace in nspSet) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ERROR_PROP_NAME), callback)\n }\n break;\n case LOGIN_PROP_NAME:\n ee.$only(LOGIN_PROP_NAME, callback)\n break;\n case READY_PROP_NAME:\n ee.$on(READY_PROP_NAME, callback)\n break;\n default:\n ee.$trigger(ERROR_PROP_NAME, new JsonqlError(CB_FN_NAME, `Unknown event name ${evtName}!`))\n }\n }\n // @TODO need to issue another error here!\n })\n}\n","// take out from the resolver-methods\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { injectToFn, chainFns, isString } from '../utils'\n\n/**\n * @TODO this is now become unnecessary because the login is a slave to the\n * http-client - but keep this for now and see what we want to do with it later\n * break out from createAuthMethods to allow chaining call\n * @param {object} obj the main client object\n * @param {object} ee event emitter\n * @param {object} opts configuration\n * @return {array} modified input\n */\nconst setupLoginHandler = (obj, ee, opts) => [\n injectToFn(obj, opts.loginHandlerName, function loginHandler(token) {\n if (token && isString(token)) {\n return ee.$trigger(LOGIN_EVENT_NAME, [token])\n }\n // should trigger a global error instead @TODO\n throw new JsonqlValidationError(opts.loginHandlerName, `Unexpected token ${token}`)\n }),\n ee,\n opts\n]\n\n/**\n * break out from createAuthMethods to allow chaining call - final in chain\n * @param {object} obj the main client object\n * @param {object} ee event emitter\n * @param {object} opts configuration\n * @return {object} the modified obj\n */\nconst setupLogoutHandler = (obj, ee, opts) => (\n injectToFn(obj, opts.logoutHandlerName, function logoutHandler(...args) {\n ee.$trigger(LOGOUT_EVENT_NAME, args)\n })\n)\n\n/**\n * Create auth related methods\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} opts configuration\n * @return {object} obj with auth methods if any\n */\nexport function createAuthMethods(obj, ee, opts) {\n if (opts.enableAuth) {\n return chainFns(setupLoginHandler, setupLogoutHandler)(obj, ee, opts)\n }\n return obj;\n}\n","// resolvers generator\n// we change the interface to return promise from v1.0.3\n// this way we make sure the obj return is correct and timely\nimport { setupResolver } from './setup-resolver'\nimport {\n createResolver,\n createNamespaceErrorHandler,\n createOnReadyhandler,\n createOnLoginhandler,\n createCallbackHandler\n} from './resolver-methods'\nimport { createAuthMethods } from './setup-auth-methods'\nimport { injectToFn, chainProcessPromises } from '../utils'\n\n/**\n * step one get the obj map with the namespace\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {promise} resolve the obj mapped, and start the chain\n */\nfunction getMappedObj(opts, nspMap, ee) {\n let obj = {};\n // let resolverNames = [];\n const { nspSet } = nspMap;\n const { useCallbackStyle } = opts; // @1.2.1\n for (let namespace in nspSet) {\n let list = nspSet[namespace]\n for (let resolverName in list) {\n // resolverNames.push(resolverName)\n let params = list[resolverName]\n let fn = createResolver(ee, namespace, resolverName, params, useCallbackStyle)\n // this should set as a getter therefore can not be overwrite by accident\n // obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee)\n obj = injectToFn(obj, resolverName, setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle))\n }\n }\n // move this two method down to helpers\n // we want these methods visible in debug or console.log\n obj.devHelpers = {\n // this is a helper method for the developer to know the namespace inside\n getNsp: () => Object.keys(nspSet),\n // simple get version trick\n getVer: () => opts.version || 'NOT SET'\n // not really necessary because the dev can query the contract\n // getResolverNames: () => resolverNames\n }\n // resolve the obj to start the chain\n // chain the result to allow the chain processing\n return Promise.resolve(obj)\n}\n\n/**\n * prepare the methods\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {object} of resolvers\n * @public\n */\nexport function generator(opts, nspMap, ee) {\n const { nspSet } = nspMap\n const { useCallbackStyle } = opts;\n let args = [getMappedObj]\n if (useCallbackStyle) {\n args.push(obj => createCallbackHandler(obj, ee, nspSet, opts))\n } else {\n args.push(\n obj1 => createNamespaceErrorHandler(obj1, ee, nspSet),\n obj2 => createOnReadyhandler(obj2, ee, nspSet),\n obj3 => createOnLoginhandler(obj3, ee, opts),\n )\n }\n args.push(obj4 => createAuthMethods(obj4, ee, opts))\n // run it\n const executor = Reflect.apply(chainProcessPromises, null, args)\n return executor(opts, nspMap, ee)\n\n /*\n return getMappedObj(opts, nspMap, ee)\n // add error handler\n .then(obj1 => createNamespaceErrorHandler(obj1, ee, nspSet))\n // add onReady handler\n .then(obj2 => createOnReadyhandler(obj2, ee, nspSet))\n // add onLogin handler -- this is optional\n .then(obj3 => createOnLoginhandler(obj3, ee, opts))\n // Auth related methods -- this is optional\n .then(obj4 => createAuthMethods(obj4, ee, opts))\n */\n}\n","// create options\nimport { checkConfigAsync, isNotEmpty } from 'jsonql-params-validator'\nimport { CHECKED_KEY } from 'jsonql-constants'\n// import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors'\n// this should be remove - we have to make it generic\nimport { defaultOptions } from './defaults'\nimport { fixWss, getHostName, objHasProp } from '../utils'\n\n// constant props\nconst defaultConstProps = {\n eventEmitter: null,\n // we unify the two different client into one now\n // only expect different parameter\n nspClient: null,\n nspAuthClient: null,\n // contructed path\n wssPath: ''\n}\n// for export\nconst jsonqlWsDefaultOptions = defaultOptions\nconst jsonqlWsDefaultConstProps = defaultConstProps\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config\n * @param {object} dOpt\n * @param {object} cProps\n * @return {promise} resolve to the checked opitons\n */\nfunction checkOptionsWrapper(config, dOpt, cProps) {\n if (objHasProp(config, CHECKED_KEY)) {\n return Promise.resolve(config)\n }\n return checkConfigAsync(config, dOpt, cProps)\n}\n\n/**\n * check the configuration\n * @param {object} config user supplied configuration\n * @param {object} constProps developer supplied configuration\n * @return {object} after checked\n */\nfunction checkOptions(config, constProps) {\n return checkOptionsWrapper(config, defaultOptions, Object.assign(defaultConstProps, constProps))\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // debug('CONFIGURATION OPTIONS', opts)\n return opts;\n })\n}\n\nexport {\n jsonqlWsDefaultConstProps,\n jsonqlWsDefaultOptions,\n checkOptions\n}\n","// the top level API\n// The goal is to create a generic method that will able to handle\n// any kind of clients\n// import { injectToFn } from 'jsonql-utils'\nimport { generator } from './core'\nimport { checkOptions } from './options'\nimport { ee, processContract } from './utils'\n\n/**\n * The main interface which will generate the socket clients and map all events\n * @param {object} socketClientResolver this is the one method export by various clients\n * @param {object} [constProps={}] add this to supply the constProps from the downstream client\n * @return {object} the wsClient instance with all the available API\n */\nexport default function wsClient(socketClientResolver, constProps = {}) {\n const { log } = constProps // 1.3.9 if we pass a log method here then we use this\n const logger = log && typeof log === 'function' ? log : () => {}\n // we need to inject property to this client later\n // therefore we need to do it this way\n return (opts) => {\n const { eventEmitter } = opts; // pass from the next level up\n return checkOptions(opts, constProps)\n .then(opts => {\n opts.logger = logger\n return opts;\n })\n .then(opts => ({\n opts,\n nspMap: processContract(opts),\n ee: eventEmitter || new ee(logger)\n }))\n .then(\n ({opts, nspMap, ee}) => socketClientResolver(opts, nspMap, ee)\n )\n .then(\n ({opts, nspMap, ee}) => generator(opts, nspMap, ee)\n )\n .catch(err => {\n console.error(`jsonql-ws-client init error`, err)\n })\n }\n}\n","// where all the base options are\n// create options\nimport { JS_WS_NAME } from 'jsonql-constants'\n// constant props\nconst constProps = {\n version: '__PLACEHOLDER__', // will get replace\n serverType: JS_WS_NAME\n}\n\nexport { constProps }\n","// pass the different type of ws to generate the client\nimport { TOKEN_PARAM_NAME } from 'jsonql-constants'\n/**\n * WebSocket is strict about the path, therefore we need to make sure before it goes in\n * @param {string} url input url\n * @return {string} url with correct path name\n */\nconst fixWss = url => {\n const uri = url.toLowerCase()\n if (uri.indexOf('http') > -1) {\n if (uri.indexOf('https') > -1) {\n return uri.replace('https', 'wss')\n }\n return uri.replace('http', 'ws')\n }\n return uri;\n}\n\n/**\n * The bug was in the wsOptions where ws doesn't need it but socket.io do\n * therefore the object was pass as second parameter!\n * @param {object} WebSocket the client or node version of ws\n * @param {boolean} auth if it's auth then 3 param or just one\n */\nexport function createWsClient(WebSocket, auth = false) {\n if (auth === false) {\n return function createWsClientHandler(url) {\n return new WebSocket(fixWss(url))\n }\n }\n\n /**\n * Create a client with auth token\n * @param {string} url start with ws:// @TODO check this?\n * @param {string} token the jwt token\n * @return {object} ws instance\n */\n return function createWsAuthClientHandler(url, token) {\n const ws_url = fixWss(url)\n // console.log('what happen here?', url, ws_url, token)\n const uri = token && typeof token === 'string' ? `${ws_url}?${TOKEN_PARAM_NAME}=${token}` : ws_url;\n try {\n return new WebSocket(uri)\n } catch(e) {\n console.error('WebSocket Connection Error', e)\n return false;\n }\n }\n}\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME;\nconst WS = JS_WS_NAME;\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!';\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!';\n\nconst MISSING_PROP_ERR = 'Missing property in contract!';\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!';\n\nconst EMIT_EVT = EMIT_REPLY_TYPE;\n\nconst NAMESPACE_KEY = 'namespaceMap';\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!';\n\nconst NOT_ALLOW_OP = 'This operation is not allow!';\n\nconst MY_NAMESPACE = 'myNamespace'\n\nconst CB_FN_NAME = 'on'\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME\n}\n","// since both the ws and io version are\n// pre-defined in the client-generator\n// and this one will have the same parameters\n// and the callback is identical\n\n/**\n * wrapper method to create a nsp without login\n * @param {string|boolean} namespace namespace url could be false\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspClient(namespace, opts) {\n const { hostname, wssPath, wsOptions, nspClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n return nspClient(url, wsOptions)\n}\n\n/**\n * wrapper method to create a nsp with token auth\n * @param {string} namespace namespace url\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspAuthClient(namespace, opts) {\n const { hostname, wssPath, token, wsOptions, nspAuthClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n if (token && typeof token !== 'string') {\n throw new Error(`Expect token to be string, but got ${token}`)\n }\n return nspAuthClient(url, token, wsOptions)\n}\n\nexport {\n createNspClient,\n createNspAuthClient\n}\n","// group all the small functions here\nimport { JS_WS_SOCKET_IO_NAME, JS_WS_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/src/generic'\n\n// we shouldn't do this anymore\nexport const fixWss = (url, serverType) => {\n // ws only allow ws:// path\n if (serverType === JS_WS_NAME) {\n return url.replace('http://', 'ws://')\n }\n return url;\n}\n\n/**\n * get a stock host name from browser\n */\nexport const getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n throw new JsonqlValidationError(e)\n }\n}\n\n/**\n * Unbind the event\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nexport const clearMainEmitEvt = (ee, namespace) => {\n let nsps = toArray(namespace)\n nsps.forEach(n => {\n ee.$off(createEvt(n, EMIT_REPLY_TYPE))\n })\n}\n\n/**\n * @param {object} nsps namespace as key\n * @param {string} type of server\n */\nexport const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => {\n try {\n // @TODO need to figure out a better way here?\n const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate';\n for (let namespace in nsps) {\n let nsp = nsps[namespace]\n if (nsp && nsp[method]) {\n Reflect.apply(nsp[method], null, [])\n }\n }\n } catch(e) {\n // socket.io throw a this.destroy of undefined?\n console.error('Disconnect call failed', e)\n }\n}\n","// this use by client-event-handler\nimport { ON_ERROR_PROP_NAME, ERROR_PROP_NAME } from 'jsonql-constants'\nimport { createEvt } from '../utils'\n\n/**\n * trigger errors on all the namespace onError handler\n * @param {object} ee Event Emitter\n * @param {array} namespaces nsps string\n * @param {string} message optional\n * @param {object} opts configuration\n * @return {void}\n */\nexport function triggerNamespacesOnError(ee, namespaces, message, opts = {}) {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n namespaces.forEach( namespace => {\n ee.$call(createEvt(namespace, ERROR_SUBFIX), [{ message, namespace }])\n })\n}\n","// This is share between different clients so we export it\n// @TODO port what is in the ws-main-handler\n// because all the client side call are via the ee\n// and that makes it re-usable between different client setup\nimport {\n ERROR_PROP_NAME,\n RESULT_PROP_NAME,\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n NOT_LOGIN_ERR_MSG,\n ON_ERROR_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n} from 'jsonql-constants'\nimport { EMIT_EVT, SOCKET_IO, WS } from '../options/constants'\nimport { createEvt, clearMainEmitEvt } from '../utils'\nimport { triggerNamespacesOnError } from './trigger-namespaces-on-error'\n\n/**\n * A fake ee handler\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nconst notLoginWsHandler = (namespace, ee, opts) => {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function notLoginHandlerCallback(resolverName, args) {\n opts.logger('noLoginHandler hijack the ws call', namespace, resolverName, args)\n let error = {\n message: NOT_LOGIN_ERR_MSG\n }\n // It should just throw error here and should not call the result\n // because that's channel for handling normal event not the fake one\n ee.$call(createEvt(namespace, resolverName, ERROR_SUBFIX), [error])\n // also trigger the result handler, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, RESULT_SUBFIX), [{ error }])\n }\n )\n}\n\n/**\n * get the private namespace\n * @param {array} namespaces array\n * @return {*} string on success\n */\nconst getPrivateNamespace = (namespaces) => (\n namespaces.length > 1 ? namespaces[0] : false\n)\n\n/**\n * centralize all the comm in one place\n * @param {object} opts configuration\n * @param {array} namespaces namespace(s)\n * @param {object} ee Event Emitter instance\n * @param {function} bindWsHandler binding the ee to ws --> this is the core bit\n * @param {array} namespaces array of namespace available\n * @param {object} nsps namespaced nsp\n * @return {void} nothing\n */\nexport function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) {\n // @1.1.3 add isPrivate prop to id which namespace is the private nsp\n // then we can use this prop to determine if we need to fire the ON_LOGIN_PROP_NAME event\n const privateNamespace = getPrivateNamespace(namespaces)\n let isPrivate = false;\n // loop\n // @BUG for io this has to be in order the one with auth need to get call first\n // The order of login is very import we need to run a waterfall here to make sure\n // one is execute then the other\n namespaces.forEach(namespace => {\n isPrivate = privateNamespace === namespace;\n if (nsps[namespace]) {\n opts.logger('call bindWsHandler', isPrivate, namespace)\n let args = [namespace, nsps[namespace], ee, isPrivate, opts]\n if (opts.serverType === SOCKET_IO) {\n let { nspSet } = nspMap;\n args.push(nspSet[namespace])\n }\n Reflect.apply(bindWsHandler, null, args)\n } else {\n // a dummy placeholder\n notLoginWsHandler(namespace, ee, opts)\n }\n })\n // this will be available regardless enableAuth\n // because the server can log the client out\n ee.$on(LOGOUT_EVENT_NAME, function logoutEvtHandler() {\n opts.logger('LOGOUT_EVENT_NAME')\n // disconnect(nsps, opts.serverType)\n // we need to issue error to all the namespace onError handler\n triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME)\n // rebind all of the handler to the fake one\n namespaces.forEach( namespace => {\n clearMainEmitEvt(ee, namespace)\n // clear out the nsp\n nsps[namespace] = false;\n // add a NOT LOGIN error if call\n notLoginWsHandler(namespace, ee, opts)\n })\n })\n}\n","// take the ws reply data for use\nimport { WS_EVT_NAME, WS_DATA_NAME, WS_REPLY_TYPE } from 'jsonql-constants'\nimport { isString } from 'jsonql-params-validator'\nimport { isObjectHasKey } from 'jsonql-utils/module'\nimport { JsonqlError, clientErrorsHandler } from 'jsonql-errors'\n\nconst keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ]\n\n/**\n * @param {object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nconst isWsReply = payload => {\n const { data } = payload;\n if (data) {\n let result = keys.filter(key => isObjectHasKey(data, key))\n return (result.length === keys.length) ? data : false;\n }\n return false;\n}\n\n/**\n * @param {object} payload This is the entire ws Event Object\n * @return {object} false on failed\n */\nconst extractWsPayload = payload => {\n const { data } = payload;\n let json = isString(data) ? JSON.parse(data) : data;\n // debugFn('extractWsPayload', json)\n let fdata;\n if ((fdata = isWsReply(json)) !== false) {\n return {\n resolverName: fdata[WS_EVT_NAME],\n data: fdata[WS_DATA_NAME],\n type: fdata[WS_REPLY_TYPE]\n };\n }\n throw new JsonqlError('payload can not be decoded', payload)\n}\n// export it\nexport default extractWsPayload\n","// the WebSocket main handler\nimport {\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n ACKNOWLEDGE_REPLY_TYPE,\n EMIT_REPLY_TYPE,\n ERROR_TYPE,\n\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_READY_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME,\n READY_PROP_NAME,\n LOGIN_PROP_NAME\n} from 'jsonql-constants'\nimport { createQueryStr, createEvt } from 'jsonql-utils/module'\nimport extractWsPayload from './extract-ws-payload'\nconst dummyLogger = () => {}\n/**\n * under extremely circumstances we might not even have a resolverName, then\n * we issue a global error for the developer to catch it\n * @param {object} ee event emitter\n * @param {string} namespace nsp\n * @param {string} resolverName resolver\n * @param {object} json decoded payload or error object\n * @param {string} ERROR_EVT_NAME the error event name\n * @return {undefined} nothing return\n */\nconst errorTypeHandler = (ee, namespace, resolverName, json, ERROR_EVT_NAME) => {\n let evt = [namespace]\n if (resolverName) {\n evt.push(resolverName)\n }\n evt.push(ERROR_EVT_NAME)\n let evtName = Reflect.apply(createEvt, null, evt)\n // test if there is a data field\n let payload = json.data || json;\n ee.$trigger(evtName, [payload])\n}\n\n/**\n * Binding the even to socket normally\n * @param {string} namespace\n * @param {object} ws the nsp\n * @param {object} ee EventEmitter\n * @param {boolean} isPrivate to id if this namespace is private or not\n * @param {object} opts configuration\n * @return {object} promise resolve after the onopen event\n */\nexport function wsMainHandler(namespace, ws, ee, isPrivate, opts) {\n\n const debugFn = opts.log || dummyLogger\n\n const { useCallbackStyle } = opts;\n const READY_EVT_NAME = useCallbackStyle ? READY_PROP_NAME : ON_READY_PROP_NAME;\n const LOGIN_EVT_NAME = useCallbackStyle ? LOGIN_PROP_NAME : ON_LOGIN_PROP_NAME;\n const MESSAGE_EVT_NAME = useCallbackStyle ? MESSAGE_PROP_NAME : ON_MESSAGE_PROP_NAME;\n const RESULT_EVT_NAME = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n const ERROR_EVT_NAME = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n // connection open\n ws.onopen = function onOpenCallback() {\n debugFn('ws.onopen listened')\n // we just call the onReady\n ee.$call(READY_EVT_NAME, namespace)\n // need an extra parameter here to id the private nsp\n if (isPrivate) {\n console.log(`isPrivate and fire the ${LOGIN_EVT_NAME}`)\n ee.$call(LOGIN_EVT_NAME, namespace)\n }\n // add listener only after the open is called\n ee.$only(\n createEvt(namespace, EMIT_REPLY_TYPE),\n function wsMainOnEvtHandler(resolverName, args) {\n debugFn('calling server', resolverName, args)\n ws.send(\n createQueryStr(resolverName, args)\n )\n }\n )\n }\n\n // reply\n // If we change it to the event callback style\n // then the payload will just be the payload and fucks up the extractWsPayload call @TODO\n ws.onmessage = function onMessageCallback(payload) {\n // console.log(`on.message`, typeof payload, payload)\n try {\n const json = extractWsPayload(payload)\n const { resolverName, type } = json;\n debugFn('Hear from server', type, json)\n switch (type) {\n case EMIT_REPLY_TYPE:\n let e1 = createEvt(namespace, resolverName, MESSAGE_EVT_NAME)\n let r = ee.$trigger(e1, [json])\n debugFn(`EMIT_REPLY_TYPE`, e1, r)\n break;\n case ACKNOWLEDGE_REPLY_TYPE:\n let e2 = createEvt(namespace, resolverName, RESULT_EVT_NAME)\n let x = ee.$trigger(e2, [json])\n // debugFn(`ACKNOWLEDGE_REPLY_TYPE`, e2, json)\n break;\n case ERROR_TYPE:\n // this is handled error and we won't throw it\n // we need to extract the error from json\n debugFn(`ERROR_TYPE`)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\n break;\n // @TODO there should be an error type instead of roll into the other two types? TBC\n default:\n // if this happen then we should throw it and halt the operation all together\n debugFn('Unhandled event!', json)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\n // let error = {error: {'message': 'Unhandled event!', type}};\n // ee.$trigger(createEvt(namespace, resolverName, ON_RESULT_PROP_NAME), [error])\n }\n } catch(e) {\n console.error(`ws.onmessage error`, e)\n errorTypeHandler(ee, namespace, false, e, ERROR_EVT_NAME)\n }\n }\n // when the server close the connection\n ws.onclose = function onCloseCallback() {\n debugFn('ws.onclose callback')\n // @TODO what to do with this\n // ee.$trigger(LOGOUT_EVENT_NAME, [namespace])\n }\n // listen to the LOGOUT_EVENT_NAME\n ee.$on(LOGOUT_EVENT_NAME, function closeEvtHandler() {\n try {\n debugFn('terminate ws connection')\n ws.terminate()\n } catch(e) {\n console.error('ws.terminate error', e)\n }\n })\n}\n","// actually binding the event client to the socket client\nimport { getNameFromPayload, getNamespaceInOrder } from 'jsonql-utils/module'\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, JS_WS_NAME } from 'jsonql-constants'\nimport {\n createNspClient,\n createNspAuthClient,\n clientEventHandler,\n triggerNamespacesOnError,\n clearMainEmitEvt,\n disconnect\n} from 'jsonql-ws-client/share'\nimport { wsMainHandler } from './ws-main-handler'\n\n/**\n * Because the nsps can be throw away so it doesn't matter the scope\n * this will get reuse again\n * @param {object} opts configuration\n * @param {object} nspMap from contract\n * @param {string|null} token whether we have the token at run time\n * @return {object} nsps namespace with namespace as key\n */\nconst createNsps = function(opts, nspMap, token) {\n let { nspSet, publicNamespace } = nspMap;\n let login = false;\n let namespaces = [];\n let nsps = {};\n // first we need to binding all the events handler\n if (opts.enableAuth) { // && opts.useJwt\n login = true; // just saying we need to listen to login event\n namespaces = getNamespaceInOrder(nspSet, publicNamespace)\n nsps = namespaces.map((namespace, i) => {\n if (i === 0) {\n if (token) {\n opts.token = token;\n // console.log('create createNspAuthClient at run time', opts)\n return {[namespace]: createNspAuthClient(namespace, opts)}\n }\n return {[namespace]: false}\n }\n return {[namespace]: createNspClient(namespace, opts)}\n }).reduce((first, next) => Object.assign(first, next), {})\n } else {\n let namespace = getNameFromPayload(nspSet)\n namespaces.push(namespace)\n // standard without login\n // the stock version should not have a namespace\n nsps[namespace] = createNspClient(false, opts)\n }\n // return\n return { nsps, namespaces, login }\n}\n\n/**\n * create a ws client\n * @param {object} opts configuration\n * @param {object} nspMap namespace with resolvers\n * @param {object} ee EventEmitter to pass through\n * @return {object} what comes in what goes out\n */\nexport function createClient(opts, nspMap, ee) {\n // arguments that don't change\n const args = [opts, nspMap, ee, wsMainHandler]\n // now create the nsps\n const { token } = opts;\n const { nsps, namespaces, login } = createNsps(opts, nspMap, token)\n // binding the listeners - and it will listen to LOGOUT event\n // to unbind itself, and the above call will bind it again\n Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps]))\n // setup listener\n if (login) {\n ee.$only(LOGIN_EVENT_NAME, function loginEventHandler(tokenLater) {\n // debugFn(`LOGIN_EVENT_NAME called with token:`, tokenLater)\n // @BUG this keep causing an \"Disconnect call failed TypeError: Cannot read property 'readyState' of null\"\n // I think that is because it's not login then it can not be disconnect\n // how do we track this state globally\n // disconnect(nsps, JS_WS_NAME)\n\n // @TODO should we trigger error on this one?\n // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME)\n clearMainEmitEvt(ee, namespaces)\n // console.log('LOGIN_EVENT_NAME', token)\n const newNsps = createNsps(opts, nspMap, tokenLater)\n // rebind it\n Reflect.apply(\n clientEventHandler,\n null,\n args.concat([newNsps.namespaces, newNsps.nsps])\n )\n })\n }\n // return what input\n return { opts, nspMap, ee }\n}\n","// share method to create the wsClientResolver\n\nimport { createWsClient } from './create-ws-client'\nimport { createClient } from './create-client'\n\n/**\n * combine the create client resolver\n * @param {object} ws the different WebSocket module\n * @return {function} the wsClientResolver\n */\nexport default function createClientResolver(ws) {\n const client = createWsClient(ws)\n const authClient = createWsClient(ws, true)\n /**\n * wsClientResolver\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\n return function(opts, nspMap, ee) {\n opts.nspClient = client;\n opts.nspAuthClient = authClient;\n\n // console.log(`contract`, opts.contract)\n\n return createClient(opts, nspMap, ee)\n }\n}\n","// this will be the news style interface that will pass to the jsonql-ws-client\n// then return a function for accepting an opts to generate the final\n// client api\nimport WebSocket from './core/ws'\nimport createClientResolver from './core/create-client-resolver'\n\n/**\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\nexport default createClientResolver(WebSocket)\n","// this is the module entry point for ES6 for client\n// the main will point to the node.js server side setup\nimport { jsonqlWsClientCore } from 'jsonql-ws-client-core'\n\nimport { constProps } from './src/options'\nimport wsClientResolver from './src/ws-client-resolver'\n\n// export back the function and that's it\nexport default jsonqlWsClientCore(wsClientResolver, constProps)\n","// create options\nimport { checkConfigAsync, isNotEmpty } from 'jsonql-params-validator'\nimport { CHECKED_KEY } from 'jsonql-constants'\n// import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors'\n// this should be remove - we have to make it generic\nimport { defaultOptions } from './defaults'\nimport { fixWss, getHostName, objHasProp } from '../utils'\n\n// constant props\nconst defaultConstProps = {\n eventEmitter: null,\n // we unify the two different client into one now\n // only expect different parameter\n nspClient: null,\n nspAuthClient: null,\n // contructed path\n wssPath: ''\n}\n// for export\nconst jsonqlWsDefaultOptions = defaultOptions\nconst jsonqlWsDefaultConstProps = defaultConstProps\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config\n * @param {object} dOpt\n * @param {object} cProps\n * @return {promise} resolve to the checked opitons\n */\nfunction checkOptionsWrapper(config, dOpt, cProps) {\n if (objHasProp(config, CHECKED_KEY)) {\n return Promise.resolve(config)\n }\n return checkConfigAsync(config, dOpt, cProps)\n}\n\n/**\n * check the configuration\n * @param {object} config user supplied configuration\n * @param {object} constProps developer supplied configuration\n * @return {object} after checked\n */\nfunction checkOptions(config, constProps) {\n return checkOptionsWrapper(config, defaultOptions, Object.assign(defaultConstProps, constProps))\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // debug('CONFIGURATION OPTIONS', opts)\n return opts;\n })\n}\n\nexport {\n jsonqlWsDefaultConstProps,\n jsonqlWsDefaultOptions,\n checkOptions\n}\n","// export the required options here to merge with the http client to do a combine check\nimport { jsonqlWsDefaultConstProps, jsonqlWsDefaultOptions } from 'jsonql-ws-client'\nimport { constProps as localConstProps } from './src/options'\n\nconst defaultOptions = jsonqlWsDefaultOptions\nconst constProps = Object.assign(jsonqlWsDefaultConstProps, localConstProps)\n\n\nexport {\n defaultOptions,\n constProps\n}\n","// this is the jsonql client with ws\n// use like import jsonqlClient from '@jsonql/client/ws'\nimport { jsonqlClientModule } from 'jsonql-client/module'\nimport { getPreConfigCheck } from 'jsonql-client/opt'\nimport jsonqlWsClient from '@jsonql/ws'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport {\n defaultOptions as wsDefaultOptions,\n constProps as wsConstProps\n} from '@jsonql/ws/opt'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-client:test:ws')\n// debugFn(jsonqlWsClient)\n\n/**\n * @param {object} Fly the fly module\n * @param {object} [config={}] developer supply options\n * @return {object} the jsonql browser client with ws socket\n * @public\n */\nexport default function createJsonqlHttpWsClient(Fly, config = {}) {\n // @NOTE it return a function to accept the config\n const fn = getPreConfigCheck(wsDefaultOptions, wsConstProps)\n const opts = fn(config)\n opts.socketClient = jsonqlWsClient\n // init the client\n return jsonqlClientModule(Fly, opts)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;ECAA;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"jsonql-client-ws.debug.js","sources":["../../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/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-utils/src/contract.js","../../node_modules/nb-event-service/src/hash-code.js","../../node_modules/jsonql-client/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/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","../../node_modules/jsonql-utils/src/timestamp.js","../../node_modules/store/plugins/defaults.js","../../node_modules/jsonql-client/src/stores/local-store.js","../../node_modules/jsonql-client/src/stores/session-store.js","../../node_modules/jsonql-client/src/stores/index.js","../../node_modules/jsonql-utils/src/params-api.js","../../node_modules/jsonql-utils/src/results.js","../../node_modules/jsonql-client/src/base/store-cls.js","../../node_modules/jsonql-client/src/base/http-cls.js","../../node_modules/jsonql-client/src/base/contract-cls.js","../../node_modules/jsonql-client/src/base/auth-cls.js","../../node_modules/jsonql-client/src/base/base-cls.js","../../node_modules/jsonql-client/src/base/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","../../node_modules/jsonql-client/src/ee.js","../../node_modules/jsonql-client/src/core/methods-generator.js","../../node_modules/jsonql-client/src/core/jsonql-api-generator.js","../../node_modules/jsonql-client/src/options/base-options.js","../../node_modules/jsonql-client/src/options/check-options-async.js","../../node_modules/jsonql-client/src/options/index.js","../../node_modules/jsonql-client/module.js","../../node_modules/jsonql-utils/src/chain-promises.js","../../node_modules/jsonql-utils/src/pre-config-check.js","../../node_modules/jsonql-client/opt.js","../../node_modules/jsonql-ws-client-core/src/options/constants.js","../../node_modules/jsonql-ws-client-core/src/utils/ee.js","../../node_modules/jsonql-ws-client-core/src/utils/process-contract.js","../../node_modules/jsonql-ws-client-core/src/utils/helpers.js","../../node_modules/jsonql-ws-client-core/src/core/respond-handler.js","../../node_modules/jsonql-ws-client-core/src/core/action-call.js","../../node_modules/jsonql-ws-client-core/src/core/setup-callback-api.js","../../node_modules/jsonql-ws-client-core/src/core/setup-resolver.js","../../node_modules/jsonql-ws-client-core/src/core/resolver-methods.js","../../node_modules/jsonql-ws-client-core/src/core/setup-auth-methods.js","../../node_modules/jsonql-ws-client-core/src/core/generator.js","../../node_modules/jsonql-ws-client-core/src/options/index.js","../../node_modules/jsonql-ws-client-core/src/api.js","../../node_modules/@jsonql/ws/src/options/index.js","../../node_modules/@jsonql/ws/src/core/create-ws-client.js","../../node_modules/jsonql-ws-client/src/options/constants.js","../../node_modules/jsonql-ws-client/src/share/create-nsp-client.js","../../node_modules/jsonql-ws-client/src/utils/helpers.js","../../node_modules/jsonql-ws-client/src/share/trigger-namespaces-on-error.js","../../node_modules/jsonql-ws-client/src/share/client-event-handler.js","../../node_modules/@jsonql/ws/src/core/extract-ws-payload.js","../../node_modules/@jsonql/ws/src/core/ws-main-handler.js","../../node_modules/@jsonql/ws/src/core/create-client.js","../../node_modules/@jsonql/ws/src/core/create-client-resolver.js","../../node_modules/@jsonql/ws/src/ws-client-resolver.js","../../node_modules/@jsonql/ws/index.js","../../node_modules/jsonql-ws-client/src/options/index.js","../../node_modules/@jsonql/ws/opt.js","../../ws.js"],"sourcesContent":["/**\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","/**\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","// 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","// 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 * construct the actual end user method, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfigAsync = function(validateSync) {\n /**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n/**\n * copy of above but it's sync, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n getCheckConfigAsync,\n getCheckConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\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// construct the final output 1.5.2\nexport const checkConfigAsync = jsonqlOptions.getCheckConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.getCheckConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/options/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 // cache\n this.__userdata__ = null;\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.__userdata__ = this.decoder(token)\n this.jsonqlUserdata = this.__userdata__\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 \n return { token, userdata: this.__userdata__ }\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","// 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","// 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, userdata}) => {\n ee.$trigger(LOGIN_NAME, token)\n // 1.5.6 return the decoded userdata instead\n return userdata\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) { // this one has a server side logout\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 { // this is only for client side logout\n // @TODO should allow to login particular profile\n auth[logoutHandlerName] = function logoutHandlerFn(profileId = null) {\n jsonqlInstance.postLogoutAction(KEY_WORD, profileId)\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 // 1.5.2 change it to a getter to return a method, pass a name to id which one is which\n client.getLogger = (name) => (...args) => Reflect.apply(jsonqlInstance.log, jsonqlInstance, [name].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","// new module interface for @jsonql/client\n// this will be use with the @jsonql/ws, @jsonql/socketio\nimport { SOCKET_NAME } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\nimport JsonqlBaseClient from './src/base'\nimport getEventEmitter from './src/ee'\nimport generator from './src/core/jsonql-api-generator'\nimport { checkOptionsAsync } from './src/options'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { isObjectHasKey } from 'jsonql-utils/src/generic'\nimport { getContractFromConfig } from './src/utils'\n\n/**\n * Check if the contract has socket field and the socket client is suplied\n * @param {object} client the http client\n * @param {object} contract the json\n * @param {object} config the checked configuration\n * @param {object} socketClient from the original config\n * @return {object} the completed client\n */\nfunction initSocketClient(client, contract, config, socketClient) {\n if (isObjectHasKey(contract, SOCKET_NAME)) {\n if (socketClient) {\n // pass the contract here one more time in case the constProps overwritten it\n config.log = client.getLogger(`jsonql-client:${config.serverType}`)\n config.contract = contract\n config.eventEmitter = client.eventEmitter\n return socketClient(config)\n .then(sc => {\n client[SOCKET_NAME] = sc\n return client\n })\n } else {\n throw new JsonqlError(`initSocketClient`, `socketClient is missing!`)\n }\n }\n return client\n}\n\n/**\n * Main interface for jsonql fetch api\n * @1.4.8 change this to named export to diff this from the other\n * and this is only use with the @jsonql/client to construct the client with ws\n * @param {object} Fly the http engine\n * @param {object} [config={}] configuration\n * @return {object} jsonqlClient\n */\nfunction jsonqlClientModule(fly, config = {}) {\n const { socketClient, debugOn } = config;\n const ee = getEventEmitter(debugOn)\n return checkOptionsAsync(config)\n .then(opts => (\n {\n opts,\n baseClient: new JsonqlBaseClient(fly, opts)\n }\n ))\n // make sure the contract is presented\n .then(({opts, baseClient}) => getContractFromConfig(baseClient, opts.contract)\n .then(contract => (\n {\n opts,\n contract,\n client: generator(baseClient, opts, contract, ee)\n }\n )\n )\n )\n // finally generate the websocket client if any\n .then(({opts, contract, client}) => (\n initSocketClient(client, contract, opts, socketClient)\n ))\n}\n// export it\nexport { jsonqlClientModule }\n","// break it out on its own because\n// it's building from the lodash-es from scratch\n// according to this discussion https://github.com/lodash/lodash/issues/3298\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport merge from 'lodash-es/merge'\n\n/**\n * previously we already make sure the order of the namespaces\n * and attach the auth client to it\n * @param {array} promises array of unresolved promises\n * @param {boolean} asObject if true then merge the result object\n * @return {object} promise resolved with the array of promises resolved results\n */\nexport function chainPromises(promises, asObject = false) {\n return promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResults => (\n currentTask.then(currentResult => (\n asObject === false ? [...chainResults, currentResult] : merge(chainResults, currentResult)\n ))\n ))\n ), Promise.resolve(\n asObject === false ? [] : (isPlainObject(asObject) ? asObject : {})\n ))\n}\n\n\n/**\n * This one return a different result from the chainPromises\n * it will be the same like chainFns that take one promise resolve as the next fn parameter\n * @param {function} initPromise a function that accept param and resolve result\n * @param {array} promises array of function pass that resolve promises\n * @return {promise} resolve the processed result\n */\nexport function chainProcessPromises(initPromise, ...promises) {\n return (...args) => (\n promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResult => (\n currentTask(chainResult)\n )\n )\n ), Reflect.apply(initPromise, null, args))\n )\n}\n","// this will replace the preConfigCheck in jsonql-koa\n// also this will get use in the client as well\n// basically this is just a wrapper method to load everything together\n// and then add the CHECKED_KEY to it\nimport { CHECKED_KEY } from 'jsonql-constants'\n\nimport { chainFns } from './chain-fns'\nimport { timestamp } from './timestamp'\nimport { injectToFn } from './obj-define-props'\n\n/**\n * the rest of the argument will be functions that\n * need to add to the process chain,\n * finally return a function to accept the config\n * @param {object} defaultOptions prepared before hand\n * @param {object} constProps prepare before hand\n * @param {array} fns arguments see description\n * @return {function} to perform the final configuration check\n */\nexport function preConfigCheck(defaultOptions, constProps, ...fns) {\n // should have just add the method to the last\n const finalFn = opt => injectToFn(opt, CHECKED_KEY, timestamp())\n // if there is more than one then chain it otherwise just return the zero idx one\n const fn = Reflect.apply(chainFns, null, fns.concat(finalFn))\n // 0.8.8 add a default property empty object\n return (config = {}) => fn(config, defaultOptions, constProps)\n}\n","// export the options for the pre-check to use\nimport { preConfigCheck } from 'jsonql-utils/module'\nimport { checkConfig } from 'jsonql-params-validator'\nimport merge from 'lodash-es/merge'\n\nimport { appProps, constProps } from './src/options/base-options'\n// just export the function here for use to save repeat coding\n\n/**\n * This will combine the socket client options and merge this one\n * then do a pre-check on both at the same time\n * @param {object} [extraProps = {}]\n * @param {object} [extraConstProps = {}]\n * @return {function} to process the developer options\n */\nexport function getPreConfigCheck(extraProps = {}, extraConstProps = {}) {\n const aProps = merge({}, appProps, extraProps)\n const cProps = merge({}, constProps, extraConstProps)\n\n return preConfigCheck(aProps, cProps, checkConfig)\n}\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME;\nconst WS = JS_WS_NAME;\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!';\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!';\n\nconst MISSING_PROP_ERR = 'Missing property in contract!';\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!';\n\nconst EMIT_EVT = EMIT_REPLY_TYPE;\n\nconst NAMESPACE_KEY = 'namespaceMap';\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!';\n\nconst NOT_ALLOW_OP = 'This operation is not allow!';\n\nconst MY_NAMESPACE = 'myNamespace'\n\nconst CB_FN_NAME = 'on'\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME\n}\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// create a clone version so we know which one we actually is using\nexport default class JsonqlWsEvt extends NBEventService {\n\n constructor(logger) {\n // this ee will always come with the logger\n // because we should take the ee from the configuration\n super({ logger })\n }\n\n get name() {\n return'jsonql-ws-client'\n }\n}\n","// mapping the resolver to their respective nsp\nimport { JSONQL_PATH, NSP_SET, PUBLIC_NAMESPACE } from 'jsonql-constants'\nimport { groupByNamespace, extractSocketPart } from 'jsonql-utils/module'\nimport { JsonqlResolverNotFoundError } from 'jsonql-errors'\n\nimport { MISSING_PROP_ERR } from '../options/constants'\n\n/**\n * Just make sure the object contain what we are looking for\n * @param {object} opts configuration from checkOptions\n * @return {object} the target content\n */\nconst getResolverList = contract => {\n const result = extractSocketPart(contract)\n if (result !== false) {\n return result\n }\n throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR)\n}\n\n/**\n * process the contract first\n * @param {object} opts configuration\n * @return {object} sorted list\n */\nexport default function processContract(opts) {\n const { contract, enableAuth } = opts;\n if (enableAuth) {\n return groupByNamespace(contract)\n }\n return {\n [NSP_SET]: { [JSONQL_PATH]: getResolverList(contract) },\n [PUBLIC_NAMESPACE]: JSONQL_PATH\n }\n}\n","// group all the small functions here\nimport { JS_WS_SOCKET_IO_NAME, JS_WS_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/src/generic'\n\n// we shouldn't do this anymore\nexport const fixWss = (url, serverType) => {\n // ws only allow ws:// path\n if (serverType === JS_WS_NAME) {\n return url.replace('http://', 'ws://')\n }\n return url;\n}\n\n/**\n * get a stock host name from browser\n */\nexport const getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n throw new JsonqlValidationError(e)\n }\n}\n\n/**\n * Unbind the event\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nexport const clearMainEmitEvt = (ee, namespace) => {\n let nsps = toArray(namespace)\n nsps.forEach(n => {\n ee.$off(createEvt(n, EMIT_REPLY_TYPE))\n })\n}\n\n/**\n * @param {object} nsps namespace as key\n * @param {string} type of server\n */\nexport const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => {\n try {\n // @TODO need to figure out a better way here?\n const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate';\n for (let namespace in nsps) {\n let nsp = nsps[namespace]\n if (nsp && nsp[method]) {\n Reflect.apply(nsp[method], null, [])\n }\n }\n } catch(e) {\n // socket.io throw a this.destroy of undefined?\n console.error('Disconnect call failed', e)\n }\n}\n","// breaking it up further to share between methods\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { UNKNOWN_RESULT } from '../options/constants'\nimport { isObjectHasKey } from '../utils'\n\n/**\n * break out to use in different places to handle the return from server\n * @param {object} data from server\n * @param {function} resolver NOT from promise\n * @param {function} rejecter NOT from promise\n * @return {void} nothing\n */\nexport function respondHandler(data, resolver, rejecter) {\n if (isObjectHasKey(data, ERROR_KEY)) {\n // debugFn('-- rejecter called --', data[ERROR_KEY])\n rejecter(data[ERROR_KEY])\n } else if (isObjectHasKey(data, DATA_KEY)) {\n // debugFn('-- resolver called --', data[DATA_KEY])\n resolver(data[DATA_KEY])\n } else {\n // debugFn('-- UNKNOWN_RESULT --', data)\n rejecter({message: UNKNOWN_RESULT, error: data})\n }\n}\n","// the actual trigger call method\nimport { ON_RESULT_PROP_NAME, RESULT_PROP_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { createEvt, toArray } from '../utils'\nimport { respondHandler } from './respond-handler'\n\n/**\n * just wrapper\n * @param {object} ee EventEmitter\n * @param {string} namespace where this belongs\n * @param {string} resolverName resolver\n * @param {boolean} useCallbackStyle use on or not\n * @param {array} args arguments\n * @return {void} nothing\n */\nexport function actionCall(ee, namespace, resolverName, useCallbackStyle, args = []) {\n const eventName = createEvt(namespace, EMIT_REPLY_TYPE)\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME\n // debugFn(`actionCall: ${eventName} --> ${resolverName}`, args)\n ee.$trigger(eventName, [resolverName, toArray(args)])\n // once we trigger there is nothing return from the resolve\n // @TODO if we need the next then call to have the result back\n // then we need to listen to the event callback here as well\n return new Promise((resolver, rejecter) => {\n ee.$on(\n createEvt(namespace, resolverName, RESULT_SUBFIX),\n function actionCallResultHandler(result) {\n // debugFn(`got the first result`, result)\n respondHandler(result, resolver, rejecter)\n }\n )\n })\n}\n","// @TODO using the obj.on syntax to do the same thing\n/*\nThe new callback style `useCallbackStyle` set to true then use this one\nclient.resolverName.on(EVENT_NAME, cb)\n*/\nimport { JsonqlValidationError, JsonqlError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME\n} from 'jsonql-constants'\nimport { CB_FN_NAME } from '../options/constants'\n\nimport { respondHandler } from './respond-handler'\nimport { chainFns, injectToFn, createEvt, toArray, isFunc, isString } from '../utils'\n\n/**\n * Add extra property to the resolver via the getter\n * @param {function} fn the resolver itself\n * @param {object} ee event emitter\n * @param {string} namespace the namespace this belongs to\n * @param {string} resolverName resolver namee\n * @param {object} params from the contract\n * @return {array} same as what goes in\n */\nexport function setupCallbackApi(fn, ee, namespace, resolverName, params) {\n return [\n injectToFn(fn, CB_FN_NAME, function(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch(evtName) {\n case RESULT_PROP_NAME:\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n // register the handler for this message event\n case MESSAGE_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME),\n function onMessageCallback(args) {\n respondHandler(args, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n case READY_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n callback\n )\n break;\n default:\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n new JsonqlError(resolverName, `Unknown event name ${evtName}!`)\n )\n }\n }\n }),\n ee,\n namespace,\n resolverName,\n params\n ]\n}\n","// break up the original setup resolver method here\nimport { JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\nimport { MY_NAMESPACE } from '../options/constants'\nimport { chainFns, objDefineProps, injectToFn, createEvt, toArray, isFunc } from '../utils'\n\nimport { respondHandler } from './respond-handler'\nimport { setupSend } from './setup-send'\nimport { setupCallbackApi } from './setup-callback-api'\n\n/**\n * The first one in the chain\n * @return {array}\n */\nconst setupNamespace = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n injectToFn(fn, MY_NAMESPACE, namespace),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// onResult handler\nconst setupOnResult = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_RESULT_PROP_NAME, function(resultCallback) {\n if (isFunc(resultCallback)) {\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, resultCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// we do need to add the send prop back because it's the only way to deal with\n// bi-directional data stream\nconst setupOnMessage = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_MESSAGE_PROP_NAME, function(messageCallback) {\n // we expect this to be a function\n if (isFunc(messageCallback)) {\n // did that add to the callback\n let onMessageCallback = (args) => {\n respondHandler(args, messageCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n // register the handler for this message event\n ee.$only(createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME), onMessageCallback)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// add an ON_ERROR_PROP_NAME handler\nconst setupOnError = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_ERROR_PROP_NAME, function(resolverErrorHandler) {\n if (isFunc(resolverErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n ee.$only(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), resolverErrorHandler)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n/**\n * Add extra property to the resolver\n * @param {string} namespace where this belongs\n * @param {string} resolverName name as event name\n * @param {object} params from contract\n * @param {function} fn resolver function\n * @param {object} ee EventEmitter\n * @param {boolean} useCallbackStyle new callback style\n * @return {function} resolver\n */\nexport function setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle) {\n // also need to setup a getter to get back the namespace of this resolver\n let args = [setupNamespace]\n useCallbackStyle ? args.push(setupCallbackApi) : args.push(setupOnResult, setupOnMessage, setupOnError)\n args.push(setupSend)\n // get the executor\n const executor = Reflect.apply(chainFns, null, args)\n\n return Reflect.apply(executor, null, [fn, ee, namespace, resolverName, params, useCallbackStyle])\n}\n","// put all the resolver related methods here to make it more clear\n\n// this will be a mini client server architect\n// The reason is when the enableAuth setup - the private route\n// might not be validated, but we need the callable point is ready\n// therefore this part will always take the contract and generate\n// callable api for the developer to setup their front end\n// the only thing is - when they call they might get an error or\n// NOT_LOGIN_IN and they can react to this error accordingly\nimport { JsonqlError, JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n ERROR_PROP_NAME,\n LOGIN_PROP_NAME,\n READY_PROP_NAME,\n ON_ERROR_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n ON_READY_PROP_NAME\n} from 'jsonql-constants'\nimport { actionCall } from './action-call'\nimport {\n createEvt,\n toArray,\n injectToFn,\n objDefineProps,\n chainFns,\n isString,\n isFunc,\n isObjectHasKey\n} from '../utils'\nimport { CB_FN_NAME } from '../options/constants'\n\n/**\n * create the actual function to send message to server\n * @param {object} ee EventEmitter instance\n * @param {string} namespace this resolver end point\n * @param {string} resolverName name of resolver as event name\n * @param {object} params from contract\n * @param {boolean} useCallbackStyle on style or not\n * @return {function} resolver\n */\nexport function createResolver(ee, namespace, resolverName, params, useCallbackStyle) {\n // note we pass the new withResult=true option\n return function(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => actionCall(ee, namespace, resolverName, useCallbackStyle, _args))\n .catch(finalCatch)\n }\n}\n\n/**\n * The problem is the namespace can have more than one\n * and we only have on onError message\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @param {boolean} useCallbackStyle use cb or not\n * @return {object} obj with onError prop\n */\nexport function createNamespaceErrorHandler(obj, ee, nspSet) {\n // using the onError as name\n // @TODO we should follow the convention earlier\n // make this a setter for the obj itself\n return objDefineProps(obj, ON_ERROR_PROP_NAME, function namespaceErrorCallbackHandler(namespaceErrorHandler) {\n if (isFunc(namespaceErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n for (let namespace in nspSet) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ON_ERROR_PROP_NAME), namespaceErrorHandler)\n }\n }\n })\n}\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @return {object} obj with onReady prop\n */\nexport function createOnReadyhandler(obj, ee, nspSet) {\n return objDefineProps(obj, ON_READY_PROP_NAME, function onReadyCallbackHandler(onReadyCallback) {\n if (isFunc(onReadyCallback)) {\n // reduce it down to just one flat level\n ee.$on(ON_READY_PROP_NAME, onReadyCallback)\n }\n })\n}\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * Plus this will check if it's the private namespace that fired the event\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} opts configuration\n * @return {object} obj with onLogin prop\n */\nexport function createOnLoginhandler(obj, ee, opts) {\n if (opts.enableAuth) {\n return objDefineProps(obj, ON_LOGIN_PROP_NAME, function onLoginCallbackHandler(onLoginCallback) {\n if (isFunc(onLoginCallback)) {\n // only one callback can registered with it, TBC\n ee.$only(ON_LOGIN_PROP_NAME, onLoginCallback)\n }\n })\n }\n // just skip it\n return obj\n}\n\n/**\n * when useCallbackStyle=true use this instead of the above method\n * @param {object} obj the base object to attach to\n * @param {object} ee EventEmitter\n * @param {object} nspSet the map\n * @param {object} opts configuration\n * @return {object} obj\n */\nexport function createCallbackHandler(obj, ee, nspSet, opts) {\n return injectToFn(obj, CB_FN_NAME, function onHandler(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch (evtName) {\n case ERROR_PROP_NAME:\n for (let namespace in nspSet) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ERROR_PROP_NAME), callback)\n }\n break;\n case LOGIN_PROP_NAME:\n ee.$only(LOGIN_PROP_NAME, callback)\n break;\n case READY_PROP_NAME:\n ee.$on(READY_PROP_NAME, callback)\n break;\n default:\n ee.$trigger(ERROR_PROP_NAME, new JsonqlError(CB_FN_NAME, `Unknown event name ${evtName}!`))\n }\n }\n // @TODO need to issue another error here!\n })\n}\n","// take out from the resolver-methods\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { injectToFn, chainFns, isString } from '../utils'\n\n/**\n * @TODO this is now become unnecessary because the login is a slave to the\n * http-client - but keep this for now and see what we want to do with it later\n * break out from createAuthMethods to allow chaining call\n * @param {object} obj the main client object\n * @param {object} ee event emitter\n * @param {object} opts configuration\n * @return {array} modified input\n */\nconst setupLoginHandler = (obj, ee, opts) => [\n injectToFn(obj, opts.loginHandlerName, function loginHandler(token) {\n if (token && isString(token)) {\n return ee.$trigger(LOGIN_EVENT_NAME, [token])\n }\n // should trigger a global error instead @TODO\n throw new JsonqlValidationError(opts.loginHandlerName, `Unexpected token ${token}`)\n }),\n ee,\n opts\n]\n\n/**\n * break out from createAuthMethods to allow chaining call - final in chain\n * @param {object} obj the main client object\n * @param {object} ee event emitter\n * @param {object} opts configuration\n * @return {object} the modified obj\n */\nconst setupLogoutHandler = (obj, ee, opts) => (\n injectToFn(obj, opts.logoutHandlerName, function logoutHandler(...args) {\n ee.$trigger(LOGOUT_EVENT_NAME, args)\n })\n)\n\n/**\n * Create auth related methods\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} opts configuration\n * @return {object} obj with auth methods if any\n */\nexport function createAuthMethods(obj, ee, opts) {\n if (opts.enableAuth) {\n return chainFns(setupLoginHandler, setupLogoutHandler)(obj, ee, opts)\n }\n return obj;\n}\n","// resolvers generator\n// we change the interface to return promise from v1.0.3\n// this way we make sure the obj return is correct and timely\nimport { setupResolver } from './setup-resolver'\nimport {\n createResolver,\n createNamespaceErrorHandler,\n createOnReadyhandler,\n createOnLoginhandler,\n createCallbackHandler\n} from './resolver-methods'\nimport { createAuthMethods } from './setup-auth-methods'\nimport { injectToFn, chainProcessPromises } from '../utils'\n\n/**\n * step one get the obj map with the namespace\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {promise} resolve the obj mapped, and start the chain\n */\nfunction getMappedObj(opts, nspMap, ee) {\n let obj = {};\n // let resolverNames = [];\n const { nspSet } = nspMap;\n const { useCallbackStyle } = opts; // @1.2.1\n for (let namespace in nspSet) {\n let list = nspSet[namespace]\n for (let resolverName in list) {\n // resolverNames.push(resolverName)\n let params = list[resolverName]\n let fn = createResolver(ee, namespace, resolverName, params, useCallbackStyle)\n // this should set as a getter therefore can not be overwrite by accident\n // obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee)\n obj = injectToFn(obj, resolverName, setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle))\n }\n }\n // move this two method down to helpers\n // we want these methods visible in debug or console.log\n obj.devHelpers = {\n // this is a helper method for the developer to know the namespace inside\n getNsp: () => Object.keys(nspSet),\n // simple get version trick\n getVer: () => opts.version || 'NOT SET'\n // not really necessary because the dev can query the contract\n // getResolverNames: () => resolverNames\n }\n // resolve the obj to start the chain\n // chain the result to allow the chain processing\n return Promise.resolve(obj)\n}\n\n/**\n * prepare the methods\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {object} of resolvers\n * @public\n */\nexport function generator(opts, nspMap, ee) {\n const { nspSet } = nspMap\n const { useCallbackStyle } = opts;\n let args = [getMappedObj]\n if (useCallbackStyle) {\n args.push(obj => createCallbackHandler(obj, ee, nspSet, opts))\n } else {\n args.push(\n obj1 => createNamespaceErrorHandler(obj1, ee, nspSet),\n obj2 => createOnReadyhandler(obj2, ee, nspSet),\n obj3 => createOnLoginhandler(obj3, ee, opts),\n )\n }\n args.push(obj4 => createAuthMethods(obj4, ee, opts))\n // run it\n const executor = Reflect.apply(chainProcessPromises, null, args)\n return executor(opts, nspMap, ee)\n\n /*\n return getMappedObj(opts, nspMap, ee)\n // add error handler\n .then(obj1 => createNamespaceErrorHandler(obj1, ee, nspSet))\n // add onReady handler\n .then(obj2 => createOnReadyhandler(obj2, ee, nspSet))\n // add onLogin handler -- this is optional\n .then(obj3 => createOnLoginhandler(obj3, ee, opts))\n // Auth related methods -- this is optional\n .then(obj4 => createAuthMethods(obj4, ee, opts))\n */\n}\n","// create options\nimport { checkConfigAsync, isNotEmpty } from 'jsonql-params-validator'\nimport { CHECKED_KEY } from 'jsonql-constants'\n// import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors'\n// this should be remove - we have to make it generic\nimport { defaultOptions } from './defaults'\nimport { fixWss, getHostName, objHasProp } from '../utils'\n\n// constant props\nconst defaultConstProps = {\n eventEmitter: null,\n // we unify the two different client into one now\n // only expect different parameter\n nspClient: null,\n nspAuthClient: null,\n // contructed path\n wssPath: ''\n}\n// for export\nconst jsonqlWsDefaultOptions = defaultOptions\nconst jsonqlWsDefaultConstProps = defaultConstProps\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config\n * @param {object} dOpt\n * @param {object} cProps\n * @return {promise} resolve to the checked opitons\n */\nfunction checkOptionsWrapper(config, dOpt, cProps) {\n if (objHasProp(config, CHECKED_KEY)) {\n return Promise.resolve(config)\n }\n return checkConfigAsync(config, dOpt, cProps)\n}\n\n/**\n * check the configuration\n * @param {object} config user supplied configuration\n * @param {object} constProps developer supplied configuration\n * @return {object} after checked\n */\nfunction checkOptions(config, constProps) {\n return checkOptionsWrapper(config, defaultOptions, Object.assign(defaultConstProps, constProps))\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // debug('CONFIGURATION OPTIONS', opts)\n return opts;\n })\n}\n\nexport {\n jsonqlWsDefaultConstProps,\n jsonqlWsDefaultOptions,\n checkOptions\n}\n","// the top level API\n// The goal is to create a generic method that will able to handle\n// any kind of clients\n// import { injectToFn } from 'jsonql-utils'\nimport { generator } from './core'\nimport { checkOptions } from './options'\nimport { ee, processContract } from './utils'\n\n/**\n * The main interface which will generate the socket clients and map all events\n * @param {object} socketClientResolver this is the one method export by various clients\n * @param {object} [constProps={}] add this to supply the constProps from the downstream client\n * @return {object} the wsClient instance with all the available API\n */\nexport default function wsClient(socketClientResolver, constProps = {}) {\n const { log } = constProps // 1.3.9 if we pass a log method here then we use this\n const logger = log && typeof log === 'function' ? log : () => {}\n // we need to inject property to this client later\n // therefore we need to do it this way\n return (opts) => {\n const { eventEmitter } = opts; // pass from the next level up\n return checkOptions(opts, constProps)\n .then(opts => {\n opts.logger = logger\n return opts;\n })\n .then(opts => ({\n opts,\n nspMap: processContract(opts),\n ee: eventEmitter || new ee(logger)\n }))\n .then(\n ({opts, nspMap, ee}) => socketClientResolver(opts, nspMap, ee)\n )\n .then(\n ({opts, nspMap, ee}) => generator(opts, nspMap, ee)\n )\n .catch(err => {\n console.error(`jsonql-ws-client init error`, err)\n })\n }\n}\n","// where all the base options are\n// create options\nimport { JS_WS_NAME } from 'jsonql-constants'\n// constant props\nconst constProps = {\n version: '__PLACEHOLDER__', // will get replace\n serverType: JS_WS_NAME\n}\n\nexport { constProps }\n","// pass the different type of ws to generate the client\nimport { TOKEN_PARAM_NAME } from 'jsonql-constants'\n/**\n * WebSocket is strict about the path, therefore we need to make sure before it goes in\n * @param {string} url input url\n * @return {string} url with correct path name\n */\nconst fixWss = url => {\n const uri = url.toLowerCase()\n if (uri.indexOf('http') > -1) {\n if (uri.indexOf('https') > -1) {\n return uri.replace('https', 'wss')\n }\n return uri.replace('http', 'ws')\n }\n return uri;\n}\n\n/**\n * The bug was in the wsOptions where ws doesn't need it but socket.io do\n * therefore the object was pass as second parameter!\n * @param {object} WebSocket the client or node version of ws\n * @param {boolean} auth if it's auth then 3 param or just one\n */\nexport function createWsClient(WebSocket, auth = false) {\n if (auth === false) {\n return function createWsClientHandler(url) {\n return new WebSocket(fixWss(url))\n }\n }\n\n /**\n * Create a client with auth token\n * @param {string} url start with ws:// @TODO check this?\n * @param {string} token the jwt token\n * @return {object} ws instance\n */\n return function createWsAuthClientHandler(url, token) {\n const ws_url = fixWss(url)\n // console.log('what happen here?', url, ws_url, token)\n const uri = token && typeof token === 'string' ? `${ws_url}?${TOKEN_PARAM_NAME}=${token}` : ws_url;\n try {\n return new WebSocket(uri)\n } catch(e) {\n console.error('WebSocket Connection Error', e)\n return false;\n }\n }\n}\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME;\nconst WS = JS_WS_NAME;\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!';\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!';\n\nconst MISSING_PROP_ERR = 'Missing property in contract!';\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!';\n\nconst EMIT_EVT = EMIT_REPLY_TYPE;\n\nconst NAMESPACE_KEY = 'namespaceMap';\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!';\n\nconst NOT_ALLOW_OP = 'This operation is not allow!';\n\nconst MY_NAMESPACE = 'myNamespace'\n\nconst CB_FN_NAME = 'on'\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME\n}\n","// since both the ws and io version are\n// pre-defined in the client-generator\n// and this one will have the same parameters\n// and the callback is identical\n\n/**\n * wrapper method to create a nsp without login\n * @param {string|boolean} namespace namespace url could be false\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspClient(namespace, opts) {\n const { hostname, wssPath, wsOptions, nspClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n return nspClient(url, wsOptions)\n}\n\n/**\n * wrapper method to create a nsp with token auth\n * @param {string} namespace namespace url\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspAuthClient(namespace, opts) {\n const { hostname, wssPath, token, wsOptions, nspAuthClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n if (token && typeof token !== 'string') {\n throw new Error(`Expect token to be string, but got ${token}`)\n }\n return nspAuthClient(url, token, wsOptions)\n}\n\nexport {\n createNspClient,\n createNspAuthClient\n}\n","// group all the small functions here\nimport { JS_WS_SOCKET_IO_NAME, JS_WS_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/src/generic'\n\n// we shouldn't do this anymore\nexport const fixWss = (url, serverType) => {\n // ws only allow ws:// path\n if (serverType === JS_WS_NAME) {\n return url.replace('http://', 'ws://')\n }\n return url;\n}\n\n/**\n * get a stock host name from browser\n */\nexport const getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n throw new JsonqlValidationError(e)\n }\n}\n\n/**\n * Unbind the event\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nexport const clearMainEmitEvt = (ee, namespace) => {\n let nsps = toArray(namespace)\n nsps.forEach(n => {\n ee.$off(createEvt(n, EMIT_REPLY_TYPE))\n })\n}\n\n/**\n * @param {object} nsps namespace as key\n * @param {string} type of server\n */\nexport const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => {\n try {\n // @TODO need to figure out a better way here?\n const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate';\n for (let namespace in nsps) {\n let nsp = nsps[namespace]\n if (nsp && nsp[method]) {\n Reflect.apply(nsp[method], null, [])\n }\n }\n } catch(e) {\n // socket.io throw a this.destroy of undefined?\n console.error('Disconnect call failed', e)\n }\n}\n","// this use by client-event-handler\nimport { ON_ERROR_PROP_NAME, ERROR_PROP_NAME } from 'jsonql-constants'\nimport { createEvt } from '../utils'\n\n/**\n * trigger errors on all the namespace onError handler\n * @param {object} ee Event Emitter\n * @param {array} namespaces nsps string\n * @param {string} message optional\n * @param {object} opts configuration\n * @return {void}\n */\nexport function triggerNamespacesOnError(ee, namespaces, message, opts = {}) {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n namespaces.forEach( namespace => {\n ee.$call(createEvt(namespace, ERROR_SUBFIX), [{ message, namespace }])\n })\n}\n","// This is share between different clients so we export it\n// @TODO port what is in the ws-main-handler\n// because all the client side call are via the ee\n// and that makes it re-usable between different client setup\nimport {\n ERROR_PROP_NAME,\n RESULT_PROP_NAME,\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n NOT_LOGIN_ERR_MSG,\n ON_ERROR_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n} from 'jsonql-constants'\nimport { EMIT_EVT, SOCKET_IO, WS } from '../options/constants'\nimport { createEvt, clearMainEmitEvt } from '../utils'\nimport { triggerNamespacesOnError } from './trigger-namespaces-on-error'\n\n/**\n * A fake ee handler\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nconst notLoginWsHandler = (namespace, ee, opts) => {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function notLoginHandlerCallback(resolverName, args) {\n opts.logger('noLoginHandler hijack the ws call', namespace, resolverName, args)\n let error = {\n message: NOT_LOGIN_ERR_MSG\n }\n // It should just throw error here and should not call the result\n // because that's channel for handling normal event not the fake one\n ee.$call(createEvt(namespace, resolverName, ERROR_SUBFIX), [error])\n // also trigger the result handler, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, RESULT_SUBFIX), [{ error }])\n }\n )\n}\n\n/**\n * get the private namespace\n * @param {array} namespaces array\n * @return {*} string on success\n */\nconst getPrivateNamespace = (namespaces) => (\n namespaces.length > 1 ? namespaces[0] : false\n)\n\n/**\n * centralize all the comm in one place\n * @param {object} opts configuration\n * @param {array} namespaces namespace(s)\n * @param {object} ee Event Emitter instance\n * @param {function} bindWsHandler binding the ee to ws --> this is the core bit\n * @param {array} namespaces array of namespace available\n * @param {object} nsps namespaced nsp\n * @return {void} nothing\n */\nexport function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) {\n // @1.1.3 add isPrivate prop to id which namespace is the private nsp\n // then we can use this prop to determine if we need to fire the ON_LOGIN_PROP_NAME event\n const privateNamespace = getPrivateNamespace(namespaces)\n let isPrivate = false;\n // loop\n // @BUG for io this has to be in order the one with auth need to get call first\n // The order of login is very import we need to run a waterfall here to make sure\n // one is execute then the other\n namespaces.forEach(namespace => {\n isPrivate = privateNamespace === namespace;\n if (nsps[namespace]) {\n opts.logger('call bindWsHandler', isPrivate, namespace)\n let args = [namespace, nsps[namespace], ee, isPrivate, opts]\n if (opts.serverType === SOCKET_IO) {\n let { nspSet } = nspMap;\n args.push(nspSet[namespace])\n }\n Reflect.apply(bindWsHandler, null, args)\n } else {\n // a dummy placeholder\n notLoginWsHandler(namespace, ee, opts)\n }\n })\n // this will be available regardless enableAuth\n // because the server can log the client out\n ee.$on(LOGOUT_EVENT_NAME, function logoutEvtHandler() {\n opts.logger('LOGOUT_EVENT_NAME')\n // disconnect(nsps, opts.serverType)\n // we need to issue error to all the namespace onError handler\n triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME)\n // rebind all of the handler to the fake one\n namespaces.forEach( namespace => {\n clearMainEmitEvt(ee, namespace)\n // clear out the nsp\n nsps[namespace] = false;\n // add a NOT LOGIN error if call\n notLoginWsHandler(namespace, ee, opts)\n })\n })\n}\n","// take the ws reply data for use\nimport { WS_EVT_NAME, WS_DATA_NAME, WS_REPLY_TYPE } from 'jsonql-constants'\nimport { isString } from 'jsonql-params-validator'\nimport { isObjectHasKey } from 'jsonql-utils/module'\nimport { JsonqlError, clientErrorsHandler } from 'jsonql-errors'\n\nconst keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ]\n\n/**\n * @param {object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nconst isWsReply = payload => {\n const { data } = payload;\n if (data) {\n let result = keys.filter(key => isObjectHasKey(data, key))\n return (result.length === keys.length) ? data : false;\n }\n return false;\n}\n\n/**\n * @param {object} payload This is the entire ws Event Object\n * @return {object} false on failed\n */\nconst extractWsPayload = payload => {\n const { data } = payload;\n let json = isString(data) ? JSON.parse(data) : data;\n // debugFn('extractWsPayload', json)\n let fdata;\n if ((fdata = isWsReply(json)) !== false) {\n return {\n resolverName: fdata[WS_EVT_NAME],\n data: fdata[WS_DATA_NAME],\n type: fdata[WS_REPLY_TYPE]\n };\n }\n throw new JsonqlError('payload can not be decoded', payload)\n}\n// export it\nexport default extractWsPayload\n","// the WebSocket main handler\nimport {\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n ACKNOWLEDGE_REPLY_TYPE,\n EMIT_REPLY_TYPE,\n ERROR_TYPE,\n\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_READY_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME,\n READY_PROP_NAME,\n LOGIN_PROP_NAME\n} from 'jsonql-constants'\nimport { createQueryStr, createEvt } from 'jsonql-utils/module'\nimport extractWsPayload from './extract-ws-payload'\nconst dummyLogger = () => {}\n/**\n * under extremely circumstances we might not even have a resolverName, then\n * we issue a global error for the developer to catch it\n * @param {object} ee event emitter\n * @param {string} namespace nsp\n * @param {string} resolverName resolver\n * @param {object} json decoded payload or error object\n * @param {string} ERROR_EVT_NAME the error event name\n * @return {undefined} nothing return\n */\nconst errorTypeHandler = (ee, namespace, resolverName, json, ERROR_EVT_NAME) => {\n let evt = [namespace]\n if (resolverName) {\n evt.push(resolverName)\n }\n evt.push(ERROR_EVT_NAME)\n let evtName = Reflect.apply(createEvt, null, evt)\n // test if there is a data field\n let payload = json.data || json;\n ee.$trigger(evtName, [payload])\n}\n\n/**\n * Binding the even to socket normally\n * @param {string} namespace\n * @param {object} ws the nsp\n * @param {object} ee EventEmitter\n * @param {boolean} isPrivate to id if this namespace is private or not\n * @param {object} opts configuration\n * @return {object} promise resolve after the onopen event\n */\nexport function wsMainHandler(namespace, ws, ee, isPrivate, opts) {\n\n const debugFn = opts.log || dummyLogger\n\n const { useCallbackStyle } = opts;\n const READY_EVT_NAME = useCallbackStyle ? READY_PROP_NAME : ON_READY_PROP_NAME;\n const LOGIN_EVT_NAME = useCallbackStyle ? LOGIN_PROP_NAME : ON_LOGIN_PROP_NAME;\n const MESSAGE_EVT_NAME = useCallbackStyle ? MESSAGE_PROP_NAME : ON_MESSAGE_PROP_NAME;\n const RESULT_EVT_NAME = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n const ERROR_EVT_NAME = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n // connection open\n ws.onopen = function onOpenCallback() {\n debugFn('ws.onopen listened')\n // we just call the onReady\n ee.$call(READY_EVT_NAME, namespace)\n // need an extra parameter here to id the private nsp\n if (isPrivate) {\n console.log(`isPrivate and fire the ${LOGIN_EVT_NAME}`)\n ee.$call(LOGIN_EVT_NAME, namespace)\n }\n // add listener only after the open is called\n ee.$only(\n createEvt(namespace, EMIT_REPLY_TYPE),\n function wsMainOnEvtHandler(resolverName, args) {\n debugFn('calling server', resolverName, args)\n ws.send(\n createQueryStr(resolverName, args)\n )\n }\n )\n }\n\n // reply\n // If we change it to the event callback style\n // then the payload will just be the payload and fucks up the extractWsPayload call @TODO\n ws.onmessage = function onMessageCallback(payload) {\n // console.log(`on.message`, typeof payload, payload)\n try {\n const json = extractWsPayload(payload)\n const { resolverName, type } = json;\n debugFn('Hear from server', type, json)\n switch (type) {\n case EMIT_REPLY_TYPE:\n let e1 = createEvt(namespace, resolverName, MESSAGE_EVT_NAME)\n let r = ee.$trigger(e1, [json])\n debugFn(`EMIT_REPLY_TYPE`, e1, r)\n break;\n case ACKNOWLEDGE_REPLY_TYPE:\n let e2 = createEvt(namespace, resolverName, RESULT_EVT_NAME)\n let x = ee.$trigger(e2, [json])\n // debugFn(`ACKNOWLEDGE_REPLY_TYPE`, e2, json)\n break;\n case ERROR_TYPE:\n // this is handled error and we won't throw it\n // we need to extract the error from json\n debugFn(`ERROR_TYPE`)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\n break;\n // @TODO there should be an error type instead of roll into the other two types? TBC\n default:\n // if this happen then we should throw it and halt the operation all together\n debugFn('Unhandled event!', json)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\n // let error = {error: {'message': 'Unhandled event!', type}};\n // ee.$trigger(createEvt(namespace, resolverName, ON_RESULT_PROP_NAME), [error])\n }\n } catch(e) {\n console.error(`ws.onmessage error`, e)\n errorTypeHandler(ee, namespace, false, e, ERROR_EVT_NAME)\n }\n }\n // when the server close the connection\n ws.onclose = function onCloseCallback() {\n debugFn('ws.onclose callback')\n // @TODO what to do with this\n // ee.$trigger(LOGOUT_EVENT_NAME, [namespace])\n }\n // listen to the LOGOUT_EVENT_NAME\n ee.$on(LOGOUT_EVENT_NAME, function closeEvtHandler() {\n try {\n debugFn('terminate ws connection')\n ws.terminate()\n } catch(e) {\n console.error('ws.terminate error', e)\n }\n })\n}\n","// actually binding the event client to the socket client\nimport { getNameFromPayload, getNamespaceInOrder } from 'jsonql-utils/module'\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, JS_WS_NAME } from 'jsonql-constants'\nimport {\n createNspClient,\n createNspAuthClient,\n clientEventHandler,\n triggerNamespacesOnError,\n clearMainEmitEvt,\n disconnect\n} from 'jsonql-ws-client/share'\nimport { wsMainHandler } from './ws-main-handler'\n\n/**\n * Because the nsps can be throw away so it doesn't matter the scope\n * this will get reuse again\n * @param {object} opts configuration\n * @param {object} nspMap from contract\n * @param {string|null} token whether we have the token at run time\n * @return {object} nsps namespace with namespace as key\n */\nconst createNsps = function(opts, nspMap, token) {\n let { nspSet, publicNamespace } = nspMap;\n let login = false;\n let namespaces = [];\n let nsps = {};\n // first we need to binding all the events handler\n if (opts.enableAuth) { // && opts.useJwt\n login = true; // just saying we need to listen to login event\n namespaces = getNamespaceInOrder(nspSet, publicNamespace)\n nsps = namespaces.map((namespace, i) => {\n if (i === 0) {\n if (token) {\n opts.token = token;\n // console.log('create createNspAuthClient at run time', opts)\n return {[namespace]: createNspAuthClient(namespace, opts)}\n }\n return {[namespace]: false}\n }\n return {[namespace]: createNspClient(namespace, opts)}\n }).reduce((first, next) => Object.assign(first, next), {})\n } else {\n let namespace = getNameFromPayload(nspSet)\n namespaces.push(namespace)\n // standard without login\n // the stock version should not have a namespace\n nsps[namespace] = createNspClient(false, opts)\n }\n // return\n return { nsps, namespaces, login }\n}\n\n/**\n * create a ws client\n * @param {object} opts configuration\n * @param {object} nspMap namespace with resolvers\n * @param {object} ee EventEmitter to pass through\n * @return {object} what comes in what goes out\n */\nexport function createClient(opts, nspMap, ee) {\n // arguments that don't change\n const args = [opts, nspMap, ee, wsMainHandler]\n // now create the nsps\n const { token } = opts;\n const { nsps, namespaces, login } = createNsps(opts, nspMap, token)\n // binding the listeners - and it will listen to LOGOUT event\n // to unbind itself, and the above call will bind it again\n Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps]))\n // setup listener\n if (login) {\n ee.$only(LOGIN_EVENT_NAME, function loginEventHandler(tokenLater) {\n // debugFn(`LOGIN_EVENT_NAME called with token:`, tokenLater)\n // @BUG this keep causing an \"Disconnect call failed TypeError: Cannot read property 'readyState' of null\"\n // I think that is because it's not login then it can not be disconnect\n // how do we track this state globally\n // disconnect(nsps, JS_WS_NAME)\n\n // @TODO should we trigger error on this one?\n // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME)\n clearMainEmitEvt(ee, namespaces)\n // console.log('LOGIN_EVENT_NAME', token)\n const newNsps = createNsps(opts, nspMap, tokenLater)\n // rebind it\n Reflect.apply(\n clientEventHandler,\n null,\n args.concat([newNsps.namespaces, newNsps.nsps])\n )\n })\n }\n // return what input\n return { opts, nspMap, ee }\n}\n","// share method to create the wsClientResolver\n\nimport { createWsClient } from './create-ws-client'\nimport { createClient } from './create-client'\n\n/**\n * combine the create client resolver\n * @param {object} ws the different WebSocket module\n * @return {function} the wsClientResolver\n */\nexport default function createClientResolver(ws) {\n const client = createWsClient(ws)\n const authClient = createWsClient(ws, true)\n /**\n * wsClientResolver\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\n return function(opts, nspMap, ee) {\n opts.nspClient = client;\n opts.nspAuthClient = authClient;\n\n // console.log(`contract`, opts.contract)\n\n return createClient(opts, nspMap, ee)\n }\n}\n","// this will be the news style interface that will pass to the jsonql-ws-client\n// then return a function for accepting an opts to generate the final\n// client api\nimport WebSocket from './core/ws'\nimport createClientResolver from './core/create-client-resolver'\n\n/**\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\nexport default createClientResolver(WebSocket)\n","// this is the module entry point for ES6 for client\n// the main will point to the node.js server side setup\nimport { jsonqlWsClientCore } from 'jsonql-ws-client-core'\n\nimport { constProps } from './src/options'\nimport wsClientResolver from './src/ws-client-resolver'\n\n// export back the function and that's it\nexport default jsonqlWsClientCore(wsClientResolver, constProps)\n","// create options\nimport { checkConfigAsync, isNotEmpty } from 'jsonql-params-validator'\nimport { CHECKED_KEY } from 'jsonql-constants'\n// import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors'\n// this should be remove - we have to make it generic\nimport { defaultOptions } from './defaults'\nimport { fixWss, getHostName, objHasProp } from '../utils'\n\n// constant props\nconst defaultConstProps = {\n eventEmitter: null,\n // we unify the two different client into one now\n // only expect different parameter\n nspClient: null,\n nspAuthClient: null,\n // contructed path\n wssPath: ''\n}\n// for export\nconst jsonqlWsDefaultOptions = defaultOptions\nconst jsonqlWsDefaultConstProps = defaultConstProps\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config\n * @param {object} dOpt\n * @param {object} cProps\n * @return {promise} resolve to the checked opitons\n */\nfunction checkOptionsWrapper(config, dOpt, cProps) {\n if (objHasProp(config, CHECKED_KEY)) {\n return Promise.resolve(config)\n }\n return checkConfigAsync(config, dOpt, cProps)\n}\n\n/**\n * check the configuration\n * @param {object} config user supplied configuration\n * @param {object} constProps developer supplied configuration\n * @return {object} after checked\n */\nfunction checkOptions(config, constProps) {\n return checkOptionsWrapper(config, defaultOptions, Object.assign(defaultConstProps, constProps))\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // debug('CONFIGURATION OPTIONS', opts)\n return opts;\n })\n}\n\nexport {\n jsonqlWsDefaultConstProps,\n jsonqlWsDefaultOptions,\n checkOptions\n}\n","// export the required options here to merge with the http client to do a combine check\nimport { jsonqlWsDefaultConstProps, jsonqlWsDefaultOptions } from 'jsonql-ws-client'\nimport { constProps as localConstProps } from './src/options'\n\nconst defaultOptions = jsonqlWsDefaultOptions\nconst constProps = Object.assign(jsonqlWsDefaultConstProps, localConstProps)\n\n\nexport {\n defaultOptions,\n constProps\n}\n","// this is the jsonql client with ws\n// use like import jsonqlClient from '@jsonql/client/ws'\nimport { jsonqlClientModule } from 'jsonql-client/module'\nimport { getPreConfigCheck } from 'jsonql-client/opt'\nimport jsonqlWsClient from '@jsonql/ws'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport {\n defaultOptions as wsDefaultOptions,\n constProps as wsConstProps\n} from '@jsonql/ws/opt'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-client:test:ws')\n// debugFn(jsonqlWsClient)\n\n/**\n * @param {object} Fly the fly module\n * @param {object} [config={}] developer supply options\n * @return {object} the jsonql browser client with ws socket\n * @public\n */\nexport default function createJsonqlHttpWsClient(Fly, config = {}) {\n // @NOTE it return a function to accept the config\n const fn = getPreConfigCheck(wsDefaultOptions, wsConstProps)\n const opts = fn(config)\n opts.socketClient = jsonqlWsClient\n // init the client\n return jsonqlClientModule(Fly, opts)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;ECAA;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js b/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js index e70ba57f..c582eb93 100644 --- a/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js +++ b/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js @@ -1,6 +1,6 @@ QUnit.test('jsonql client should have http and ws clients', function(assert) { var done = [] - var ctn = 3; // just change this number as the test increase + var ctn = 4; // just change this number as the test increase for (var i = 0; i < ctn; ++i) { done.push(assert.async()) } @@ -20,20 +20,26 @@ QUnit.test('jsonql client should have http and ws clients', function(assert) { .catch((err) => { console.error('login error', err) // @BUG this is actually wrong but need to fix this in jsonql-koa - assert.equal('JsonqlResolverAppError', err.className) + assert.equal('JsonqlResolverAppError', err.className, 'When throw a JsonqlAuthorisationError @BUG! inside the resolver should able to catch it back') done[1]() // now test the correct login client.auth.login('joel') .then(result => { console.info('login result', result) - - + assert.equal('joel', result.name, 'Expect the login result to be the user object return from resolver on the server side') done[2]() }) - - }) - + // listen to the onLogin event + client.socket.onLogin = function(ns) { + console.info('--- onLogin ---', ns) + done[3]() + } + + client.socket.onReady = function(ns) { + console.info('--- onReady ---', ns) + + } }) .catch(function(err) { diff --git a/packages/@jsonql/ws/src/core/ws-main-handler.js b/packages/@jsonql/ws/src/core/ws-main-handler.js index dd9caac0..bc798945 100644 --- a/packages/@jsonql/ws/src/core/ws-main-handler.js +++ b/packages/@jsonql/ws/src/core/ws-main-handler.js @@ -69,7 +69,7 @@ export function wsMainHandler(namespace, ws, ee, isPrivate, opts) { ee.$call(READY_EVT_NAME, namespace) // need an extra parameter here to id the private nsp if (isPrivate) { - console.log(`isPrivate and fire the ${LOGIN_EVT_NAME}`) + debugFn(`isPrivate and fire the ${LOGIN_EVT_NAME}`) ee.$call(LOGIN_EVT_NAME, namespace) } // add listener only after the open is called diff --git a/packages/ws-client-core/package.json b/packages/ws-client-core/package.json index e8762fc3..b17a2fdf 100644 --- a/packages/ws-client-core/package.json +++ b/packages/ws-client-core/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-ws-client-core", - "version": "0.2.0", + "version": "0.3.0", "description": "This is the jsonql Web Socket client core library for Node and Browser. Not for direct use.", "main": "main.js", "module": "index.js", diff --git a/packages/ws-client-core/src/api.js b/packages/ws-client-core/src/api.js index a1819347..413b159f 100644 --- a/packages/ws-client-core/src/api.js +++ b/packages/ws-client-core/src/api.js @@ -5,7 +5,7 @@ import { generator } from './core' import { checkOptions } from './options' import { ee, processContract } from './utils' - +const dummyLogger = () => {} /** * The main interface which will generate the socket clients and map all events * @param {object} socketClientResolver this is the one method export by various clients @@ -14,7 +14,7 @@ import { ee, processContract } from './utils' */ export default function wsClient(socketClientResolver, constProps = {}) { const { log } = constProps // 1.3.9 if we pass a log method here then we use this - const logger = log && typeof log === 'function' ? log : () => {} + const logger = log && typeof log === 'function' ? log : dummyLogger // we need to inject property to this client later // therefore we need to do it this way return (opts) => { diff --git a/packages/ws-client-core/src/core/generator.js b/packages/ws-client-core/src/core/generator.js index eb4c60f5..969807a7 100644 --- a/packages/ws-client-core/src/core/generator.js +++ b/packages/ws-client-core/src/core/generator.js @@ -60,7 +60,7 @@ function getMappedObj(opts, nspMap, ee) { */ export function generator(opts, nspMap, ee) { const { nspSet } = nspMap - const { useCallbackStyle } = opts; + const { useCallbackStyle, enableAuth } = opts; let args = [getMappedObj] if (useCallbackStyle) { args.push(obj => createCallbackHandler(obj, ee, nspSet, opts)) @@ -68,23 +68,16 @@ export function generator(opts, nspMap, ee) { args.push( obj1 => createNamespaceErrorHandler(obj1, ee, nspSet), obj2 => createOnReadyhandler(obj2, ee, nspSet), - obj3 => createOnLoginhandler(obj3, ee, opts), ) + if (enableAuth) { + args.push(obj3 => createOnLoginhandler(obj3, ee, opts)) + } + } + // this only apply to when enableAuth = true + if (enableAuth) { + args.push(obj4 => createAuthMethods(obj4, ee, opts)) } - args.push(obj4 => createAuthMethods(obj4, ee, opts)) // run it const executor = Reflect.apply(chainProcessPromises, null, args) return executor(opts, nspMap, ee) - - /* - return getMappedObj(opts, nspMap, ee) - // add error handler - .then(obj1 => createNamespaceErrorHandler(obj1, ee, nspSet)) - // add onReady handler - .then(obj2 => createOnReadyhandler(obj2, ee, nspSet)) - // add onLogin handler -- this is optional - .then(obj3 => createOnLoginhandler(obj3, ee, opts)) - // Auth related methods -- this is optional - .then(obj4 => createAuthMethods(obj4, ee, opts)) - */ } diff --git a/packages/ws-client-core/src/core/resolver-methods.js b/packages/ws-client-core/src/core/resolver-methods.js index e86afd15..66daf621 100644 --- a/packages/ws-client-core/src/core/resolver-methods.js +++ b/packages/ws-client-core/src/core/resolver-methods.js @@ -129,7 +129,7 @@ export function createCallbackHandler(obj, ee, nspSet, opts) { ee.$on(createEvt(namespace, ERROR_PROP_NAME), callback) } break; - case LOGIN_PROP_NAME: + case LOGIN_PROP_NAME: // @TODO should only available when enableAuth=true ee.$only(LOGIN_PROP_NAME, callback) break; case READY_PROP_NAME: diff --git a/packages/ws-client-core/src/core/setup-callback-api.js b/packages/ws-client-core/src/core/setup-callback-api.js index 84cd5c2e..4380c34b 100644 --- a/packages/ws-client-core/src/core/setup-callback-api.js +++ b/packages/ws-client-core/src/core/setup-callback-api.js @@ -10,7 +10,11 @@ import { ERROR_KEY, ERROR_PROP_NAME, MESSAGE_PROP_NAME, - RESULT_PROP_NAME + RESULT_PROP_NAME, + READY_PROP_NAME, + ON_ERROR_PROP_NAME, + ON_RESULT_PROP_NAME, + ON_MESSAGE_PROP_NAME } from 'jsonql-constants' import { CB_FN_NAME } from '../options/constants' diff --git a/packages/ws-client-core/tests/on.test.js b/packages/ws-client-core/tests/on.test.js index 6a273b43..7ded4482 100644 --- a/packages/ws-client-core/tests/on.test.js +++ b/packages/ws-client-core/tests/on.test.js @@ -88,35 +88,35 @@ test.serial('It should able to create the WebSocket client object', t => { t.falsy( Object.getOwnPropertyDescriptor(client, ON_LOGIN_PROP_NAME), `the client object should have ${ON_LOGIN_PROP_NAME} prop`) }) -// @TODO this is not correct +// @TODO Fix the coding error but this is still not working test.serial.cb.skip('The ws client can connect to the WebSocket server public interface', t => { t.plan(3) let ctn = 0; const client = t.context.client; - client.onReady = function testOnReadyCallback() { + client.on(ON_READY_PROP_NAME, function testOnReadyCallback() { debug(`onReady executed`) - } + }) - client.pinging.onResult = function testonResultCallback(result) { + client.pinging.on(ON_RESULT_PROP_NAME, function testonResultCallback(result) { ++ctn debug(`[${ctn}] result`, result) t.pass() - } + }) - client.pinging.onError = function testOnErrorCallback(err) { + client.pinging.on(ON_ERROR_PROP_NAME, function testOnErrorCallback(err) { ++ctn; debug(`[got error]`, err.error.detail[0]) t.pass() - } + }) debug(`${ON_MESSAGE_PROP_NAME}`) - client.pinging.onMessage = function testOnMessageCallback(msg) { + client.pinging.on(ON_MESSAGE_PROP_NAME, function testOnMessageCallback(msg) { ++ctn; debug(`[${ctn}] ${ON_MESSAGE_PROP_NAME}`, msg) t.pass() t.end() - } + }) client.pinging('xxx') .then(msg => { diff --git a/packages/ws-client-core/tests/test-node.test.js b/packages/ws-client-core/tests/test-node.test.js index 24a6857f..a889350c 100644 --- a/packages/ws-client-core/tests/test-node.test.js +++ b/packages/ws-client-core/tests/test-node.test.js @@ -88,6 +88,8 @@ test.serial.cb('The ws client can connect to the WebSocket server public interfa let ctn = 0; const client = t.context.client; + debug('ws client', client) + client.onReady = function testOnReadyCallback() { debug(`onReady executed`) } -- Gitee From 8b1e14462475ff82fc861885da8755bf719b8a9b Mon Sep 17 00:00:00 2001 From: joelchu Date: Wed, 11 Dec 2019 14:16:16 +0800 Subject: [PATCH 2/3] @jsonql/ws 1.0.1 --- packages/@jsonql/ws/dist/jsonql-ws-client.umd.js | 2 +- packages/@jsonql/ws/node.js | 2 +- packages/@jsonql/ws/package.json | 4 ++-- packages/@jsonql/ws/src/core/create-client.js | 12 ++++++------ packages/@jsonql/ws/src/core/create-ws-client.js | 6 +++--- packages/@jsonql/ws/src/core/extract-ws-payload.js | 10 +++++----- packages/@jsonql/ws/src/core/ws-main-handler.js | 2 ++ 7 files changed, 20 insertions(+), 18 deletions(-) diff --git a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js index fadce466..eb27f180 100644 --- a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js +++ b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlWsClient=e()}(this,(function(){"use strict";var t=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),e=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),r=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),n=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),o=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),a=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),i=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),u=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),c=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),f=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),s=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),l="data",p="error",h="jsonql",v="query",g="mutation",d="socket",y="TS",b="type",_="optional",m="enumv",w="args",j="checker",O="alias",S="__checked__",k="No message",E="__login__",$="__logout__",A="emit",T="acknowledge",P="error",N="nspSet",R="publicNamespace",z="onMessage",x="onResult",C="onError",q="onReady",M="onLogin",F="message",W="result",L="error",J="ready",U="login",D="token",I=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),V=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);function B(l){if(Array.isArray(l))throw new s("",l);var p=l.message||k,h=l.detail||l;switch(!0){case l instanceof t:throw new t(p,h);case l instanceof e:throw new e(p,h);case l instanceof r:throw new r(p,h);case l instanceof n:throw new n(p,h);case l instanceof o:throw new o(p,h);case l instanceof a:throw new a(p,h);case l instanceof i:throw new i(p,h);case l instanceof u:throw new u(p,h);case l instanceof c:throw new c(p,h);case l instanceof f:throw new f(p,h);case l instanceof s:throw new s(p,h);case l instanceof V:throw new V(p,h);default:throw new I(p,h)}}var H="UKNNOWN RESULT!",Y="on",G="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},K="object"==typeof G&&G&&G.Object===Object&&G,Q="object"==typeof self&&self&&self.Object===Object&&self,X=K||Q||Function("return this")(),Z=X.Symbol;function tt(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 a=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 qt=function(t){return!!et(t)||null!=t&&""!==Ct(t)},Mt="[object Number]";function Ft(t){return function(t){return"number"==typeof t||lt(t)&&st(t)==Mt}(t)&&t!=+t}var Wt="[object String]";function Lt(t){return"string"==typeof t||!et(t)&<(t)&&st(t)==Wt}var Jt=function(t){return!Lt(t)&&!Ft(parseFloat(t))},Ut=function(t){return""!==Ct(t)&&Lt(t)},Dt=function(t){return null!=t&&"boolean"==typeof t},It=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==Ct(t)&&(!1===e||!0===e&&null!==t)},Vt=b,Bt=_,Ht=m,Yt=w,Gt=j,Kt=O,Qt="continue",Xt=function(t){switch(t){case"number":return Jt;case"string":return Ut;case"boolean":return Dt;default:return It}},Zt=function(t,e){return void 0===e&&(e=""),!!et(t)&&(""===e||""===Ct(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};function re(t,e){return function(r){return t(e(r))}}var ne=re(Object.getPrototypeOf,Object),oe="[object Object]",ae=Function.prototype,ie=Object.prototype,ue=ae.toString,ce=ie.hasOwnProperty,fe=ue.call(Object);function se(t){if(!lt(t)||st(t)!=oe)return!1;var e=ne(t);if(null===e)return!0;var r=ce.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&ue.call(r)==fe}var le,pe=function(t,e,r){for(var n=-1,o=Object(t),a=r(t),i=a.length;i--;){var u=a[le?i:++n];if(!1===e(o[u],u,o))break}return t};var he="[object Arguments]";function ve(t){return lt(t)&&st(t)==he}var ge=Object.prototype,de=ge.hasOwnProperty,ye=ge.propertyIsEnumerable,be=ve(function(){return arguments}())?ve:function(t){return lt(t)&&de.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?X.Buffer:void 0,je=(we?we.isBuffer:void 0)||function(){return!1},Oe=9007199254740991,Se=/^(?:0|[1-9]\d*)$/;function ke(t,e){var r=typeof t;return!!(e=null==e?Oe:e)&&("number"==r||"symbol"!=r&&Se.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=Ee}var Ae={};Ae["[object Float32Array]"]=Ae["[object Float64Array]"]=Ae["[object Int8Array]"]=Ae["[object Int16Array]"]=Ae["[object Int32Array]"]=Ae["[object Uint8Array]"]=Ae["[object Uint8ClampedArray]"]=Ae["[object Uint16Array]"]=Ae["[object Uint32Array]"]=!0,Ae["[object Arguments]"]=Ae["[object Array]"]=Ae["[object ArrayBuffer]"]=Ae["[object Boolean]"]=Ae["[object DataView]"]=Ae["[object Date]"]=Ae["[object Error]"]=Ae["[object Function]"]=Ae["[object Map]"]=Ae["[object Number]"]=Ae["[object Object]"]=Ae["[object RegExp]"]=Ae["[object Set]"]=Ae["[object String]"]=Ae["[object WeakMap]"]=!1;var Te,Pe="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ne=Pe&&"object"==typeof module&&module&&!module.nodeType&&module,Re=Ne&&Ne.exports===Pe&&K.process,ze=function(){try{var t=Ne&&Ne.require&&Ne.require("util").types;return t||Re&&Re.binding&&Re.binding("util")}catch(t){}}(),xe=ze&&ze.isTypedArray,Ce=xe?(Te=xe,function(t){return Te(t)}):function(t){return lt(t)&&$e(t.length)&&!!Ae[st(t)]},qe=Object.prototype.hasOwnProperty;function Me(t,e){var r=et(t),n=!r&&be(t),o=!r&&!n&&je(t),a=!r&&!n&&!o&&Ce(t),i=r||n||o||a,u=i?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=X["__core-js_shared__"],nr=(er=/[^.]+$/.exec(rr&&rr.keys&&rr.keys.IE_PROTO||""))?"Symbol(src)_1."+er:"";var or=Function.prototype.toString;function ar(t){if(null!=t){try{return or.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ir=/^\[object .+?Constructor\]$/,ur=Function.prototype,cr=Object.prototype,fr=ur.toString,sr=cr.hasOwnProperty,lr=RegExp("^"+fr.call(sr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function pr(t){return!(!Ue(t)||function(t){return!!nr&&nr in t}(t))&&(He(t)?lr:ir).test(ar(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 vr=hr(X,"Map"),gr=hr(Object,"create");var dr="__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 f=a.get(t);if(f&&a.get(e))return f==e;var s=-1,l=!0,p=r&Tr?new Er:void 0;for(a.set(t,e),a.set(e,t);++se.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},Kn=function(t,e){var r,n,o,a,i;switch(!0){case"object"===t:return o=(n=e).arg,a=n.param,i=[o],Array.isArray(a.keys)&&a.keys.length&&i.push(a.keys),!Reflect.apply(Gn,null,i);case"array"===t:return!Zt(e.arg);case!1!==(r=te(t)):return!ee(e,r);default:return!Xt(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(!Zt(e))throw new I("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 I("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 a=r>=n||!!e[r].optional,i=e[r]||{type:o,name:"_"+r};return{arg:a?Qn(t,i):t,index:r,param:i,optional:a}}));default:throw new I("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),a=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!qt(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={})[p]=a,n[l]=o.map((function(t){return t.arg})),n):a},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?X.Buffer:void 0,ao=oo?oo.allocUnsafe:void 0;function io(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new Nr(n).set(new Nr(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(!Ue(e))return{};if(uo)return uo(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 so=Object.prototype.hasOwnProperty;function lo(t,e,r){var n=t[e];so.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(!Ue(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=We(t),r=[];for(var n in t)("constructor"!=n||!e&&po.call(t,n))&&r.push(n);return r}function vo(t){return Ye(t)?Me(t,!0):ho(t)}function go(t){return function(t,e,r,n){var o=!r;r||(r={});for(var a=-1,i=e.length;++a0){if(++e>=jo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(wo);function Eo(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,a=mo(n.length-e,0),i=Array(a);++o1?e[n-1]:void 0,a=n>2?e[2]:void 0;for(o=$o.length>3&&"function"==typeof o?(n--,o):void 0,a&&function(t,e,r){if(!Ue(r))return!1;var n=typeof e;return!!("number"==n?Ye(r)&&ke(e,r.length):"string"==n&&e in r)&&Qe(r[e],t)}(e[0],e[1],a)&&(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,Qo(t))}),Reflect.apply(t,null,r))}};function ra(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 t.then((function(t){return e(t)}))}),Reflect.apply(t,null,r))}}function na(t,e,r,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,e)&&Object.defineProperty(t,e,{set:r,get:null===n?function(){return null}:n}),t}function oa(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function aa(t,e,r,n){void 0===n&&(n=!1);var o=oa(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}function ia(t){return!!Xo(t,"socket")&&t.socket}var ua=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},ca=function(t){var e;return(e={}).args=t,e};function fa(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Lt(t)&&et(e)){var n=ca(e);return!0===r?n:function(t,e){var r;return(r={})[t]=e,r[y]=[ua()],r}(t,n)}throw new s("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}var sa=new WeakMap,la=new WeakMap;var pa=function(){this.__suspend__=null,this.queueStore=new Set},ha={$suspend:{configurable:!0},$queues:{configurable:!0}};ha.$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__},ha.$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,ha);var va=function(t){function e(e){t.call(this,{logger:e})}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"jsonql-ws-client"},Object.defineProperties(e.prototype,r),e}(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 a=0;return o.forEach((function(o){var i=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,i,r||u),a+=n.addToNormalStore(t,"on",e,r||u)})),a},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],a=o[0],i=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,a,r||i),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,a=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==a)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(a).forEach((function(o){var a=o[0],i=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,a,r||i)})));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 a=Array.from(o)[0],i=a[0],u=a[1],c=a[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,i,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,a=this.normalStore;if(this.logger("($trigger)","normalStore",a),a.has(t)){var i=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",i),!0===i)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(a.get(t)),c=u.length,f=!1,s=0;s0;)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 a=n[2];this.checkTypeInLazyStore(e,a)||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),a=[this.normalStore,t,o,r,n,e],i=Reflect.apply(this.addToStore,this,a),u=i[0],c=i[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 a=Reflect.apply(this.addToStore,this,o),i=a[0],u=a[1];return this.lazyStore=i,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){sa.set(this,t)},r.normalStore.get=function(){return sa.get(this)},r.lazyStore.set=function(t){la.set(this,t)},r.lazyStore.get=function(){return la.get(this)},e.prototype.hashFnToKey=function(t){return t.toString().split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)+""},Object.defineProperties(e.prototype,r),e}(pa))),ga=function(t){var e=ia(t);if(!1!==e)return e;throw new i("Missing property in contract!")};function da(t){var e,r,n=t.contract;return t.enableAuth?function(t,e){void 0===e&&(e=!1);var r=ia(t);if(!1===r){if(e)return t;throw new I("socket not found in contract!")}var n,o={},a=0;for(var i in r){var u=r[i],c=u.namespace;c&&(o[c]||(++a,o[c]={}),o[c][i]=u,n||u.public&&(n=c))}return{size:a,nspSet:o,publicNamespace:n}}(n):((r={})[N]=((e={})[h]=ga(n),e),r[R]=h,r)}var ya=function(t,e){return"ws"===e?t.replace("http://","ws://"):t},ba=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new JsonqlValidationError(t)}};function _a(t,e,r){Xo(t,p)?r(t[p]):Xo(t,l)?e(t[l]):r({message:H,error:t})}function ma(t,e,r,n,o){void 0===o&&(o=[]);var a=Zo(e,A),i=n?W:x;return t.$trigger(a,[r,Qo(o)]),new Promise((function(n,o){t.$on(Zo(e,r,i),(function(t){_a(t,n,o)}))}))}var wa=function(t,e,r,n,o,a){return na(t,"send",(function(t){var i=a?L:C;Yo(Qo(t),o.params,!0).then((function(o){if(!o[p]||!o[p].length)return ma(e,r,n,a,t);e.$call(Zo(r,n,i),[new s(n,o[p])])})).catch((function(t){e.$call(Zo(r,n,i),[new s(n,t)])}))}),(function(){return function(){for(var t=[],i=arguments.length;i--;)t[i]=arguments[i];return Yo(t,o.params,!0).then((function(t){return ma(e,r,n,a,t)})).catch(B)}}))};function ja(t,e,r,n,o){return[aa(t,Y,(function(t,o){if(Ho(t)&&ta(o))switch(t){case W:e.$on(Zo(r,n,ON_RESULT_PROP_NAME),(function(t){_a(t,o,(function(t){e.$trigger(Zo(r,n,ON_ERROR_PROP_NAME),t)}))}));break;case F:e.$only(Zo(r,n,ON_MESSAGE_PROP_NAME),(function(t){_a(t,o,(function(t){e.$trigger(Zo(r,n,ON_ERROR_PROP_NAME),t)}))}));break;case READY_PROP_NAME:e.$only(Zo(r,n,ON_ERROR_PROP_NAME),o);break;default:e.$trigger(Zo(r,n,ON_ERROR_PROP_NAME),new I(n,"Unknown event name "+t+"!"))}})),e,r,n,o]}var Oa=function(t,e,r,n,o,a){return[aa(t,"myNamespace",r),e,r,n,o,a]},Sa=function(t,e,r,n,o,a){return[na(t,x,(function(t){ta(t)&&e.$on(Zo(r,n,x),(function(o){_a(o,t,(function(t){e.$trigger(Zo(r,n,C),t)}))}))})),e,r,n,o,a]},ka=function(t,e,r,n,o,a){return[na(t,z,(function(t){if(ta(t)){e.$only(Zo(r,n,z),(function(o){_a(o,t,(function(t){e.$trigger(Zo(r,n,C),t)}))}))}})),e,r,n,o,a]},Ea=function(t,e,r,n,o,a){return[na(t,C,(function(t){ta(t)&&e.$only(Zo(r,n,C),t)})),e,r,n,o,a]};function $a(t,e,r,n,o,a){var i=[Oa];a?i.push(ja):i.push(Sa,ka,Ea),i.push(wa);var u=Reflect.apply(ea,null,i);return Reflect.apply(u,null,[n,o,t,e,r,a])}function Aa(t,e,r,n,o){return function(){for(var a=[],i=arguments.length;i--;)a[i]=arguments[i];return Yo(a,n.params,!0).then((function(n){return ma(t,e,r,o,n)})).catch(B)}}var Ta,Pa,Na=function(t,e,r){return[aa(t,r.loginHandlerName,(function(t){if(t&&Ho(t))return e.$trigger(E,[t]);throw new s(r.loginHandlerName,"Unexpected token "+t)})),e,r]},Ra=function(t,e,r){return aa(t,r.logoutHandlerName,(function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];e.$trigger($,t)}))};function za(t,e,r){var n={},o=e.nspSet,a=t.useCallbackStyle;for(var i in o){var u=o[i];for(var c in u){var f=u[c];n=aa(n,c,$a(i,c,f,Aa(r,i,c,f,a),r,a))}}return n.devHelpers={getNsp:function(){return Object.keys(o)},getVer:function(){return t.version||"NOT SET"}},Promise.resolve(n)}function xa(t,e,r){var n=e.nspSet,o=[za];return t.useCallbackStyle?o.push((function(t){return function(t,e,r,n){return aa(t,Y,(function(t,n){if(Ho(t)&&ta(n))switch(t){case L:for(var o in r)e.$on(Zo(o,L),n);break;case U:e.$only(U,n);break;case J:e.$on(J,n);break;default:e.$trigger(L,new I(Y,"Unknown event name "+t+"!"))}}))}(t,r,n)})):o.push((function(t){return function(t,e,r){return na(t,C,(function(t){if(ta(t))for(var n in r)e.$on(Zo(n,C),t)}))}(t,r,n)}),(function(t){return function(t,e,r){return na(t,q,(function(t){ta(t)&&e.$on(q,t)}))}(t,r)}),(function(e){return function(t,e,r){return r.enableAuth?na(t,M,(function(t){ta(t)&&e.$only(M,t)})):t}(e,r,t)})),o.push((function(e){return function(t,e,r){return r.enableAuth?ea(Na,Ra)(t,e,r):t}(e,r,t)})),Reflect.apply(ra,null,o)(t,e,r)}var Ca=["roundtip","handshake"],qa={useCallbackStyle:Go(!1,["boolean"]),loginHandlerName:Go("login",["string"]),logoutHandlerName:Go("logout",["string"]),loginMethod:Go("handshake",["string"],(Ta={},Ta[m]=Ca,Ta)),useJwt:Go(!0,["boolean","string"]),hostname:Go(!1,["string"]),namespace:Go(h,["string"]),wsOptions:Go({},["object"]),contract:Go({},["object"],(Pa={},Pa[j]=function(t){return!!function(t){return se(t)&&(Xo(t,v)||Xo(t,g)||Xo(t,d))}(t)&&t},Pa)),enableAuth:Go(!1,["boolean"]),token:Go(!1,["string"])},Ma={eventEmitter:null,nspClient:null,nspAuthClient:null,wssPath:""};function Fa(t,e){return function(t,e,r){return oa(t,S)?Promise.resolve(t):Ko(t,e,r)}(t,qa,Object.assign(Ma,e)).then((function(t){return t.hostname||(t.hostname=ba()),t.wssPath=ya([t.hostname,t.namespace].join("/"),t.serverType),t}))}var Wa={version:"version: 1.0.0 module: umd",serverType:"ws"},La=null;"undefined"!=typeof WebSocket?La=WebSocket:"undefined"!=typeof MozWebSocket?La=MozWebSocket:void 0!==G?La=G.WebSocket||G.MozWebSocket:"undefined"!=typeof window?La=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(La=self.WebSocket||self.MozWebSocket);var Ja=function(t){var e=t.toLowerCase();return e.indexOf("http")>-1?e.indexOf("https")>-1?e.replace("https","wss"):e.replace("http","ws"):e};function Ua(t,e){return void 0===e&&(e=!1),!1===e?function(e){return new t(Ja(e))}:function(e,r){var n=Ja(e),o=r&&"string"==typeof r?n+"?"+D+"="+r:n;try{return new t(o)}catch(t){return console.error("WebSocket Connection Error",t),!1}}}var Da="socket.io",Ia=A;function Va(t,e){var r=e.hostname,n=e.wssPath,o=e.wsOptions;return(0,e.nspClient)(t?[r,t].join("/"):n,o)}var Ba=function(t,e){Qo(e).forEach((function(e){t.$off(Zo(e,A))}))};var Ha=function(t,e,r){var n=r.useCallbackStyle,o=n?L:C,a=n?W:x;e.$only(Zo(t,Ia),(function(n,i){r.logger("noLoginHandler hijack the ws call",t,n,i);var u={message:"NOT LOGIN"};e.$call(Zo(t,n,o),[u]),e.$call(Zo(t,n,a),[{error:u}])}))},Ya=function(t){return t.length>1&&t[0]};function Ga(t,e,r,n,o,a){var i=Ya(o),u=!1;o.forEach((function(o){if(u=i===o,a[o]){t.logger("call bindWsHandler",u,o);var c=[o,a[o],r,u,t];if(t.serverType===Da){var f=e.nspSet;c.push(f[o])}Reflect.apply(n,null,c)}else Ha(o,r,t)})),r.$on($,(function(){t.logger("LOGOUT_EVENT_NAME"),function(t,e,r,n){void 0===n&&(n={});var o=n.useCallbackStyle?L:C;e.forEach((function(e){t.$call(Zo(e,o),[{message:r,namespace:e}])}))}(r,o,$),o.forEach((function(e){Ba(r,e),a[e]=!1,Ha(e,r,t)}))}))}var Ka=["__reply__","__event__","__data__"],Qa=function(t){var e,r=t.data;if(!1!==(e=function(t){var e=t.data;return!!e&&(Ka.filter((function(t){return Xo(e,t)})).length===Ka.length&&e)}(Ho(r)?JSON.parse(r):r)))return{resolverName:e.__event__,data:e.__data__,type:e.__reply__};throw new I("payload can not be decoded",t)},Xa=function(){},Za=function(t,e,r,n,o){var a=[e];r&&a.push(r),a.push(o);var i=Reflect.apply(Zo,null,a),u=n.data||n;t.$trigger(i,[u])};function ti(t,e,r,n,o){var a=o.log||Xa,i=o.useCallbackStyle,u=i?J:q,c=i?U:M,f=i?F:z,s=i?W:x,l=i?L:C;e.onopen=function(){a("ws.onopen listened"),r.$call(u,t),n&&(console.log("isPrivate and fire the "+c),r.$call(c,t)),r.$only(Zo(t,A),(function(t,r){a("calling server",t,r),e.send(function(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(fa(t,e,r))}(t,r))}))},e.onmessage=function(e){try{var n=Qa(e),o=n.resolverName,i=n.type;switch(a("Hear from server",i,n),i){case A:var u=Zo(t,o,f),c=r.$trigger(u,[n]);a("EMIT_REPLY_TYPE",u,c);break;case T:var p=Zo(t,o,s);r.$trigger(p,[n]);break;case P:a("ERROR_TYPE"),Za(r,t,o,n,l);break;default:a("Unhandled event!",n),Za(r,t,o,n,l)}}catch(e){console.error("ws.onmessage error",e),Za(r,t,!1,e,l)}},e.onclose=function(){a("ws.onclose callback")},r.$on($,(function(){try{a("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var ei=function(t,e,r){var n,o=e.nspSet,a=e.publicNamespace,i=!1,u=[],c={};if(t.enableAuth)i=!0,c=(u=function(t,e){var r=[];for(var n in t)n===e?r[1]=n:r[0]=n;return r}(o,a)).map((function(e,n){var o,a,i;return 0===n?r?(t.token=r,(o={})[e]=function(t,e){var r=e.hostname,n=e.wssPath,o=e.token,a=e.wsOptions,i=e.nspAuthClient,u=t?[r,t].join("/"):n;if(o&&"string"!=typeof o)throw new Error("Expect token to be string, but got "+o);return i(u,o,a)}(e,t),o):((a={})[e]=!1,a):((i={})[e]=Va(e,t),i)})).reduce((function(t,e){return Object.assign(t,e)}),{});else{var f=(n=o,Object.keys(n)[0]);u.push(f),c[f]=Va(!1,t)}return{nsps:c,namespaces:u,login:i}};return function(t,e){void 0===e&&(e={});var r=e.log,n=r&&"function"==typeof r?r:function(){};return function(r){var o=r.eventEmitter;return Fa(r,e).then((function(t){return t.logger=n,t})).then((function(t){return{opts:t,nspMap:da(t),ee:o||new va(n)}})).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return xa(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("jsonql-ws-client init error",t)}))}}(function(t){var e=Ua(t),r=Ua(t,!0);return function(t,n,o){return t.nspClient=e,t.nspAuthClient=r,function(t,e,r){var n=[t,e,r,ti],o=t.token,a=ei(t,e,o),i=a.nsps,u=a.namespaces,c=a.login;return Reflect.apply(Ga,null,n.concat([u,i])),c&&r.$only(E,(function(o){Ba(r,u);var a=ei(t,e,o);Reflect.apply(Ga,null,n.concat([a.namespaces,a.nsps]))})),{opts:t,nspMap:e,ee:r}}(t,n,o)}}(La),Wa)})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).jsonqlWsClient=e()}(this,(function(){"use strict";var t=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),e=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),r=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),n=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),o=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),a=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),i=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),u=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),c=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),f=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),s=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),l="data",p="error",h="jsonql",v="query",g="mutation",d="socket",y="TS",b="type",_="optional",m="enumv",w="args",j="checker",S="alias",O="__checked__",k="No message",$="__login__",E="__logout__",T="emit",A="acknowledge",P="error",z="nspSet",N="publicNamespace",x="onMessage",C="onResult",q="onError",R="onReady",M="onLogin",F="message",W="result",L="error",J="ready",U="login",I="token",D=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),V=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);function H(l){if(Array.isArray(l))throw new s("",l);var p=l.message||k,h=l.detail||l;switch(!0){case l instanceof t:throw new t(p,h);case l instanceof e:throw new e(p,h);case l instanceof r:throw new r(p,h);case l instanceof n:throw new n(p,h);case l instanceof o:throw new o(p,h);case l instanceof a:throw new a(p,h);case l instanceof i:throw new i(p,h);case l instanceof u:throw new u(p,h);case l instanceof c:throw new c(p,h);case l instanceof f:throw new f(p,h);case l instanceof s:throw new s(p,h);case l instanceof V:throw new V(p,h);default:throw new D(p,h)}}var B="UKNNOWN RESULT!",Y="on",G="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},K="object"==typeof G&&G&&G.Object===Object&&G,Q="object"==typeof self&&self&&self.Object===Object&&self,X=K||Q||Function("return this")(),Z=X.Symbol;function tt(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 a=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 Rt=function(t){return!!et(t)||null!=t&&""!==qt(t)},Mt="[object Number]";function Ft(t){return function(t){return"number"==typeof t||lt(t)&&st(t)==Mt}(t)&&t!=+t}var Wt="[object String]";function Lt(t){return"string"==typeof t||!et(t)&<(t)&&st(t)==Wt}var Jt=function(t){return!Lt(t)&&!Ft(parseFloat(t))},Ut=function(t){return""!==qt(t)&&Lt(t)},It=function(t){return null!=t&&"boolean"==typeof t},Dt=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==qt(t)&&(!1===e||!0===e&&null!==t)},Vt=b,Ht=_,Bt=m,Yt=w,Gt=j,Kt=S,Qt="continue",Xt=function(t){switch(t){case"number":return Jt;case"string":return Ut;case"boolean":return It;default:return Dt}},Zt=function(t,e){return void 0===e&&(e=""),!!et(t)&&(""===e||""===qt(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};function re(t,e){return function(r){return t(e(r))}}var ne=re(Object.getPrototypeOf,Object),oe="[object Object]",ae=Function.prototype,ie=Object.prototype,ue=ae.toString,ce=ie.hasOwnProperty,fe=ue.call(Object);function se(t){if(!lt(t)||st(t)!=oe)return!1;var e=ne(t);if(null===e)return!0;var r=ce.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&ue.call(r)==fe}var le,pe=function(t,e,r){for(var n=-1,o=Object(t),a=r(t),i=a.length;i--;){var u=a[le?i:++n];if(!1===e(o[u],u,o))break}return t};var he="[object Arguments]";function ve(t){return lt(t)&&st(t)==he}var ge=Object.prototype,de=ge.hasOwnProperty,ye=ge.propertyIsEnumerable,be=ve(function(){return arguments}())?ve:function(t){return lt(t)&&de.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?X.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<=$e}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 Ae,Pe="object"==typeof exports&&exports&&!exports.nodeType&&exports,ze=Pe&&"object"==typeof module&&module&&!module.nodeType&&module,Ne=ze&&ze.exports===Pe&&K.process,xe=function(){try{var t=ze&&ze.require&&ze.require("util").types;return t||Ne&&Ne.binding&&Ne.binding("util")}catch(t){}}(),Ce=xe&&xe.isTypedArray,qe=Ce?(Ae=Ce,function(t){return Ae(t)}):function(t){return lt(t)&&Ee(t.length)&&!!Te[st(t)]},Re=Object.prototype.hasOwnProperty;function Me(t,e){var r=et(t),n=!r&&be(t),o=!r&&!n&&je(t),a=!r&&!n&&!o&&qe(t),i=r||n||o||a,u=i?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=X["__core-js_shared__"],nr=(er=/[^.]+$/.exec(rr&&rr.keys&&rr.keys.IE_PROTO||""))?"Symbol(src)_1."+er:"";var or=Function.prototype.toString;function ar(t){if(null!=t){try{return or.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ir=/^\[object .+?Constructor\]$/,ur=Function.prototype,cr=Object.prototype,fr=ur.toString,sr=cr.hasOwnProperty,lr=RegExp("^"+fr.call(sr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function pr(t){return!(!Ue(t)||function(t){return!!nr&&nr in t}(t))&&(Be(t)?lr:ir).test(ar(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 vr=hr(X,"Map"),gr=hr(Object,"create");var dr="__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 f=a.get(t);if(f&&a.get(e))return f==e;var s=-1,l=!0,p=r&Ar?new $r:void 0;for(a.set(t,e),a.set(e,t);++se.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},Kn=function(t,e){var r,n,o,a,i;switch(!0){case"object"===t:return o=(n=e).arg,a=n.param,i=[o],Array.isArray(a.keys)&&a.keys.length&&i.push(a.keys),!Reflect.apply(Gn,null,i);case"array"===t:return!Zt(e.arg);case!1!==(r=te(t)):return!ee(e,r);default:return!Xt(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(!Zt(e))throw new D("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 D("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 a=r>=n||!!e[r].optional,i=e[r]||{type:o,name:"_"+r};return{arg:a?Qn(t,i):t,index:r,param:i,optional:a}}));default:throw new D("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),a=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 Kn(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Kn(e,t)})).length)}));return r?((n={})[p]=a,n[l]=o.map((function(t){return t.arg})),n):a},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?X.Buffer:void 0,ao=oo?oo.allocUnsafe:void 0;function io(t,e){var r,n,o=e?(r=t.buffer,n=new r.constructor(r.byteLength),new zr(n).set(new zr(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(!Ue(e))return{};if(uo)return uo(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 so=Object.prototype.hasOwnProperty;function lo(t,e,r){var n=t[e];so.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(!Ue(t))return function(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}(t);var e=We(t),r=[];for(var n in t)("constructor"!=n||!e&&po.call(t,n))&&r.push(n);return r}function vo(t){return Ye(t)?Me(t,!0):ho(t)}function go(t){return function(t,e,r,n){var o=!r;r||(r={});for(var a=-1,i=e.length;++a0){if(++e>=jo)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(wo);function $o(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,a=mo(n.length-e,0),i=Array(a);++o1?e[n-1]:void 0,a=n>2?e[2]:void 0;for(o=Eo.length>3&&"function"==typeof o?(n--,o):void 0,a&&function(t,e,r){if(!Ue(r))return!1;var n=typeof e;return!!("number"==n?Ye(r)&&ke(e,r.length):"string"==n&&e in r)&&Qe(r[e],t)}(e[0],e[1],a)&&(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,Qo(t))}),Reflect.apply(t,null,r))}};function ra(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 t.then((function(t){return e(t)}))}),Reflect.apply(t,null,r))}}function na(t,e,r,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,e)&&Object.defineProperty(t,e,{set:r,get:null===n?function(){return null}:n}),t}function oa(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return void 0!==r&&r.value?r.value:r}function aa(t,e,r,n){void 0===n&&(n=!1);var o=oa(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}function ia(t){return!!Xo(t,"socket")&&t.socket}var ua=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e},ca=function(t){var e;return(e={}).args=t,e};function fa(t,e,r){if(void 0===e&&(e=[]),void 0===r&&(r=!1),Lt(t)&&et(e)){var n=ca(e);return!0===r?n:function(t,e){var r;return(r={})[t]=e,r[y]=[ua()],r}(t,n)}throw new s("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}var sa=new WeakMap,la=new WeakMap;var pa=function(){this.__suspend__=null,this.queueStore=new Set},ha={$suspend:{configurable:!0},$queues:{configurable:!0}};ha.$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__},ha.$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,ha);var va=function(t){function e(e){t.call(this,{logger:e})}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"jsonql-ws-client"},Object.defineProperties(e.prototype,r),e}(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 a=0;return o.forEach((function(o){var i=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,i,r||u),a+=n.addToNormalStore(t,"on",e,r||u)})),a},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],a=o[0],i=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,a,r||i),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,a=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==a)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(a).forEach((function(o){var a=o[0],i=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,a,r||i)})));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 a=Array.from(o)[0],i=a[0],u=a[1],c=a[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,i,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,a=this.normalStore;if(this.logger("($trigger)","normalStore",a),a.has(t)){var i=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",i),!0===i)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(a.get(t)),c=u.length,f=!1,s=0;s0;)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 a=n[2];this.checkTypeInLazyStore(e,a)||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),a=[this.normalStore,t,o,r,n,e],i=Reflect.apply(this.addToStore,this,a),u=i[0],c=i[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 a=Reflect.apply(this.addToStore,this,o),i=a[0],u=a[1];return this.lazyStore=i,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){sa.set(this,t)},r.normalStore.get=function(){return sa.get(this)},r.lazyStore.set=function(t){la.set(this,t)},r.lazyStore.get=function(){return la.get(this)},e.prototype.hashFnToKey=function(t){return t.toString().split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)+""},Object.defineProperties(e.prototype,r),e}(pa))),ga=function(t){var e=ia(t);if(!1!==e)return e;throw new i("Missing property in contract!")};function da(t){var e,r,n=t.contract;return t.enableAuth?function(t,e){void 0===e&&(e=!1);var r=ia(t);if(!1===r){if(e)return t;throw new D("socket not found in contract!")}var n,o={},a=0;for(var i in r){var u=r[i],c=u.namespace;c&&(o[c]||(++a,o[c]={}),o[c][i]=u,n||u.public&&(n=c))}return{size:a,nspSet:o,publicNamespace:n}}(n):((r={})[z]=((e={})[h]=ga(n),e),r[N]=h,r)}var ya=function(t,e){return"ws"===e?t.replace("http://","ws://"):t},ba=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new JsonqlValidationError(t)}};function _a(t,e,r){Xo(t,p)?r(t[p]):Xo(t,l)?e(t[l]):r({message:B,error:t})}function ma(t,e,r,n,o){void 0===o&&(o=[]);var a=Zo(e,T),i=n?W:C;return t.$trigger(a,[r,Qo(o)]),new Promise((function(n,o){t.$on(Zo(e,r,i),(function(t){_a(t,n,o)}))}))}var wa=function(t,e,r,n,o,a){return na(t,"send",(function(t){var i=a?L:q;Yo(Qo(t),o.params,!0).then((function(o){if(!o[p]||!o[p].length)return ma(e,r,n,a,t);e.$call(Zo(r,n,i),[new s(n,o[p])])})).catch((function(t){e.$call(Zo(r,n,i),[new s(n,t)])}))}),(function(){return function(){for(var t=[],i=arguments.length;i--;)t[i]=arguments[i];return Yo(t,o.params,!0).then((function(t){return ma(e,r,n,a,t)})).catch(H)}}))};function ja(t,e,r,n,o){return[aa(t,Y,(function(t,o){if(Bo(t)&&ta(o))switch(t){case W:e.$on(Zo(r,n,C),(function(t){_a(t,o,(function(t){e.$trigger(Zo(r,n,q),t)}))}));break;case F:e.$only(Zo(r,n,x),(function(t){_a(t,o,(function(t){e.$trigger(Zo(r,n,q),t)}))}));break;case J:e.$only(Zo(r,n,q),o);break;default:e.$trigger(Zo(r,n,q),new D(n,"Unknown event name "+t+"!"))}})),e,r,n,o]}var Sa=function(t,e,r,n,o,a){return[aa(t,"myNamespace",r),e,r,n,o,a]},Oa=function(t,e,r,n,o,a){return[na(t,C,(function(t){ta(t)&&e.$on(Zo(r,n,C),(function(o){_a(o,t,(function(t){e.$trigger(Zo(r,n,q),t)}))}))})),e,r,n,o,a]},ka=function(t,e,r,n,o,a){return[na(t,x,(function(t){if(ta(t)){e.$only(Zo(r,n,x),(function(o){_a(o,t,(function(t){e.$trigger(Zo(r,n,q),t)}))}))}})),e,r,n,o,a]},$a=function(t,e,r,n,o,a){return[na(t,q,(function(t){ta(t)&&e.$only(Zo(r,n,q),t)})),e,r,n,o,a]};function Ea(t,e,r,n,o,a){var i=[Sa];a?i.push(ja):i.push(Oa,ka,$a),i.push(wa);var u=Reflect.apply(ea,null,i);return Reflect.apply(u,null,[n,o,t,e,r,a])}function Ta(t,e,r,n,o){return function(){for(var a=[],i=arguments.length;i--;)a[i]=arguments[i];return Yo(a,n.params,!0).then((function(n){return ma(t,e,r,o,n)})).catch(H)}}var Aa,Pa,za=function(t,e,r){return[aa(t,r.loginHandlerName,(function(t){if(t&&Bo(t))return e.$trigger($,[t]);throw new s(r.loginHandlerName,"Unexpected token "+t)})),e,r]},Na=function(t,e,r){return aa(t,r.logoutHandlerName,(function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];e.$trigger(E,t)}))};function xa(t,e,r){var n={},o=e.nspSet,a=t.useCallbackStyle;for(var i in o){var u=o[i];for(var c in u){var f=u[c];n=aa(n,c,Ea(i,c,f,Ta(r,i,c,f,a),r,a))}}return n.devHelpers={getNsp:function(){return Object.keys(o)},getVer:function(){return t.version||"NOT SET"}},Promise.resolve(n)}function Ca(t,e,r){var n=e.nspSet,o=t.useCallbackStyle,a=t.enableAuth,i=[xa];return o?i.push((function(t){return function(t,e,r,n){return aa(t,Y,(function(t,n){if(Bo(t)&&ta(n))switch(t){case L:for(var o in r)e.$on(Zo(o,L),n);break;case U:e.$only(U,n);break;case J:e.$on(J,n);break;default:e.$trigger(L,new D(Y,"Unknown event name "+t+"!"))}}))}(t,r,n)})):(i.push((function(t){return function(t,e,r){return na(t,q,(function(t){if(ta(t))for(var n in r)e.$on(Zo(n,q),t)}))}(t,r,n)}),(function(t){return function(t,e,r){return na(t,R,(function(t){ta(t)&&e.$on(R,t)}))}(t,r)})),a&&i.push((function(e){return function(t,e,r){return r.enableAuth?na(t,M,(function(t){ta(t)&&e.$only(M,t)})):t}(e,r,t)}))),a&&i.push((function(e){return function(t,e,r){return r.enableAuth?ea(za,Na)(t,e,r):t}(e,r,t)})),Reflect.apply(ra,null,i)(t,e,r)}var qa=["roundtip","handshake"],Ra={useCallbackStyle:Go(!1,["boolean"]),loginHandlerName:Go("login",["string"]),logoutHandlerName:Go("logout",["string"]),loginMethod:Go("handshake",["string"],(Aa={},Aa[m]=qa,Aa)),useJwt:Go(!0,["boolean","string"]),hostname:Go(!1,["string"]),namespace:Go(h,["string"]),wsOptions:Go({},["object"]),contract:Go({},["object"],(Pa={},Pa[j]=function(t){return!!function(t){return se(t)&&(Xo(t,v)||Xo(t,g)||Xo(t,d))}(t)&&t},Pa)),enableAuth:Go(!1,["boolean"]),token:Go(!1,["string"])},Ma={eventEmitter:null,nspClient:null,nspAuthClient:null,wssPath:""};function Fa(t,e){return function(t,e,r){return oa(t,O)?Promise.resolve(t):Ko(t,e,r)}(t,Ra,Object.assign(Ma,e)).then((function(t){return t.hostname||(t.hostname=ba()),t.wssPath=ya([t.hostname,t.namespace].join("/"),t.serverType),t}))}var Wa=function(){};var La={version:"version: 1.0.1 module: umd",serverType:"ws"},Ja=null;"undefined"!=typeof WebSocket?Ja=WebSocket:"undefined"!=typeof MozWebSocket?Ja=MozWebSocket:void 0!==G?Ja=G.WebSocket||G.MozWebSocket:"undefined"!=typeof window?Ja=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(Ja=self.WebSocket||self.MozWebSocket);var Ua=function(t){var e=t.toLowerCase();return e.indexOf("http")>-1?e.indexOf("https")>-1?e.replace("https","wss"):e.replace("http","ws"):e};function Ia(t,e){return void 0===e&&(e=!1),!1===e?function(e){return new t(Ua(e))}:function(e,r){var n=Ua(e),o=r&&"string"==typeof r?n+"?"+I+"="+r:n;try{return new t(o)}catch(t){return console.error("WebSocket Connection Error",t),!1}}}var Da="socket.io",Va=T;function Ha(t,e){var r=e.hostname,n=e.wssPath,o=e.wsOptions;return(0,e.nspClient)(t?[r,t].join("/"):n,o)}var Ba=function(t,e){Qo(e).forEach((function(e){t.$off(Zo(e,T))}))};var Ya=function(t,e,r){var n=r.useCallbackStyle,o=n?L:q,a=n?W:C;e.$only(Zo(t,Va),(function(n,i){r.logger("noLoginHandler hijack the ws call",t,n,i);var u={message:"NOT LOGIN"};e.$call(Zo(t,n,o),[u]),e.$call(Zo(t,n,a),[{error:u}])}))},Ga=function(t){return t.length>1&&t[0]};function Ka(t,e,r,n,o,a){var i=Ga(o),u=!1;o.forEach((function(o){if(u=i===o,a[o]){t.logger("call bindWsHandler",u,o);var c=[o,a[o],r,u,t];if(t.serverType===Da){var f=e.nspSet;c.push(f[o])}Reflect.apply(n,null,c)}else Ya(o,r,t)})),r.$on(E,(function(){t.logger("LOGOUT_EVENT_NAME"),function(t,e,r,n){void 0===n&&(n={});var o=n.useCallbackStyle?L:q;e.forEach((function(e){t.$call(Zo(e,o),[{message:r,namespace:e}])}))}(r,o,E),o.forEach((function(e){Ba(r,e),a[e]=!1,Ya(e,r,t)}))}))}var Qa=["__reply__","__event__","__data__"],Xa=function(t){var e,r=t.data;if(!1!==(e=function(t){var e=t.data;return!!e&&(Qa.filter((function(t){return Xo(e,t)})).length===Qa.length&&e)}(Bo(r)?JSON.parse(r):r)))return{resolverName:e.__event__,data:e.__data__,type:e.__reply__};throw new D("payload can not be decoded",t)},Za=function(){},ti=function(t,e,r,n,o){var a=[e];r&&a.push(r),a.push(o);var i=Reflect.apply(Zo,null,a),u=n.data||n;t.$trigger(i,[u])};function ei(t,e,r,n,o){var a=o.log||Za;a("wsMainHandler log test");var i=o.useCallbackStyle,u=i?J:R,c=i?U:M,f=i?F:x,s=i?W:C,l=i?L:q;e.onopen=function(){a("ws.onopen listened"),r.$call(u,t),n&&(a("isPrivate and fire the "+c),r.$call(c,t)),r.$only(Zo(t,T),(function(t,r){a("calling server",t,r),e.send(function(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(fa(t,e,r))}(t,r))}))},e.onmessage=function(e){try{var n=Xa(e),o=n.resolverName,i=n.type;switch(a("Hear from server",i,n),i){case T:var u=Zo(t,o,f),c=r.$trigger(u,[n]);a("EMIT_REPLY_TYPE",u,c);break;case A:var p=Zo(t,o,s);r.$trigger(p,[n]);break;case P:a("ERROR_TYPE"),ti(r,t,o,n,l);break;default:a("Unhandled event!",n),ti(r,t,o,n,l)}}catch(e){console.error("ws.onmessage error",e),ti(r,t,!1,e,l)}},e.onclose=function(){a("ws.onclose callback")},r.$on(E,(function(){try{a("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var ri=function(t,e,r){var n,o=e.nspSet,a=e.publicNamespace,i=!1,u=[],c={};if(t.enableAuth)i=!0,c=(u=function(t,e){var r=[];for(var n in t)n===e?r[1]=n:r[0]=n;return r}(o,a)).map((function(e,n){var o,a,i;return 0===n?r?(t.token=r,(o={})[e]=function(t,e){var r=e.hostname,n=e.wssPath,o=e.token,a=e.wsOptions,i=e.nspAuthClient,u=t?[r,t].join("/"):n;if(o&&"string"!=typeof o)throw new Error("Expect token to be string, but got "+o);return i(u,o,a)}(e,t),o):((a={})[e]=!1,a):((i={})[e]=Ha(e,t),i)})).reduce((function(t,e){return Object.assign(t,e)}),{});else{var f=(n=o,Object.keys(n)[0]);u.push(f),c[f]=Ha(!1,t)}return{nsps:c,namespaces:u,login:i}};return function(t,e){void 0===e&&(e={});var r=e.log,n=r&&"function"==typeof r?r:Wa;return function(r){var o=r.eventEmitter;return Fa(r,e).then((function(t){return t.logger=n,t})).then((function(t){return{opts:t,nspMap:da(t),ee:o||new va(n)}})).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return Ca(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("jsonql-ws-client init error",t)}))}}(function(t){var e=Ia(t),r=Ia(t,!0);return function(t,n,o){return t.nspClient=e,t.nspAuthClient=r,function(t,e,r){var n=[t,e,r,ei],o=t.token,a=ri(t,e,o),i=a.nsps,u=a.namespaces,c=a.login;return Reflect.apply(Ka,null,n.concat([u,i])),c&&r.$only($,(function(o){Ba(r,u);var a=ri(t,e,o);Reflect.apply(Ka,null,n.concat([a.namespaces,a.nsps]))})),{opts:t,nspMap:e,ee:r}}(t,n,o)}}(Ja),La)})); //# sourceMappingURL=jsonql-ws-client.umd.js.map diff --git a/packages/@jsonql/ws/node.js b/packages/@jsonql/ws/node.js index 9ba68fed..fe7a7968 100644 --- a/packages/@jsonql/ws/node.js +++ b/packages/@jsonql/ws/node.js @@ -1,2 +1,2 @@ -"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var WebSocket=_interopDefault(require("ws")),Jsonql406Error=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 406},t.name.get=function(){return"Jsonql406Error"},Object.defineProperties(r,t),r}(Error),Jsonql500Error=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 500},t.name.get=function(){return"Jsonql500Error"},Object.defineProperties(r,t),r}(Error),JsonqlForbiddenError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 403},t.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(r,t),r}(Error),JsonqlAuthorisationError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 401},t.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(r,t),r}(Error),JsonqlContractAuthError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 401},t.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(r,t),r}(Error),JsonqlResolverAppError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 500},t.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(r,t),r}(Error),JsonqlResolverNotFoundError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 404},t.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(r,t),r}(Error),JsonqlEnumError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(r,t),r}(Error),JsonqlTypeError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(r,t),r}(Error),JsonqlCheckerError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(r,t),r}(Error),JsonqlValidationError$1=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(r,t),r}(Error),DATA_KEY="data",ERROR_KEY="error",JSONQL_PATH="jsonql",DEFAULT_TYPE="any",QUERY_NAME="query",MUTATION_NAME="mutation",SOCKET_NAME="socket",QUERY_ARG_NAME="args",TIMESTAMP_PARAM_NAME="TS",KEY_WORD="continue",TYPE_KEY="type",OPTIONAL_KEY="optional",ENUM_KEY="enumv",ARGS_KEY="args",CHECKER_KEY="checker",ALIAS_KEY="alias",CHECKED_KEY="__checked__",LOGIN_NAME="login",ISSUER_NAME=LOGIN_NAME,LOGOUT_NAME="logout",OR_SEPERATOR="|",STRING_TYPE="string",BOOLEAN_TYPE="boolean",ARRAY_TYPE="array",OBJECT_TYPE="object",NUMBER_TYPE="number",ARRAY_TYPE_LFT="array.<",ARRAY_TYPE_RGT=">",NO_ERROR_MSG="No message",NO_STATUS_CODE=-1,LOGIN_EVENT_NAME="__login__",LOGOUT_EVENT_NAME="__logout__",WS_REPLY_TYPE="__reply__",WS_EVT_NAME="__event__",WS_DATA_NAME="__data__",EMIT_REPLY_TYPE="emit",ACKNOWLEDGE_REPLY_TYPE="acknowledge",ERROR_TYPE="error",NSP_SET="nspSet",PUBLIC_NAMESPACE="publicNamespace",JS_WS_SOCKET_IO_NAME="socket.io",JS_WS_NAME="ws",ON_MESSAGE_PROP_NAME$1="onMessage",ON_RESULT_PROP_NAME$1="onResult",ON_ERROR_PROP_NAME$1="onError",ON_READY_PROP_NAME="onReady",ON_LOGIN_PROP_NAME="onLogin",SEND_MSG_PROP_NAME="send",MESSAGE_PROP_NAME="message",RESULT_PROP_NAME="result",ERROR_PROP_NAME="error",READY_PROP_NAME$1="ready",LOGIN_PROP_NAME="login",NOT_LOGIN_ERR_MSG="NOT LOGIN",TOKEN_PARAM_NAME="token",IO_ROUNDTRIP_LOGIN="roundtip",IO_HANDSHAKE_LOGIN="handshake",JsonqlError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0},statusCode:{configurable:!0}};return t.name.get=function(){return"JsonqlError"},t.statusCode.get=function(){return NO_STATUS_CODE},Object.defineProperties(r,t),r}(Error),JsonqlServerError=function(e){function r(t,n){e.call(this,n),this.statusCode=t,this.className=r.name}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlServerError"},Object.defineProperties(r,t),r}(Error);function finalCatch(e){if(Array.isArray(e))throw new JsonqlValidationError$1("",e);var r=e.message||NO_ERROR_MSG,t=e.detail||e;switch(!0){case e instanceof Jsonql406Error:throw new Jsonql406Error(r,t);case e instanceof Jsonql500Error:throw new Jsonql500Error(r,t);case e instanceof JsonqlForbiddenError:throw new JsonqlForbiddenError(r,t);case e instanceof JsonqlAuthorisationError:throw new JsonqlAuthorisationError(r,t);case e instanceof JsonqlContractAuthError:throw new JsonqlContractAuthError(r,t);case e instanceof JsonqlResolverAppError:throw new JsonqlResolverAppError(r,t);case e instanceof JsonqlResolverNotFoundError:throw new JsonqlResolverNotFoundError(r,t);case e instanceof JsonqlEnumError:throw new JsonqlEnumError(r,t);case e instanceof JsonqlTypeError:throw new JsonqlTypeError(r,t);case e instanceof JsonqlCheckerError:throw new JsonqlCheckerError(r,t);case e instanceof JsonqlValidationError$1:throw new JsonqlValidationError$1(r,t);case e instanceof JsonqlServerError:throw new JsonqlServerError(r,t);default:throw new JsonqlError(r,t)}}var MISSING_PROP_ERR="Missing property in contract!",UNKNOWN_RESULT="UKNNOWN RESULT!",MY_NAMESPACE="myNamespace",CB_FN_NAME="on",global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},freeGlobal="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol=root.Symbol;function arrayMap(e,r){for(var t=-1,n=null==e?0:e.length,o=Array(n);++to?0:o+r),(t=t>o?o:t)<0&&(t+=o),o=r>t?0:t-r>>>0,r>>>=0;for(var a=Array(o);++n=n?e:baseSlice(e,r,t)}function baseFindIndex(e,r,t,n){for(var o=e.length,a=t+(n?1:-1);n?a--:++a-1;);return t}function charsStartIndex(e,r){for(var t=-1,n=e.length;++t-1;);return t}function asciiToArray(e){return e.split("")}var rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f",reComboHalfMarksRange="\\ufe20-\\ufe2f",rsComboSymbolsRange="\\u20d0-\\u20ff",rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsVarRange="\\ufe0e\\ufe0f",rsZWJ="\\u200d",reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+"]");function hasUnicode(e){return reHasUnicode.test(e)}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",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",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("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g");function unicodeToArray(e){return e.match(reUnicode)||[]}function stringToArray(e){return hasUnicode(e)?unicodeToArray(e):asciiToArray(e)}function toString(e){return null==e?"":baseToString(e)}var reTrim=/^\s+|\s+$/g;function trim(e,r,t){if((e=toString(e))&&(t||void 0===r))return e.replace(reTrim,"");if(!e||!(r=baseToString(r)))return e;var n=stringToArray(e),o=stringToArray(r);return castSlice(n,charsStartIndex(n,o),charsEndIndex(n,o)+1).join("")}var isNotEmpty=function(e){return!!isArray(e)||null!=e&&""!==trim(e)},numberTag="[object Number]";function isNumber(e){return"number"==typeof e||isObjectLike(e)&&baseGetTag(e)==numberTag}function isNaN(e){return isNumber(e)&&e!=+e}var stringTag="[object String]";function isString(e){return"string"==typeof e||!isArray(e)&&isObjectLike(e)&&baseGetTag(e)==stringTag}var checkIsNumber=function(e){return!isString(e)&&!isNaN(parseFloat(e))},checkIsString=function(e){return""!==trim(e)&&isString(e)},checkIsBoolean=function(e){return null!=e&&"boolean"==typeof e},checkIsAny=function(e,r){return void 0===r&&(r=!0),void 0!==e&&""!==e&&""!==trim(e)&&(!1===r||!0===r&&null!==e)},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)",PARAMS_NOT_ARRAY_ERR="params is not an array! Did something gone wrong when you generate the contract.json?",EXCEPTION_CASE_ERR="Could not understand your arguments and parameter structure!",DEFAULT_TYPE$1=DEFAULT_TYPE,ARRAY_TYPE_LFT$1=ARRAY_TYPE_LFT,ARRAY_TYPE_RGT$1=ARRAY_TYPE_RGT,TYPE_KEY$1=TYPE_KEY,OPTIONAL_KEY$1=OPTIONAL_KEY,ENUM_KEY$1=ENUM_KEY,ARGS_KEY$1=ARGS_KEY,CHECKER_KEY$1=CHECKER_KEY,ALIAS_KEY$1=ALIAS_KEY,ARRAY_TYPE$1=ARRAY_TYPE,OBJECT_TYPE$1=OBJECT_TYPE,STRING_TYPE$1=STRING_TYPE,BOOLEAN_TYPE$1=BOOLEAN_TYPE,NUMBER_TYPE$1=NUMBER_TYPE,KEY_WORD$1=KEY_WORD,OR_SEPERATOR$1=OR_SEPERATOR,combineFn=function(e){switch(e){case NUMBER_TYPE$1:return checkIsNumber;case STRING_TYPE$1:return checkIsString;case BOOLEAN_TYPE$1:return checkIsBoolean;default:return checkIsAny}},checkIsArray=function(e,r){return void 0===r&&(r=""),!!isArray(e)&&(""===r||""===trim(r)||!(e.filter((function(e){return!combineFn(r)(e)})).length>0))},isArrayLike=function(e){if(e.indexOf(ARRAY_TYPE_LFT$1)>-1&&e.indexOf(ARRAY_TYPE_RGT$1)>-1){var r=e.replace(ARRAY_TYPE_LFT$1,"").replace(ARRAY_TYPE_RGT$1,"");return r.indexOf(OR_SEPERATOR$1)?r.split(OR_SEPERATOR$1):[r]}return!1},arrayTypeHandler=function(e,r){var t=e.arg;return r.length>1?!t.filter((function(e){return!(r.length>r.filter((function(r){return!combineFn(r)(e)})).length)})).length:r.length>r.filter((function(e){return!checkIsArray(t,e)})).length};function overArg(e,r){return function(t){return e(r(t))}}var getPrototype=overArg(Object.getPrototypeOf,Object),objectTag="[object Object]",funcProto=Function.prototype,objectProto$2=Object.prototype,funcToString=funcProto.toString,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectCtorString=funcToString.call(Object);function isPlainObject(e){if(!isObjectLike(e)||baseGetTag(e)!=objectTag)return!1;var r=getPrototype(e);if(null===r)return!0;var t=hasOwnProperty$1.call(r,"constructor")&&r.constructor;return"function"==typeof t&&t instanceof t&&funcToString.call(t)==objectCtorString}function arrayFilter(e,r){for(var t=-1,n=null==e?0:e.length,o=0,a=[];++t-1&&e%1==0&&e-1&&e%1==0&&e<=MAX_SAFE_INTEGER$1}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]",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]",typedArrayTags={};function baseIsTypedArray(e){return isObjectLike(e)&&isLength(e.length)&&!!typedArrayTags[baseGetTag(e)]}function baseUnary(e){return function(r){return e(r)}}typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,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]=!1;var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,freeProcess=moduleExports$1&&freeGlobal.process,nodeUtil=function(){try{var e=freeModule$1&&freeModule$1.require&&freeModule$1.require("util").types;return e||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,objectProto$4=Object.prototype,hasOwnProperty$3=objectProto$4.hasOwnProperty;function arrayLikeKeys(e,r){var t=isArray(e),n=!t&&isArguments(e),o=!t&&!n&&isBuffer(e),a=!t&&!n&&!o&&isTypedArray(e),i=t||n||o||a,s=i?baseTimes(e.length,String):[],c=s.length;for(var u in e)!r&&!hasOwnProperty$3.call(e,u)||i&&("length"==u||o&&("offset"==u||"parent"==u)||a&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||isIndex(u,c))||s.push(u);return s}var objectProto$5=Object.prototype;function isPrototype(e){var r=e&&e.constructor;return e===("function"==typeof r&&r.prototype||objectProto$5)}var nativeKeys=overArg(Object.keys,Object),objectProto$6=Object.prototype,hasOwnProperty$4=objectProto$6.hasOwnProperty;function baseKeys(e){if(!isPrototype(e))return nativeKeys(e);var r=[];for(var t in Object(e))hasOwnProperty$4.call(e,t)&&"constructor"!=t&&r.push(t);return r}function isObject(e){var r=typeof e;return null!=e&&("object"==r||"function"==r)}var asyncTag="[object AsyncFunction]",funcTag$1="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]";function isFunction(e){if(!isObject(e))return!1;var r=baseGetTag(e);return r==funcTag$1||r==genTag||r==asyncTag||r==proxyTag}function isArrayLike$1(e){return null!=e&&isLength(e.length)&&!isFunction(e)}function keys(e){return isArrayLike$1(e)?arrayLikeKeys(e):baseKeys(e)}function baseForOwn(e,r){return e&&baseFor(e,r,keys)}function listCacheClear(){this.__data__=[],this.size=0}function eq(e,r){return e===r||e!=e&&r!=r}function assocIndexOf(e,r){for(var t=e.length;t--;)if(eq(e[t][0],r))return t;return-1}var arrayProto=Array.prototype,splice=arrayProto.splice;function listCacheDelete(e){var r=this.__data__,t=assocIndexOf(r,e);return!(t<0)&&(t==r.length-1?r.pop():splice.call(r,t,1),--this.size,!0)}function listCacheGet(e){var r=this.__data__,t=assocIndexOf(r,e);return t<0?void 0:r[t][1]}function listCacheHas(e){return assocIndexOf(this.__data__,e)>-1}function listCacheSet(e,r){var t=this.__data__,n=assocIndexOf(t,e);return n<0?(++this.size,t.push([e,r])):t[n][1]=r,this}function ListCache(e){var r=-1,t=null==e?0:e.length;for(this.clear();++rs))return!1;var u=a.get(e);if(u&&a.get(r))return u==r;var l=-1,f=!0,p=t&COMPARE_UNORDERED_FLAG?new SetCache:void 0;for(a.set(e,r),a.set(r,e);++lr.type.filter((function(e){var r;return void 0===t||(!1!==(r=isArrayLike(e))?!arrayTypeHandler({arg:t},r):!combineFn(e)(t))})).length)})).length}return!1},objectTypeHandler=function(e){var r=e.arg,t=e.param,n=[r];return Array.isArray(t.keys)&&t.keys.length&&n.push(t.keys),Reflect.apply(checkIsObject,null,n)},optionalHandler=function(e){var r=e.arg,t=e.param;return!!isNotEmpty(r)&&!(t.type.length>t.type.filter((function(r){return validateHandler(r,e)})).length)},validateHandler=function(e,r){var t;switch(!0){case e===OBJECT_TYPE$1:return!objectTypeHandler(r);case e===ARRAY_TYPE$1:return!checkIsArray(r.arg);case!1!==(t=isArrayLike(e)):return!arrayTypeHandler(r,t);default:return!combineFn(e)(r.arg)}},getOptionalValue=function(e,r){return void 0!==e?e:!0===r.optional&&void 0!==r.defaultvalue?r.defaultvalue:null},normalizeArgs=function(e,r){if(!checkIsArray(r))throw new JsonqlError(PARAMS_NOT_ARRAY_ERR);if(0===r.length)return[];if(!checkIsArray(e))throw new JsonqlError(ARGS_NOT_ARRAY_ERR);switch(!0){case e.length==r.length:return e.map((function(e,t){return{arg:e,index:t,param:r[t]}}));case!0===r[0].variable:var t=r[0].type;return e.map((function(e,n){return{arg:e,index:n,param:r[n]||{type:t,name:"_"}}}));case e.lengthr.length:var n=r.length,o=[DEFAULT_TYPE$1];return e.map((function(e,t){var a=t>=n||!!r[t].optional,i=r[t]||{type:o,name:"_"+t};return{arg:a?getOptionalValue(e,i):e,index:t,param:i,optional:a}}));default:throw new JsonqlError(EXCEPTION_CASE_ERR,{args:e,params:r})}},processReturn=function(e){return e.map((function(e){return e.arg}))},validateSync=function(e,r,t){var n;void 0===t&&(t=!1);var o=normalizeArgs(e,r),a=o.filter((function(e){return!0===e.optional||!0===e.param.optional?optionalHandler(e):!(e.param.type.length>e.param.type.filter((function(r){return validateHandler(r,e)})).length)}));return t?((n={})[ERROR_KEY]=a,n[DATA_KEY]=processReturn(o),n):a},validateAsync=function(e,r,t){return void 0===t&&(t=!1),new Promise((function(n,o){var a=validateSync(e,r,t);return t?a[ERROR_KEY].length?o(a[ERROR_KEY]):n(a[DATA_KEY]):a.length?o(a):n([])}))},defineProperty=function(){try{var e=getNative(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();function baseAssignValue(e,r,t){"__proto__"==r&&defineProperty?defineProperty(e,r,{configurable:!0,enumerable:!0,value:t,writable:!0}):e[r]=t}function assignMergeValue(e,r,t){(void 0===t||eq(e[r],t))&&(void 0!==t||r in e)||baseAssignValue(e,r,t)}var freeExports$2="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$2=freeExports$2&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2,Buffer$1=moduleExports$2?root.Buffer:void 0,allocUnsafe=Buffer$1?Buffer$1.allocUnsafe:void 0;function cloneBuffer(e,r){if(r)return e.slice();var t=e.length,n=allocUnsafe?allocUnsafe(t):new e.constructor(t);return e.copy(n),n}function cloneArrayBuffer(e){var r=new e.constructor(e.byteLength);return new Uint8Array(r).set(new Uint8Array(e)),r}function cloneTypedArray(e,r){var t=r?cloneArrayBuffer(e.buffer):e.buffer;return new e.constructor(t,e.byteOffset,e.length)}function copyArray(e,r){var t=-1,n=e.length;for(r||(r=Array(n));++t0){if(++r>=HOT_COUNT)return arguments[0]}else r=0;return e.apply(void 0,arguments)}}var setToString=shortOut(baseSetToString);function baseRest(e,r){return setToString(overRest(e,r,identity),e+"")}function isIterateeCall(e,r,t){if(!isObject(t))return!1;var n=typeof r;return!!("number"==n?isArrayLike$1(t)&&isIndex(r,t.length):"string"==n&&r in t)&&eq(t[r],e)}function createAssigner(e){return baseRest((function(r,t){var n=-1,o=t.length,a=o>1?t[o-1]:void 0,i=o>2?t[2]:void 0;for(a=e.length>3&&"function"==typeof a?(o--,a):void 0,i&&isIterateeCall(t[0],t[1],i)&&(a=o<3?void 0:a,o=1),r=Object(r);++n0;)r[t]=arguments[t+1];return function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];return r.reduce((function(e,r){return Reflect.apply(r,null,toArray$1(e))}),Reflect.apply(e,null,t))}};function chainProcessPromises(e){for(var r=[],t=arguments.length-1;t-- >0;)r[t]=arguments[t+1];return function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];return r.reduce((function(e,r){return e.then((function(e){return r(e)}))}),Reflect.apply(e,null,t))}}function objDefineProps(e,r,t,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(e,r)&&Object.defineProperty(e,r,{set:t,get:null===n?function(){return null}:n}),e}function objHasProp(e,r){var t=Object.getOwnPropertyDescriptor(e,r);return void 0!==t&&t.value?t.value:t}function injectToFn(e,r,t,n){void 0===n&&(n=!1);var o=objHasProp(e,r);return!1===n&&void 0!==o?e:(Object.defineProperty(e,r,{value:t,writable:n}),e)}function checkIsContract(e){return isPlainObject(e)&&(isObjectHasKey$1(e,QUERY_NAME)||isObjectHasKey$1(e,MUTATION_NAME)||isObjectHasKey$1(e,SOCKET_NAME))}function isContract(e){return!!checkIsContract(e)&&e}function extractSocketPart(e){return!!isObjectHasKey$1(e,"socket")&&e.socket}function groupByNamespace(e,r){void 0===r&&(r=!1);var t=extractSocketPart(e);if(!1===t){if(r)return e;throw new JsonqlError("socket not found in contract!")}var n,o={},a=0;for(var i in t){var s=t[i],c=s.namespace;c&&(o[c]||(++a,o[c]={}),o[c][i]=s,n||s.public&&(n=c))}return{size:a,nspSet:o,publicNamespace:n}}function getNamespaceInOrder(e,r){var t=[];for(var n in e)n===r?t[1]=n:t[0]=n;return t}var timestamp=function(e){void 0===e&&(e=!1);var r=Date.now();return e?Math.floor(r/1e3):r},formatPayload=function(e){var r;return(r={})[QUERY_ARG_NAME]=e,r};function getNameFromPayload(e){return Object.keys(e)[0]}function createDeliverable(e,r){var t;return(t={})[e]=r,t[TIMESTAMP_PARAM_NAME]=[timestamp()],t}function createQuery(e,r,t){if(void 0===r&&(r=[]),void 0===t&&(t=!1),isString(e)&&isArray(r)){var n=formatPayload(r);return!0===t?n:createDeliverable(e,n)}throw new JsonqlValidationError$1("[createQuery] expect resolverName to be string and args to be array!",{resolverName:e,args:r})}function createQueryStr(e,r,t){return void 0===r&&(r=[]),void 0===t&&(t=!1),JSON.stringify(createQuery(e,r,t))}var NB_EVENT_SERVICE_PRIVATE_STORE=new WeakMap,NB_EVENT_SERVICE_PRIVATE_LAZY=new WeakMap;function hashCode(e){return e.split("").reduce((function(e,r){return(e=(e<<5)-e+r.charCodeAt(0))&e}),0)}var SuspendClass=function(){this.__suspend__=null,this.queueStore=new Set},prototypeAccessors={$suspend:{configurable:!0},$queues:{configurable:!0}};prototypeAccessors.$suspend.set=function(e){var r=this;if("boolean"!=typeof e)throw new Error("$suspend only accept Boolean value!");var t=this.__suspend__;this.__suspend__=e,this.logger("($suspend)","Change from "+t+" --\x3e "+e),!0===t&&!1===e&&setTimeout((function(){r.release()}),1)},SuspendClass.prototype.$queue=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",e),this.queueStore.add(e)),this.__suspend__},prototypeAccessors.$queues.get=function(){var e=this.queueStore.size;return this.logger("($queues)","size: "+e),e>0?Array.from(this.queueStore):[]},SuspendClass.prototype.release=function(){var e=this,r=this.queueStore.size;if(this.logger("(release)","Release was called "+r),r>0){var t=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",t),t.forEach((function(r){e.logger(r),Reflect.apply(e.$trigger,e,r)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(SuspendClass.prototype,prototypeAccessors);var NbEventServiceBase=function(e){function r(r){void 0===r&&(r={}),e.call(this),r.logger&&"function"==typeof r.logger&&(this.logger=r.logger),this.keep=r.keep,this.result=r.keep?[]:null,this.normalStore=new Map,this.lazyStore=new Map}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={normalStore:{configurable:!0},lazyStore:{configurable:!0}};return r.prototype.validateEvt=function(){for(var e=this,r=[],t=arguments.length;t--;)r[t]=arguments[t];return r.forEach((function(r){if("string"!=typeof r)throw e.logger("(validateEvt)",r),new Error("event name must be string type!")})),!0},r.prototype.validate=function(e,r){if(this.validateEvt(e)&&"function"==typeof r)return!0;throw new Error("callback required to be function type!")},r.prototype.validateType=function(e){return!!["on","only","once","onlyOnce"].filter((function(r){return e===r})).length},r.prototype.run=function(e,r,t){this.logger("(run)",e,r,t),this.$done=Reflect.apply(e,t,this.toArray(r))},r.prototype.takeFromStore=function(e,r){void 0===r&&(r="lazyStore");var t=this[r];if(t){if(this.logger("(takeFromStore)",r,t),t.has(e)){var n=t.get(e);return this.logger("(takeFromStore)","has "+e,n),t.delete(e),n}return!1}throw new Error(r+" is not supported!")},r.prototype.addToStore=function(e,r){for(var t,n=[],o=arguments.length-2;o-- >0;)n[o]=arguments[o+2];if(e.has(r)?(this.logger("(addToStore)",r+" existed"),t=e.get(r)):(this.logger("(addToStore)","create new Set for "+r),t=new Set),n.length>2)if(Array.isArray(n[0])){var a=n[2];this.checkTypeInLazyStore(r,a)||t.add(n)}else this.checkContentExist(n,t)||(this.logger("(addToStore)","insert new",n),t.add(n));else t.add(n);return e.set(r,t),[e,t.size]},r.prototype.checkContentExist=function(e,r){return!!Array.from(r).filter((function(r){return r[0]===e[0]})).length},r.prototype.checkTypeInStore=function(e,r){this.validateEvt(e,r);var t=this.$get(e,!0);return!1===t||!t.filter((function(e){var t=e[3];return r!==t})).length},r.prototype.checkTypeInLazyStore=function(e,r){this.validateEvt(e,r);var t=this.lazyStore.get(e);return this.logger("(checkTypeInLazyStore)",t),!!t&&!!Array.from(t).filter((function(e){return e[2]!==r})).length},r.prototype.addToNormalStore=function(e,r,t,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",e,r,"try to add to normal store"),this.checkTypeInStore(e,r)){this.logger("(addToNormalStore)",r+" can add to "+e+" normal store");var o=this.hashFnToKey(t),a=[this.normalStore,e,o,t,n,r],i=Reflect.apply(this.addToStore,this,a),s=i[0],c=i[1];return this.normalStore=s,c}return!1},r.prototype.addToLazyStore=function(e,r,t,n){void 0===r&&(r=[]),void 0===t&&(t=null),void 0===n&&(n=!1);var o=[this.lazyStore,e,this.toArray(r),t];n&&o.push(n);var a=Reflect.apply(this.addToStore,this,o),i=a[0],s=a[1];return this.lazyStore=i,s},r.prototype.toArray=function(e){return Array.isArray(e)?e:[e]},t.normalStore.set=function(e){NB_EVENT_SERVICE_PRIVATE_STORE.set(this,e)},t.normalStore.get=function(){return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)},t.lazyStore.set=function(e){NB_EVENT_SERVICE_PRIVATE_LAZY.set(this,e)},t.lazyStore.get=function(){return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)},r.prototype.hashFnToKey=function(e){return hashCode(e.toString())+""},Object.defineProperties(r.prototype,t),r}(SuspendClass),EventService=function(e){function r(r){void 0===r&&(r={}),e.call(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={$done:{configurable:!0}};return r.prototype.logger=function(){},r.prototype.$on=function(e,r,t){var n=this;void 0===t&&(t=null);this.validate(e,r);var o=this.takeFromStore(e);if(!1===o)return this.logger("($on)",e+" callback is not in lazy store"),this.addToNormalStore(e,"on",r,t);this.logger("($on)",e+" found in lazy store");var a=0;return o.forEach((function(o){var i=o[0],s=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 "+e),n.run(r,i,t||s),a+=n.addToNormalStore(e,"on",r,t||s)})),a},r.prototype.$once=function(e,r,t){void 0===t&&(t=null),this.validate(e,r);var n=this.takeFromStore(e);this.normalStore;if(!1===n)return this.logger("($once)",e+" not in the lazy store"),this.addToNormalStore(e,"once",r,t);this.logger("($once)",n);var o=Array.from(n)[0],a=o[0],i=o[1],s=o[2];if(s&&"once"!==s)throw new Error("You are trying to register an event already been taken by other type: "+s);this.logger("($once)","call run for "+e),this.run(r,a,t||i),this.$off(e)},r.prototype.$only=function(e,r,t){var n=this;void 0===t&&(t=null),this.validate(e,r);var o=!1,a=this.takeFromStore(e);(this.normalStore.has(e)||(this.logger("($only)",e+" add to store"),o=this.addToNormalStore(e,"only",r,t)),!1!==a)&&(this.logger("($only)",e+" found data in lazy store to execute"),Array.from(a).forEach((function(o){var a=o[0],i=o[1],s=o[2];if(s&&"only"!==s)throw new Error("You are trying to register an event already been taken by other type: "+s);n.logger("($only)","call run for "+e),n.run(r,a,t||i)})));return o},r.prototype.$onlyOnce=function(e,r,t){void 0===t&&(t=null),this.validate(e,r);var n=!1,o=this.takeFromStore(e);if(this.normalStore.has(e)||(this.logger("($onlyOnce)",e+" add to store"),n=this.addToNormalStore(e,"onlyOnce",r,t)),!1!==o){this.logger("($onlyOnce)",o);var a=Array.from(o)[0],i=a[0],s=a[1],c=a[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 "+e),this.run(r,i,t||s),this.$off(e)}return n},r.prototype.$replace=function(e,r,t,n){if(void 0===t&&(t=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(e);var o=this["$"+n];return this.logger("($replace)",e,r),Reflect.apply(o,this,[e,r,t])}throw new Error(n+" is not supported!")},r.prototype.$trigger=function(e,r,t,n){void 0===r&&(r=[]),void 0===t&&(t=null),void 0===n&&(n=!1),this.validateEvt(e);var o=0,a=this.normalStore;if(this.logger("($trigger)","normalStore",a),a.has(e)){var i=this.$queue(e,r,t,n);if(this.logger("($trigger)",e,"found; add to queue: ",i),!0===i)return this.logger("($trigger)",e,"not executed. Exit now."),!1;for(var s=Array.from(a.get(e)),c=s.length,u=!1,l=0;l-1?r.indexOf("https")>-1?r.replace("https","wss"):r.replace("http","ws"):r};function createWsClient(e,r){return void 0===r&&(r=!1),!1===r?function(r){return new e(fixWss$1(r))}:function(r,t){var n=fixWss$1(r),o=t&&"string"==typeof t?n+"?"+TOKEN_PARAM_NAME+"="+t:n;try{return new e(o)}catch(e){return console.error("WebSocket Connection Error",e),!1}}}var SOCKET_IO=JS_WS_SOCKET_IO_NAME,EMIT_EVT=EMIT_REPLY_TYPE;function createNspClient(e,r){var t=r.hostname,n=r.wssPath,o=r.wsOptions;return(0,r.nspClient)(e?[t,e].join("/"):n,o)}function createNspAuthClient(e,r){var t=r.hostname,n=r.wssPath,o=r.token,a=r.wsOptions,i=r.nspAuthClient,s=e?[t,e].join("/"):n;if(o&&"string"!=typeof o)throw new Error("Expect token to be string, but got "+o);return i(s,o,a)}var clearMainEmitEvt=function(e,r){toArray$1(r).forEach((function(r){e.$off(createEvt(r,EMIT_REPLY_TYPE))}))};function triggerNamespacesOnError(e,r,t,n){void 0===n&&(n={});var o=n.useCallbackStyle?ERROR_PROP_NAME:ON_ERROR_PROP_NAME$1;r.forEach((function(r){e.$call(createEvt(r,o),[{message:t,namespace:r}])}))}var notLoginWsHandler=function(e,r,t){var n=t.useCallbackStyle,o=n?ERROR_PROP_NAME:ON_ERROR_PROP_NAME$1,a=n?RESULT_PROP_NAME:ON_RESULT_PROP_NAME$1;r.$only(createEvt(e,EMIT_EVT),(function(n,i){t.logger("noLoginHandler hijack the ws call",e,n,i);var s={message:NOT_LOGIN_ERR_MSG};r.$call(createEvt(e,n,o),[s]),r.$call(createEvt(e,n,a),[{error:s}])}))},getPrivateNamespace=function(e){return e.length>1&&e[0]};function clientEventHandler(e,r,t,n,o,a){var i=getPrivateNamespace(o),s=!1;o.forEach((function(o){if(s=i===o,a[o]){e.logger("call bindWsHandler",s,o);var c=[o,a[o],t,s,e];if(e.serverType===SOCKET_IO){var u=r.nspSet;c.push(u[o])}Reflect.apply(n,null,c)}else notLoginWsHandler(o,t,e)})),t.$on(LOGOUT_EVENT_NAME,(function(){e.logger("LOGOUT_EVENT_NAME"),triggerNamespacesOnError(t,o,LOGOUT_EVENT_NAME),o.forEach((function(r){clearMainEmitEvt(t,r),a[r]=!1,notLoginWsHandler(r,t,e)}))}))}var keys$1=[WS_REPLY_TYPE,WS_EVT_NAME,WS_DATA_NAME],isWsReply=function(e){var r=e.data;return!!r&&(keys$1.filter((function(e){return isObjectHasKey$1(r,e)})).length===keys$1.length&&r)},extractWsPayload=function(e){var r,t=e.data,n=isString$1(t)?JSON.parse(t):t;if(!1!==(r=isWsReply(n)))return{resolverName:r[WS_EVT_NAME],data:r[WS_DATA_NAME],type:r[WS_REPLY_TYPE]};throw new JsonqlError("payload can not be decoded",e)},dummyLogger=function(){},errorTypeHandler=function(e,r,t,n,o){var a=[r];t&&a.push(t),a.push(o);var i=Reflect.apply(createEvt,null,a),s=n.data||n;e.$trigger(i,[s])};function wsMainHandler(e,r,t,n,o){var a=o.log||dummyLogger,i=o.useCallbackStyle,s=i?READY_PROP_NAME$1:ON_READY_PROP_NAME,c=i?LOGIN_PROP_NAME:ON_LOGIN_PROP_NAME,u=i?MESSAGE_PROP_NAME:ON_MESSAGE_PROP_NAME$1,l=i?RESULT_PROP_NAME:ON_RESULT_PROP_NAME$1,f=i?ERROR_PROP_NAME:ON_ERROR_PROP_NAME$1;r.onopen=function(){a("ws.onopen listened"),t.$call(s,e),n&&(console.log("isPrivate and fire the "+c),t.$call(c,e)),t.$only(createEvt(e,EMIT_REPLY_TYPE),(function(e,t){a("calling server",e,t),r.send(createQueryStr(e,t))}))},r.onmessage=function(r){try{var n=extractWsPayload(r),o=n.resolverName,i=n.type;switch(a("Hear from server",i,n),i){case EMIT_REPLY_TYPE:var s=createEvt(e,o,u),c=t.$trigger(s,[n]);a("EMIT_REPLY_TYPE",s,c);break;case ACKNOWLEDGE_REPLY_TYPE:var p=createEvt(e,o,l);t.$trigger(p,[n]);break;case ERROR_TYPE:a("ERROR_TYPE"),errorTypeHandler(t,e,o,n,f);break;default:a("Unhandled event!",n),errorTypeHandler(t,e,o,n,f)}}catch(r){console.error("ws.onmessage error",r),errorTypeHandler(t,e,!1,r,f)}},r.onclose=function(){a("ws.onclose callback")},t.$on(LOGOUT_EVENT_NAME,(function(){try{a("terminate ws connection"),r.terminate()}catch(e){console.error("ws.terminate error",e)}}))}var createNsps=function(e,r,t){var n=r.nspSet,o=r.publicNamespace,a=!1,i=[],s={};if(e.enableAuth)a=!0,s=(i=getNamespaceInOrder(n,o)).map((function(r,n){var o,a,i;return 0===n?t?(e.token=t,(o={})[r]=createNspAuthClient(r,e),o):((a={})[r]=!1,a):((i={})[r]=createNspClient(r,e),i)})).reduce((function(e,r){return Object.assign(e,r)}),{});else{var c=getNameFromPayload(n);i.push(c),s[c]=createNspClient(!1,e)}return{nsps:s,namespaces:i,login:a}};function createClient(e,r,t){var n=[e,r,t,wsMainHandler],o=e.token,a=createNsps(e,r,o),i=a.nsps,s=a.namespaces,c=a.login;return Reflect.apply(clientEventHandler,null,n.concat([s,i])),c&&t.$only(LOGIN_EVENT_NAME,(function(o){clearMainEmitEvt(t,s);var a=createNsps(e,r,o);Reflect.apply(clientEventHandler,null,n.concat([a.namespaces,a.nsps]))})),{opts:e,nspMap:r,ee:t}}function createClientResolver(e){var r=createWsClient(e),t=createWsClient(e,!0);return function(e,n,o){return e.nspClient=r,e.nspAuthClient=t,createClient(e,n,o)}}var wsClientResolver=createClientResolver(WebSocket),node=wsClient(wsClientResolver,constProps);module.exports=node; +"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var WebSocket=_interopDefault(require("ws")),Jsonql406Error=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 406},t.name.get=function(){return"Jsonql406Error"},Object.defineProperties(r,t),r}(Error),Jsonql500Error=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 500},t.name.get=function(){return"Jsonql500Error"},Object.defineProperties(r,t),r}(Error),JsonqlForbiddenError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 403},t.name.get=function(){return"JsonqlForbiddenError"},Object.defineProperties(r,t),r}(Error),JsonqlAuthorisationError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 401},t.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(r,t),r}(Error),JsonqlContractAuthError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 401},t.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(r,t),r}(Error),JsonqlResolverAppError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 500},t.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(r,t),r}(Error),JsonqlResolverNotFoundError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 404},t.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(r,t),r}(Error),JsonqlEnumError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(r,t),r}(Error),JsonqlTypeError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(r,t),r}(Error),JsonqlCheckerError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(r,t),r}(Error),JsonqlValidationError$1=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(r,t),r}(Error),DATA_KEY="data",ERROR_KEY="error",JSONQL_PATH="jsonql",DEFAULT_TYPE="any",QUERY_NAME="query",MUTATION_NAME="mutation",SOCKET_NAME="socket",QUERY_ARG_NAME="args",TIMESTAMP_PARAM_NAME="TS",KEY_WORD="continue",TYPE_KEY="type",OPTIONAL_KEY="optional",ENUM_KEY="enumv",ARGS_KEY="args",CHECKER_KEY="checker",ALIAS_KEY="alias",CHECKED_KEY="__checked__",LOGIN_NAME="login",ISSUER_NAME=LOGIN_NAME,LOGOUT_NAME="logout",OR_SEPERATOR="|",STRING_TYPE="string",BOOLEAN_TYPE="boolean",ARRAY_TYPE="array",OBJECT_TYPE="object",NUMBER_TYPE="number",ARRAY_TYPE_LFT="array.<",ARRAY_TYPE_RGT=">",NO_ERROR_MSG="No message",NO_STATUS_CODE=-1,LOGIN_EVENT_NAME="__login__",LOGOUT_EVENT_NAME="__logout__",WS_REPLY_TYPE="__reply__",WS_EVT_NAME="__event__",WS_DATA_NAME="__data__",EMIT_REPLY_TYPE="emit",ACKNOWLEDGE_REPLY_TYPE="acknowledge",ERROR_TYPE="error",NSP_SET="nspSet",PUBLIC_NAMESPACE="publicNamespace",JS_WS_SOCKET_IO_NAME="socket.io",JS_WS_NAME="ws",ON_MESSAGE_PROP_NAME="onMessage",ON_RESULT_PROP_NAME="onResult",ON_ERROR_PROP_NAME="onError",ON_READY_PROP_NAME="onReady",ON_LOGIN_PROP_NAME="onLogin",SEND_MSG_PROP_NAME="send",MESSAGE_PROP_NAME="message",RESULT_PROP_NAME="result",ERROR_PROP_NAME="error",READY_PROP_NAME="ready",LOGIN_PROP_NAME="login",NOT_LOGIN_ERR_MSG="NOT LOGIN",TOKEN_PARAM_NAME="token",IO_ROUNDTRIP_LOGIN="roundtip",IO_HANDSHAKE_LOGIN="handshake",JsonqlError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0},statusCode:{configurable:!0}};return t.name.get=function(){return"JsonqlError"},t.statusCode.get=function(){return NO_STATUS_CODE},Object.defineProperties(r,t),r}(Error),JsonqlServerError=function(e){function r(t,n){e.call(this,n),this.statusCode=t,this.className=r.name}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlServerError"},Object.defineProperties(r,t),r}(Error);function finalCatch(e){if(Array.isArray(e))throw new JsonqlValidationError$1("",e);var r=e.message||NO_ERROR_MSG,t=e.detail||e;switch(!0){case e instanceof Jsonql406Error:throw new Jsonql406Error(r,t);case e instanceof Jsonql500Error:throw new Jsonql500Error(r,t);case e instanceof JsonqlForbiddenError:throw new JsonqlForbiddenError(r,t);case e instanceof JsonqlAuthorisationError:throw new JsonqlAuthorisationError(r,t);case e instanceof JsonqlContractAuthError:throw new JsonqlContractAuthError(r,t);case e instanceof JsonqlResolverAppError:throw new JsonqlResolverAppError(r,t);case e instanceof JsonqlResolverNotFoundError:throw new JsonqlResolverNotFoundError(r,t);case e instanceof JsonqlEnumError:throw new JsonqlEnumError(r,t);case e instanceof JsonqlTypeError:throw new JsonqlTypeError(r,t);case e instanceof JsonqlCheckerError:throw new JsonqlCheckerError(r,t);case e instanceof JsonqlValidationError$1:throw new JsonqlValidationError$1(r,t);case e instanceof JsonqlServerError:throw new JsonqlServerError(r,t);default:throw new JsonqlError(r,t)}}var MISSING_PROP_ERR="Missing property in contract!",UNKNOWN_RESULT="UKNNOWN RESULT!",MY_NAMESPACE="myNamespace",CB_FN_NAME="on",global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},freeGlobal="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol=root.Symbol;function arrayMap(e,r){for(var t=-1,n=null==e?0:e.length,o=Array(n);++to?0:o+r),(t=t>o?o:t)<0&&(t+=o),o=r>t?0:t-r>>>0,r>>>=0;for(var a=Array(o);++n=n?e:baseSlice(e,r,t)}function baseFindIndex(e,r,t,n){for(var o=e.length,a=t+(n?1:-1);n?a--:++a-1;);return t}function charsStartIndex(e,r){for(var t=-1,n=e.length;++t-1;);return t}function asciiToArray(e){return e.split("")}var rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f",reComboHalfMarksRange="\\ufe20-\\ufe2f",rsComboSymbolsRange="\\u20d0-\\u20ff",rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsVarRange="\\ufe0e\\ufe0f",rsZWJ="\\u200d",reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+"]");function hasUnicode(e){return reHasUnicode.test(e)}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",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",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("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g");function unicodeToArray(e){return e.match(reUnicode)||[]}function stringToArray(e){return hasUnicode(e)?unicodeToArray(e):asciiToArray(e)}function toString(e){return null==e?"":baseToString(e)}var reTrim=/^\s+|\s+$/g;function trim(e,r,t){if((e=toString(e))&&(t||void 0===r))return e.replace(reTrim,"");if(!e||!(r=baseToString(r)))return e;var n=stringToArray(e),o=stringToArray(r);return castSlice(n,charsStartIndex(n,o),charsEndIndex(n,o)+1).join("")}var isNotEmpty=function(e){return!!isArray(e)||null!=e&&""!==trim(e)},numberTag="[object Number]";function isNumber(e){return"number"==typeof e||isObjectLike(e)&&baseGetTag(e)==numberTag}function isNaN(e){return isNumber(e)&&e!=+e}var stringTag="[object String]";function isString(e){return"string"==typeof e||!isArray(e)&&isObjectLike(e)&&baseGetTag(e)==stringTag}var checkIsNumber=function(e){return!isString(e)&&!isNaN(parseFloat(e))},checkIsString=function(e){return""!==trim(e)&&isString(e)},checkIsBoolean=function(e){return null!=e&&"boolean"==typeof e},checkIsAny=function(e,r){return void 0===r&&(r=!0),void 0!==e&&""!==e&&""!==trim(e)&&(!1===r||!0===r&&null!==e)},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)",PARAMS_NOT_ARRAY_ERR="params is not an array! Did something gone wrong when you generate the contract.json?",EXCEPTION_CASE_ERR="Could not understand your arguments and parameter structure!",DEFAULT_TYPE$1=DEFAULT_TYPE,ARRAY_TYPE_LFT$1=ARRAY_TYPE_LFT,ARRAY_TYPE_RGT$1=ARRAY_TYPE_RGT,TYPE_KEY$1=TYPE_KEY,OPTIONAL_KEY$1=OPTIONAL_KEY,ENUM_KEY$1=ENUM_KEY,ARGS_KEY$1=ARGS_KEY,CHECKER_KEY$1=CHECKER_KEY,ALIAS_KEY$1=ALIAS_KEY,ARRAY_TYPE$1=ARRAY_TYPE,OBJECT_TYPE$1=OBJECT_TYPE,STRING_TYPE$1=STRING_TYPE,BOOLEAN_TYPE$1=BOOLEAN_TYPE,NUMBER_TYPE$1=NUMBER_TYPE,KEY_WORD$1=KEY_WORD,OR_SEPERATOR$1=OR_SEPERATOR,combineFn=function(e){switch(e){case NUMBER_TYPE$1:return checkIsNumber;case STRING_TYPE$1:return checkIsString;case BOOLEAN_TYPE$1:return checkIsBoolean;default:return checkIsAny}},checkIsArray=function(e,r){return void 0===r&&(r=""),!!isArray(e)&&(""===r||""===trim(r)||!(e.filter((function(e){return!combineFn(r)(e)})).length>0))},isArrayLike=function(e){if(e.indexOf(ARRAY_TYPE_LFT$1)>-1&&e.indexOf(ARRAY_TYPE_RGT$1)>-1){var r=e.replace(ARRAY_TYPE_LFT$1,"").replace(ARRAY_TYPE_RGT$1,"");return r.indexOf(OR_SEPERATOR$1)?r.split(OR_SEPERATOR$1):[r]}return!1},arrayTypeHandler=function(e,r){var t=e.arg;return r.length>1?!t.filter((function(e){return!(r.length>r.filter((function(r){return!combineFn(r)(e)})).length)})).length:r.length>r.filter((function(e){return!checkIsArray(t,e)})).length};function overArg(e,r){return function(t){return e(r(t))}}var getPrototype=overArg(Object.getPrototypeOf,Object),objectTag="[object Object]",funcProto=Function.prototype,objectProto$2=Object.prototype,funcToString=funcProto.toString,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectCtorString=funcToString.call(Object);function isPlainObject(e){if(!isObjectLike(e)||baseGetTag(e)!=objectTag)return!1;var r=getPrototype(e);if(null===r)return!0;var t=hasOwnProperty$1.call(r,"constructor")&&r.constructor;return"function"==typeof t&&t instanceof t&&funcToString.call(t)==objectCtorString}function arrayFilter(e,r){for(var t=-1,n=null==e?0:e.length,o=0,a=[];++t-1&&e%1==0&&e-1&&e%1==0&&e<=MAX_SAFE_INTEGER$1}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]",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]",typedArrayTags={};function baseIsTypedArray(e){return isObjectLike(e)&&isLength(e.length)&&!!typedArrayTags[baseGetTag(e)]}function baseUnary(e){return function(r){return e(r)}}typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,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]=!1;var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,freeProcess=moduleExports$1&&freeGlobal.process,nodeUtil=function(){try{var e=freeModule$1&&freeModule$1.require&&freeModule$1.require("util").types;return e||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,objectProto$4=Object.prototype,hasOwnProperty$3=objectProto$4.hasOwnProperty;function arrayLikeKeys(e,r){var t=isArray(e),n=!t&&isArguments(e),o=!t&&!n&&isBuffer(e),a=!t&&!n&&!o&&isTypedArray(e),i=t||n||o||a,s=i?baseTimes(e.length,String):[],c=s.length;for(var u in e)!r&&!hasOwnProperty$3.call(e,u)||i&&("length"==u||o&&("offset"==u||"parent"==u)||a&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||isIndex(u,c))||s.push(u);return s}var objectProto$5=Object.prototype;function isPrototype(e){var r=e&&e.constructor;return e===("function"==typeof r&&r.prototype||objectProto$5)}var nativeKeys=overArg(Object.keys,Object),objectProto$6=Object.prototype,hasOwnProperty$4=objectProto$6.hasOwnProperty;function baseKeys(e){if(!isPrototype(e))return nativeKeys(e);var r=[];for(var t in Object(e))hasOwnProperty$4.call(e,t)&&"constructor"!=t&&r.push(t);return r}function isObject(e){var r=typeof e;return null!=e&&("object"==r||"function"==r)}var asyncTag="[object AsyncFunction]",funcTag$1="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]";function isFunction(e){if(!isObject(e))return!1;var r=baseGetTag(e);return r==funcTag$1||r==genTag||r==asyncTag||r==proxyTag}function isArrayLike$1(e){return null!=e&&isLength(e.length)&&!isFunction(e)}function keys(e){return isArrayLike$1(e)?arrayLikeKeys(e):baseKeys(e)}function baseForOwn(e,r){return e&&baseFor(e,r,keys)}function listCacheClear(){this.__data__=[],this.size=0}function eq(e,r){return e===r||e!=e&&r!=r}function assocIndexOf(e,r){for(var t=e.length;t--;)if(eq(e[t][0],r))return t;return-1}var arrayProto=Array.prototype,splice=arrayProto.splice;function listCacheDelete(e){var r=this.__data__,t=assocIndexOf(r,e);return!(t<0)&&(t==r.length-1?r.pop():splice.call(r,t,1),--this.size,!0)}function listCacheGet(e){var r=this.__data__,t=assocIndexOf(r,e);return t<0?void 0:r[t][1]}function listCacheHas(e){return assocIndexOf(this.__data__,e)>-1}function listCacheSet(e,r){var t=this.__data__,n=assocIndexOf(t,e);return n<0?(++this.size,t.push([e,r])):t[n][1]=r,this}function ListCache(e){var r=-1,t=null==e?0:e.length;for(this.clear();++rs))return!1;var u=a.get(e);if(u&&a.get(r))return u==r;var l=-1,f=!0,p=t&COMPARE_UNORDERED_FLAG?new SetCache:void 0;for(a.set(e,r),a.set(r,e);++lr.type.filter((function(e){var r;return void 0===t||(!1!==(r=isArrayLike(e))?!arrayTypeHandler({arg:t},r):!combineFn(e)(t))})).length)})).length}return!1},objectTypeHandler=function(e){var r=e.arg,t=e.param,n=[r];return Array.isArray(t.keys)&&t.keys.length&&n.push(t.keys),Reflect.apply(checkIsObject,null,n)},optionalHandler=function(e){var r=e.arg,t=e.param;return!!isNotEmpty(r)&&!(t.type.length>t.type.filter((function(r){return validateHandler(r,e)})).length)},validateHandler=function(e,r){var t;switch(!0){case e===OBJECT_TYPE$1:return!objectTypeHandler(r);case e===ARRAY_TYPE$1:return!checkIsArray(r.arg);case!1!==(t=isArrayLike(e)):return!arrayTypeHandler(r,t);default:return!combineFn(e)(r.arg)}},getOptionalValue=function(e,r){return void 0!==e?e:!0===r.optional&&void 0!==r.defaultvalue?r.defaultvalue:null},normalizeArgs=function(e,r){if(!checkIsArray(r))throw new JsonqlError(PARAMS_NOT_ARRAY_ERR);if(0===r.length)return[];if(!checkIsArray(e))throw new JsonqlError(ARGS_NOT_ARRAY_ERR);switch(!0){case e.length==r.length:return e.map((function(e,t){return{arg:e,index:t,param:r[t]}}));case!0===r[0].variable:var t=r[0].type;return e.map((function(e,n){return{arg:e,index:n,param:r[n]||{type:t,name:"_"}}}));case e.lengthr.length:var n=r.length,o=[DEFAULT_TYPE$1];return e.map((function(e,t){var a=t>=n||!!r[t].optional,i=r[t]||{type:o,name:"_"+t};return{arg:a?getOptionalValue(e,i):e,index:t,param:i,optional:a}}));default:throw new JsonqlError(EXCEPTION_CASE_ERR,{args:e,params:r})}},processReturn=function(e){return e.map((function(e){return e.arg}))},validateSync=function(e,r,t){var n;void 0===t&&(t=!1);var o=normalizeArgs(e,r),a=o.filter((function(e){return!0===e.optional||!0===e.param.optional?optionalHandler(e):!(e.param.type.length>e.param.type.filter((function(r){return validateHandler(r,e)})).length)}));return t?((n={})[ERROR_KEY]=a,n[DATA_KEY]=processReturn(o),n):a},validateAsync=function(e,r,t){return void 0===t&&(t=!1),new Promise((function(n,o){var a=validateSync(e,r,t);return t?a[ERROR_KEY].length?o(a[ERROR_KEY]):n(a[DATA_KEY]):a.length?o(a):n([])}))},defineProperty=function(){try{var e=getNative(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();function baseAssignValue(e,r,t){"__proto__"==r&&defineProperty?defineProperty(e,r,{configurable:!0,enumerable:!0,value:t,writable:!0}):e[r]=t}function assignMergeValue(e,r,t){(void 0===t||eq(e[r],t))&&(void 0!==t||r in e)||baseAssignValue(e,r,t)}var freeExports$2="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$2=freeExports$2&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2,Buffer$1=moduleExports$2?root.Buffer:void 0,allocUnsafe=Buffer$1?Buffer$1.allocUnsafe:void 0;function cloneBuffer(e,r){if(r)return e.slice();var t=e.length,n=allocUnsafe?allocUnsafe(t):new e.constructor(t);return e.copy(n),n}function cloneArrayBuffer(e){var r=new e.constructor(e.byteLength);return new Uint8Array(r).set(new Uint8Array(e)),r}function cloneTypedArray(e,r){var t=r?cloneArrayBuffer(e.buffer):e.buffer;return new e.constructor(t,e.byteOffset,e.length)}function copyArray(e,r){var t=-1,n=e.length;for(r||(r=Array(n));++t0){if(++r>=HOT_COUNT)return arguments[0]}else r=0;return e.apply(void 0,arguments)}}var setToString=shortOut(baseSetToString);function baseRest(e,r){return setToString(overRest(e,r,identity),e+"")}function isIterateeCall(e,r,t){if(!isObject(t))return!1;var n=typeof r;return!!("number"==n?isArrayLike$1(t)&&isIndex(r,t.length):"string"==n&&r in t)&&eq(t[r],e)}function createAssigner(e){return baseRest((function(r,t){var n=-1,o=t.length,a=o>1?t[o-1]:void 0,i=o>2?t[2]:void 0;for(a=e.length>3&&"function"==typeof a?(o--,a):void 0,i&&isIterateeCall(t[0],t[1],i)&&(a=o<3?void 0:a,o=1),r=Object(r);++n0;)r[t]=arguments[t+1];return function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];return r.reduce((function(e,r){return Reflect.apply(r,null,toArray$1(e))}),Reflect.apply(e,null,t))}};function chainProcessPromises(e){for(var r=[],t=arguments.length-1;t-- >0;)r[t]=arguments[t+1];return function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];return r.reduce((function(e,r){return e.then((function(e){return r(e)}))}),Reflect.apply(e,null,t))}}function objDefineProps(e,r,t,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(e,r)&&Object.defineProperty(e,r,{set:t,get:null===n?function(){return null}:n}),e}function objHasProp(e,r){var t=Object.getOwnPropertyDescriptor(e,r);return void 0!==t&&t.value?t.value:t}function injectToFn(e,r,t,n){void 0===n&&(n=!1);var o=objHasProp(e,r);return!1===n&&void 0!==o?e:(Object.defineProperty(e,r,{value:t,writable:n}),e)}function checkIsContract(e){return isPlainObject(e)&&(isObjectHasKey$1(e,QUERY_NAME)||isObjectHasKey$1(e,MUTATION_NAME)||isObjectHasKey$1(e,SOCKET_NAME))}function isContract(e){return!!checkIsContract(e)&&e}function extractSocketPart(e){return!!isObjectHasKey$1(e,"socket")&&e.socket}function groupByNamespace(e,r){void 0===r&&(r=!1);var t=extractSocketPart(e);if(!1===t){if(r)return e;throw new JsonqlError("socket not found in contract!")}var n,o={},a=0;for(var i in t){var s=t[i],c=s.namespace;c&&(o[c]||(++a,o[c]={}),o[c][i]=s,n||s.public&&(n=c))}return{size:a,nspSet:o,publicNamespace:n}}function getNamespaceInOrder(e,r){var t=[];for(var n in e)n===r?t[1]=n:t[0]=n;return t}var timestamp=function(e){void 0===e&&(e=!1);var r=Date.now();return e?Math.floor(r/1e3):r},formatPayload=function(e){var r;return(r={})[QUERY_ARG_NAME]=e,r};function getNameFromPayload(e){return Object.keys(e)[0]}function createDeliverable(e,r){var t;return(t={})[e]=r,t[TIMESTAMP_PARAM_NAME]=[timestamp()],t}function createQuery(e,r,t){if(void 0===r&&(r=[]),void 0===t&&(t=!1),isString(e)&&isArray(r)){var n=formatPayload(r);return!0===t?n:createDeliverable(e,n)}throw new JsonqlValidationError$1("[createQuery] expect resolverName to be string and args to be array!",{resolverName:e,args:r})}function createQueryStr(e,r,t){return void 0===r&&(r=[]),void 0===t&&(t=!1),JSON.stringify(createQuery(e,r,t))}var NB_EVENT_SERVICE_PRIVATE_STORE=new WeakMap,NB_EVENT_SERVICE_PRIVATE_LAZY=new WeakMap;function hashCode(e){return e.split("").reduce((function(e,r){return(e=(e<<5)-e+r.charCodeAt(0))&e}),0)}var SuspendClass=function(){this.__suspend__=null,this.queueStore=new Set},prototypeAccessors={$suspend:{configurable:!0},$queues:{configurable:!0}};prototypeAccessors.$suspend.set=function(e){var r=this;if("boolean"!=typeof e)throw new Error("$suspend only accept Boolean value!");var t=this.__suspend__;this.__suspend__=e,this.logger("($suspend)","Change from "+t+" --\x3e "+e),!0===t&&!1===e&&setTimeout((function(){r.release()}),1)},SuspendClass.prototype.$queue=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",e),this.queueStore.add(e)),this.__suspend__},prototypeAccessors.$queues.get=function(){var e=this.queueStore.size;return this.logger("($queues)","size: "+e),e>0?Array.from(this.queueStore):[]},SuspendClass.prototype.release=function(){var e=this,r=this.queueStore.size;if(this.logger("(release)","Release was called "+r),r>0){var t=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",t),t.forEach((function(r){e.logger(r),Reflect.apply(e.$trigger,e,r)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(SuspendClass.prototype,prototypeAccessors);var NbEventServiceBase=function(e){function r(r){void 0===r&&(r={}),e.call(this),r.logger&&"function"==typeof r.logger&&(this.logger=r.logger),this.keep=r.keep,this.result=r.keep?[]:null,this.normalStore=new Map,this.lazyStore=new Map}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={normalStore:{configurable:!0},lazyStore:{configurable:!0}};return r.prototype.validateEvt=function(){for(var e=this,r=[],t=arguments.length;t--;)r[t]=arguments[t];return r.forEach((function(r){if("string"!=typeof r)throw e.logger("(validateEvt)",r),new Error("event name must be string type!")})),!0},r.prototype.validate=function(e,r){if(this.validateEvt(e)&&"function"==typeof r)return!0;throw new Error("callback required to be function type!")},r.prototype.validateType=function(e){return!!["on","only","once","onlyOnce"].filter((function(r){return e===r})).length},r.prototype.run=function(e,r,t){this.logger("(run)",e,r,t),this.$done=Reflect.apply(e,t,this.toArray(r))},r.prototype.takeFromStore=function(e,r){void 0===r&&(r="lazyStore");var t=this[r];if(t){if(this.logger("(takeFromStore)",r,t),t.has(e)){var n=t.get(e);return this.logger("(takeFromStore)","has "+e,n),t.delete(e),n}return!1}throw new Error(r+" is not supported!")},r.prototype.addToStore=function(e,r){for(var t,n=[],o=arguments.length-2;o-- >0;)n[o]=arguments[o+2];if(e.has(r)?(this.logger("(addToStore)",r+" existed"),t=e.get(r)):(this.logger("(addToStore)","create new Set for "+r),t=new Set),n.length>2)if(Array.isArray(n[0])){var a=n[2];this.checkTypeInLazyStore(r,a)||t.add(n)}else this.checkContentExist(n,t)||(this.logger("(addToStore)","insert new",n),t.add(n));else t.add(n);return e.set(r,t),[e,t.size]},r.prototype.checkContentExist=function(e,r){return!!Array.from(r).filter((function(r){return r[0]===e[0]})).length},r.prototype.checkTypeInStore=function(e,r){this.validateEvt(e,r);var t=this.$get(e,!0);return!1===t||!t.filter((function(e){var t=e[3];return r!==t})).length},r.prototype.checkTypeInLazyStore=function(e,r){this.validateEvt(e,r);var t=this.lazyStore.get(e);return this.logger("(checkTypeInLazyStore)",t),!!t&&!!Array.from(t).filter((function(e){return e[2]!==r})).length},r.prototype.addToNormalStore=function(e,r,t,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",e,r,"try to add to normal store"),this.checkTypeInStore(e,r)){this.logger("(addToNormalStore)",r+" can add to "+e+" normal store");var o=this.hashFnToKey(t),a=[this.normalStore,e,o,t,n,r],i=Reflect.apply(this.addToStore,this,a),s=i[0],c=i[1];return this.normalStore=s,c}return!1},r.prototype.addToLazyStore=function(e,r,t,n){void 0===r&&(r=[]),void 0===t&&(t=null),void 0===n&&(n=!1);var o=[this.lazyStore,e,this.toArray(r),t];n&&o.push(n);var a=Reflect.apply(this.addToStore,this,o),i=a[0],s=a[1];return this.lazyStore=i,s},r.prototype.toArray=function(e){return Array.isArray(e)?e:[e]},t.normalStore.set=function(e){NB_EVENT_SERVICE_PRIVATE_STORE.set(this,e)},t.normalStore.get=function(){return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)},t.lazyStore.set=function(e){NB_EVENT_SERVICE_PRIVATE_LAZY.set(this,e)},t.lazyStore.get=function(){return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)},r.prototype.hashFnToKey=function(e){return hashCode(e.toString())+""},Object.defineProperties(r.prototype,t),r}(SuspendClass),EventService=function(e){function r(r){void 0===r&&(r={}),e.call(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={$done:{configurable:!0}};return r.prototype.logger=function(){},r.prototype.$on=function(e,r,t){var n=this;void 0===t&&(t=null);this.validate(e,r);var o=this.takeFromStore(e);if(!1===o)return this.logger("($on)",e+" callback is not in lazy store"),this.addToNormalStore(e,"on",r,t);this.logger("($on)",e+" found in lazy store");var a=0;return o.forEach((function(o){var i=o[0],s=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 "+e),n.run(r,i,t||s),a+=n.addToNormalStore(e,"on",r,t||s)})),a},r.prototype.$once=function(e,r,t){void 0===t&&(t=null),this.validate(e,r);var n=this.takeFromStore(e);this.normalStore;if(!1===n)return this.logger("($once)",e+" not in the lazy store"),this.addToNormalStore(e,"once",r,t);this.logger("($once)",n);var o=Array.from(n)[0],a=o[0],i=o[1],s=o[2];if(s&&"once"!==s)throw new Error("You are trying to register an event already been taken by other type: "+s);this.logger("($once)","call run for "+e),this.run(r,a,t||i),this.$off(e)},r.prototype.$only=function(e,r,t){var n=this;void 0===t&&(t=null),this.validate(e,r);var o=!1,a=this.takeFromStore(e);(this.normalStore.has(e)||(this.logger("($only)",e+" add to store"),o=this.addToNormalStore(e,"only",r,t)),!1!==a)&&(this.logger("($only)",e+" found data in lazy store to execute"),Array.from(a).forEach((function(o){var a=o[0],i=o[1],s=o[2];if(s&&"only"!==s)throw new Error("You are trying to register an event already been taken by other type: "+s);n.logger("($only)","call run for "+e),n.run(r,a,t||i)})));return o},r.prototype.$onlyOnce=function(e,r,t){void 0===t&&(t=null),this.validate(e,r);var n=!1,o=this.takeFromStore(e);if(this.normalStore.has(e)||(this.logger("($onlyOnce)",e+" add to store"),n=this.addToNormalStore(e,"onlyOnce",r,t)),!1!==o){this.logger("($onlyOnce)",o);var a=Array.from(o)[0],i=a[0],s=a[1],c=a[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 "+e),this.run(r,i,t||s),this.$off(e)}return n},r.prototype.$replace=function(e,r,t,n){if(void 0===t&&(t=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(e);var o=this["$"+n];return this.logger("($replace)",e,r),Reflect.apply(o,this,[e,r,t])}throw new Error(n+" is not supported!")},r.prototype.$trigger=function(e,r,t,n){void 0===r&&(r=[]),void 0===t&&(t=null),void 0===n&&(n=!1),this.validateEvt(e);var o=0,a=this.normalStore;if(this.logger("($trigger)","normalStore",a),a.has(e)){var i=this.$queue(e,r,t,n);if(this.logger("($trigger)",e,"found; add to queue: ",i),!0===i)return this.logger("($trigger)",e,"not executed. Exit now."),!1;for(var s=Array.from(a.get(e)),c=s.length,u=!1,l=0;l-1?r.indexOf("https")>-1?r.replace("https","wss"):r.replace("http","ws"):r};function createWsClient(e,r){return void 0===r&&(r=!1),!1===r?function(r){return new e(fixWss$1(r))}:function(r,t){var n=fixWss$1(r),o=t&&"string"==typeof t?n+"?"+TOKEN_PARAM_NAME+"="+t:n;try{return new e(o)}catch(e){return console.error("WebSocket Connection Error",e),!1}}}var SOCKET_IO=JS_WS_SOCKET_IO_NAME,EMIT_EVT=EMIT_REPLY_TYPE;function createNspClient(e,r){var t=r.hostname,n=r.wssPath,o=r.wsOptions;return(0,r.nspClient)(e?[t,e].join("/"):n,o)}function createNspAuthClient(e,r){var t=r.hostname,n=r.wssPath,o=r.token,a=r.wsOptions,i=r.nspAuthClient,s=e?[t,e].join("/"):n;if(o&&"string"!=typeof o)throw new Error("Expect token to be string, but got "+o);return i(s,o,a)}var clearMainEmitEvt=function(e,r){toArray$1(r).forEach((function(r){e.$off(createEvt(r,EMIT_REPLY_TYPE))}))};function triggerNamespacesOnError(e,r,t,n){void 0===n&&(n={});var o=n.useCallbackStyle?ERROR_PROP_NAME:ON_ERROR_PROP_NAME;r.forEach((function(r){e.$call(createEvt(r,o),[{message:t,namespace:r}])}))}var notLoginWsHandler=function(e,r,t){var n=t.useCallbackStyle,o=n?ERROR_PROP_NAME:ON_ERROR_PROP_NAME,a=n?RESULT_PROP_NAME:ON_RESULT_PROP_NAME;r.$only(createEvt(e,EMIT_EVT),(function(n,i){t.logger("noLoginHandler hijack the ws call",e,n,i);var s={message:NOT_LOGIN_ERR_MSG};r.$call(createEvt(e,n,o),[s]),r.$call(createEvt(e,n,a),[{error:s}])}))},getPrivateNamespace=function(e){return e.length>1&&e[0]};function clientEventHandler(e,r,t,n,o,a){var i=getPrivateNamespace(o),s=!1;o.forEach((function(o){if(s=i===o,a[o]){e.logger("call bindWsHandler",s,o);var c=[o,a[o],t,s,e];if(e.serverType===SOCKET_IO){var u=r.nspSet;c.push(u[o])}Reflect.apply(n,null,c)}else notLoginWsHandler(o,t,e)})),t.$on(LOGOUT_EVENT_NAME,(function(){e.logger("LOGOUT_EVENT_NAME"),triggerNamespacesOnError(t,o,LOGOUT_EVENT_NAME),o.forEach((function(r){clearMainEmitEvt(t,r),a[r]=!1,notLoginWsHandler(r,t,e)}))}))}var keys$1=[WS_REPLY_TYPE,WS_EVT_NAME,WS_DATA_NAME],isWsReply=function(e){var r=e.data;return!!r&&(keys$1.filter((function(e){return isObjectHasKey$1(r,e)})).length===keys$1.length&&r)},extractWsPayload=function(e){var r,t=e.data,n=isString$1(t)?JSON.parse(t):t;if(!1!==(r=isWsReply(n)))return{resolverName:r[WS_EVT_NAME],data:r[WS_DATA_NAME],type:r[WS_REPLY_TYPE]};throw new JsonqlError("payload can not be decoded",e)},dummyLogger$1=function(){},errorTypeHandler=function(e,r,t,n,o){var a=[r];t&&a.push(t),a.push(o);var i=Reflect.apply(createEvt,null,a),s=n.data||n;e.$trigger(i,[s])};function wsMainHandler(e,r,t,n,o){var a=o.log||dummyLogger$1;a("wsMainHandler log test");var i=o.useCallbackStyle,s=i?READY_PROP_NAME:ON_READY_PROP_NAME,c=i?LOGIN_PROP_NAME:ON_LOGIN_PROP_NAME,u=i?MESSAGE_PROP_NAME:ON_MESSAGE_PROP_NAME,l=i?RESULT_PROP_NAME:ON_RESULT_PROP_NAME,f=i?ERROR_PROP_NAME:ON_ERROR_PROP_NAME;r.onopen=function(){a("ws.onopen listened"),t.$call(s,e),n&&(a("isPrivate and fire the "+c),t.$call(c,e)),t.$only(createEvt(e,EMIT_REPLY_TYPE),(function(e,t){a("calling server",e,t),r.send(createQueryStr(e,t))}))},r.onmessage=function(r){try{var n=extractWsPayload(r),o=n.resolverName,i=n.type;switch(a("Hear from server",i,n),i){case EMIT_REPLY_TYPE:var s=createEvt(e,o,u),c=t.$trigger(s,[n]);a("EMIT_REPLY_TYPE",s,c);break;case ACKNOWLEDGE_REPLY_TYPE:var p=createEvt(e,o,l);t.$trigger(p,[n]);break;case ERROR_TYPE:a("ERROR_TYPE"),errorTypeHandler(t,e,o,n,f);break;default:a("Unhandled event!",n),errorTypeHandler(t,e,o,n,f)}}catch(r){console.error("ws.onmessage error",r),errorTypeHandler(t,e,!1,r,f)}},r.onclose=function(){a("ws.onclose callback")},t.$on(LOGOUT_EVENT_NAME,(function(){try{a("terminate ws connection"),r.terminate()}catch(e){console.error("ws.terminate error",e)}}))}var createNsps=function(e,r,t){var n=r.nspSet,o=r.publicNamespace,a=!1,i=[],s={};if(e.enableAuth)a=!0,s=(i=getNamespaceInOrder(n,o)).map((function(r,n){var o,a,i;return 0===n?t?(e.token=t,(o={})[r]=createNspAuthClient(r,e),o):((a={})[r]=!1,a):((i={})[r]=createNspClient(r,e),i)})).reduce((function(e,r){return Object.assign(e,r)}),{});else{var c=getNameFromPayload(n);i.push(c),s[c]=createNspClient(!1,e)}return{nsps:s,namespaces:i,login:a}};function createClient(e,r,t){var n=[e,r,t,wsMainHandler],o=e.token,a=createNsps(e,r,o),i=a.nsps,s=a.namespaces,c=a.login;return Reflect.apply(clientEventHandler,null,n.concat([s,i])),c&&t.$only(LOGIN_EVENT_NAME,(function(o){clearMainEmitEvt(t,s);var a=createNsps(e,r,o);Reflect.apply(clientEventHandler,null,n.concat([a.namespaces,a.nsps]))})),{opts:e,nspMap:r,ee:t}}function createClientResolver(e){var r=createWsClient(e),t=createWsClient(e,!0);return function(e,n,o){return e.nspClient=r,e.nspAuthClient=t,createClient(e,n,o)}}var wsClientResolver=createClientResolver(WebSocket),node=wsClient(wsClientResolver,constProps);module.exports=node; //# sourceMappingURL=node.js.map diff --git a/packages/@jsonql/ws/package.json b/packages/@jsonql/ws/package.json index 8372e5bd..7f7a0464 100644 --- a/packages/@jsonql/ws/package.json +++ b/packages/@jsonql/ws/package.json @@ -1,6 +1,6 @@ { "name": "@jsonql/ws", - "version": "1.0.0", + "version": "1.0.1", "description": "jsonql WS (WebSocket) client module for browser / node", "main": "node.js", "browser": "dist/jsonql-ws.umd.js", @@ -45,7 +45,7 @@ "jsonql-jwt": "^1.3.8", "jsonql-params-validator": "^1.5.2", "jsonql-utils": "^0.9.3", - "jsonql-ws-client-core": "^0.2.0", + "jsonql-ws-client-core": "^0.3.0", "ws": "^7.2.0" }, "devDependencies": { diff --git a/packages/@jsonql/ws/src/core/create-client.js b/packages/@jsonql/ws/src/core/create-client.js index 50f0aafe..22c707c3 100644 --- a/packages/@jsonql/ws/src/core/create-client.js +++ b/packages/@jsonql/ws/src/core/create-client.js @@ -20,10 +20,10 @@ import { wsMainHandler } from './ws-main-handler' * @return {object} nsps namespace with namespace as key */ const createNsps = function(opts, nspMap, token) { - let { nspSet, publicNamespace } = nspMap; - let login = false; - let namespaces = []; - let nsps = {}; + let { nspSet, publicNamespace } = nspMap + let login = false + let namespaces = [] + let nsps = {} // first we need to binding all the events handler if (opts.enableAuth) { // && opts.useJwt login = true; // just saying we need to listen to login event @@ -31,7 +31,7 @@ const createNsps = function(opts, nspMap, token) { nsps = namespaces.map((namespace, i) => { if (i === 0) { if (token) { - opts.token = token; + opts.token = token // console.log('create createNspAuthClient at run time', opts) return {[namespace]: createNspAuthClient(namespace, opts)} } @@ -61,7 +61,7 @@ export function createClient(opts, nspMap, ee) { // arguments that don't change const args = [opts, nspMap, ee, wsMainHandler] // now create the nsps - const { token } = opts; + const { token } = opts const { nsps, namespaces, login } = createNsps(opts, nspMap, token) // binding the listeners - and it will listen to LOGOUT event // to unbind itself, and the above call will bind it again diff --git a/packages/@jsonql/ws/src/core/create-ws-client.js b/packages/@jsonql/ws/src/core/create-ws-client.js index b16522bb..b15fd16c 100644 --- a/packages/@jsonql/ws/src/core/create-ws-client.js +++ b/packages/@jsonql/ws/src/core/create-ws-client.js @@ -13,7 +13,7 @@ const fixWss = url => { } return uri.replace('http', 'ws') } - return uri; + return uri } /** @@ -38,12 +38,12 @@ export function createWsClient(WebSocket, auth = false) { return function createWsAuthClientHandler(url, token) { const ws_url = fixWss(url) // console.log('what happen here?', url, ws_url, token) - const uri = token && typeof token === 'string' ? `${ws_url}?${TOKEN_PARAM_NAME}=${token}` : ws_url; + const uri = token && typeof token === 'string' ? `${ws_url}?${TOKEN_PARAM_NAME}=${token}` : ws_url try { return new WebSocket(uri) } catch(e) { console.error('WebSocket Connection Error', e) - return false; + return false } } } diff --git a/packages/@jsonql/ws/src/core/extract-ws-payload.js b/packages/@jsonql/ws/src/core/extract-ws-payload.js index 77e5a1cc..d93aa55a 100644 --- a/packages/@jsonql/ws/src/core/extract-ws-payload.js +++ b/packages/@jsonql/ws/src/core/extract-ws-payload.js @@ -11,12 +11,12 @@ const keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ] * @return {boolean} true is OK */ const isWsReply = payload => { - const { data } = payload; + const { data } = payload if (data) { let result = keys.filter(key => isObjectHasKey(data, key)) - return (result.length === keys.length) ? data : false; + return (result.length === keys.length) ? data : false } - return false; + return false } /** @@ -25,7 +25,7 @@ const isWsReply = payload => { */ const extractWsPayload = payload => { const { data } = payload; - let json = isString(data) ? JSON.parse(data) : data; + let json = isString(data) ? JSON.parse(data) : data // debugFn('extractWsPayload', json) let fdata; if ((fdata = isWsReply(json)) !== false) { @@ -33,7 +33,7 @@ const extractWsPayload = payload => { resolverName: fdata[WS_EVT_NAME], data: fdata[WS_DATA_NAME], type: fdata[WS_REPLY_TYPE] - }; + } } throw new JsonqlError('payload can not be decoded', payload) } diff --git a/packages/@jsonql/ws/src/core/ws-main-handler.js b/packages/@jsonql/ws/src/core/ws-main-handler.js index bc798945..b6d26602 100644 --- a/packages/@jsonql/ws/src/core/ws-main-handler.js +++ b/packages/@jsonql/ws/src/core/ws-main-handler.js @@ -56,6 +56,8 @@ export function wsMainHandler(namespace, ws, ee, isPrivate, opts) { const debugFn = opts.log || dummyLogger + debugFn(`wsMainHandler log test`) + const { useCallbackStyle } = opts; const READY_EVT_NAME = useCallbackStyle ? READY_PROP_NAME : ON_READY_PROP_NAME; const LOGIN_EVT_NAME = useCallbackStyle ? LOGIN_PROP_NAME : ON_LOGIN_PROP_NAME; -- Gitee From 43c0e557d95dd16228e1c291577af7406ee32bed Mon Sep 17 00:00:00 2001 From: joelchu Date: Wed, 11 Dec 2019 15:11:00 +0800 Subject: [PATCH 3/3] jsonql-client 1.5.7 fix the log --- packages/@jsonql/client/package.json | 2 +- .../tests/dist/jsonql-client-ws.debug.js | 98 +++++++++---------- .../tests/dist/jsonql-client-ws.debug.js.map | 2 +- .../client/tests/qunit/files/ws-basic-test.js | 6 +- packages/http-client/core.js | 2 +- .../http-client/dist/jsonql-client.static.js | 2 +- .../http-client/dist/jsonql-client.umd.js | 2 +- packages/http-client/package.json | 2 +- packages/http-client/src/base/base-cls.js | 7 +- .../src/core/jsonql-api-generator.js | 10 +- packages/http-client/static.js | 2 +- .../tests/qunit/tests/base-test.js | 1 + 12 files changed, 68 insertions(+), 68 deletions(-) diff --git a/packages/@jsonql/client/package.json b/packages/@jsonql/client/package.json index 4a9ea789..e911dfe1 100644 --- a/packages/@jsonql/client/package.json +++ b/packages/@jsonql/client/package.json @@ -49,7 +49,7 @@ "jsonql-client": "^1.5.6" }, "optionalDependencies": { - "@jsonql/ws": "^1.0.0" + "@jsonql/ws": "^1.0.1" }, "devDependencies": { "@jsonql/koa": "^0.8.1", diff --git a/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js b/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js index 4f398043..358e3519 100644 --- a/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js +++ b/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js @@ -93,9 +93,9 @@ var JS_WS_NAME = 'ws'; // for ws client - var ON_MESSAGE_PROP_NAME$1 = 'onMessage'; - var ON_RESULT_PROP_NAME$1 = 'onResult'; - var ON_ERROR_PROP_NAME$1 = 'onError'; + var ON_MESSAGE_PROP_NAME = 'onMessage'; + var ON_RESULT_PROP_NAME = 'onResult'; + var ON_ERROR_PROP_NAME = 'onError'; var ON_READY_PROP_NAME = 'onReady'; var ON_LOGIN_PROP_NAME = 'onLogin'; // new @1.8.6 @@ -105,7 +105,7 @@ var MESSAGE_PROP_NAME = 'message'; var RESULT_PROP_NAME = 'result'; var ERROR_PROP_NAME = 'error'; - var READY_PROP_NAME$1 = 'ready'; + var READY_PROP_NAME = 'ready'; var LOGIN_PROP_NAME = 'login'; // new @1.8.6 var NOT_LOGIN_ERR_MSG = 'NOT LOGIN'; var HSA_ALGO = 'HS256'; @@ -9456,7 +9456,7 @@ if ( args === void 0 ) args = []; var eventName = createEvt(namespace, EMIT_REPLY_TYPE); - var RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME$1; + var RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME; // debugFn(`actionCall: ${eventName} --> ${resolverName}`, args) ee.$trigger(eventName, [resolverName, toArray(args)]); // once we trigger there is nothing return from the resolve @@ -9477,7 +9477,7 @@ // last of the chain so only return the resolver (fn) var setupSend = function (fn, ee, namespace, resolverName, params, useCallbackStyle) { return ( objDefineProps(fn, SEND_MSG_PROP_NAME, function sendSetter(messagePayload) { - var ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME$1; + var ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME; // debugFn('got payload for', messagePayload) // @NOTE change from sync interface to async @ 1.0.0 // this way we will able to catch all the error(s) @@ -9589,13 +9589,13 @@ // onResult handler var setupOnResult = function (fn, ee, namespace, resolverName, params, useCallbackStyle) { return [ - objDefineProps(fn, ON_RESULT_PROP_NAME$1, function(resultCallback) { + objDefineProps(fn, ON_RESULT_PROP_NAME, function(resultCallback) { if (isFunc(resultCallback)) { ee.$on( - createEvt(namespace, resolverName, ON_RESULT_PROP_NAME$1), + createEvt(namespace, resolverName, ON_RESULT_PROP_NAME), function resultHandler(result) { respondHandler(result, resultCallback, function (error) { - ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME$1), error); + ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error); }); } ); @@ -9611,17 +9611,17 @@ // we do need to add the send prop back because it's the only way to deal with // bi-directional data stream var setupOnMessage = function (fn, ee, namespace, resolverName, params, useCallbackStyle) { return [ - objDefineProps(fn, ON_MESSAGE_PROP_NAME$1, function(messageCallback) { + objDefineProps(fn, ON_MESSAGE_PROP_NAME, function(messageCallback) { // we expect this to be a function if (isFunc(messageCallback)) { // did that add to the callback var onMessageCallback = function (args) { respondHandler(args, messageCallback, function (error) { - ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME$1), error); + ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error); }); }; // register the handler for this message event - ee.$only(createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME$1), onMessageCallback); + ee.$only(createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME), onMessageCallback); } }), ee, @@ -9633,10 +9633,10 @@ // add an ON_ERROR_PROP_NAME handler var setupOnError = function (fn, ee, namespace, resolverName, params, useCallbackStyle) { return [ - objDefineProps(fn, ON_ERROR_PROP_NAME$1, function(resolverErrorHandler) { + objDefineProps(fn, ON_ERROR_PROP_NAME, function(resolverErrorHandler) { if (isFunc(resolverErrorHandler)) { // please note ON_ERROR_PROP_NAME can add multiple listners - ee.$only(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME$1), resolverErrorHandler); + ee.$only(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), resolverErrorHandler); } }), ee, @@ -9703,13 +9703,13 @@ // using the onError as name // @TODO we should follow the convention earlier // make this a setter for the obj itself - return objDefineProps(obj, ON_ERROR_PROP_NAME$1, function namespaceErrorCallbackHandler(namespaceErrorHandler) { + return objDefineProps(obj, ON_ERROR_PROP_NAME, function namespaceErrorCallbackHandler(namespaceErrorHandler) { if (isFunc(namespaceErrorHandler)) { // please note ON_ERROR_PROP_NAME can add multiple listners for (var namespace in nspSet) { // this one is very tricky, we need to make sure the trigger is calling // with the namespace as well as the error - ee.$on(createEvt(namespace, ON_ERROR_PROP_NAME$1), namespaceErrorHandler); + ee.$on(createEvt(namespace, ON_ERROR_PROP_NAME), namespaceErrorHandler); } } }) @@ -9771,11 +9771,11 @@ ee.$on(createEvt(namespace, ERROR_PROP_NAME), callback); } break; - case LOGIN_PROP_NAME: + case LOGIN_PROP_NAME: // @TODO should only available when enableAuth=true ee.$only(LOGIN_PROP_NAME, callback); break; - case READY_PROP_NAME$1: - ee.$on(READY_PROP_NAME$1, callback); + case READY_PROP_NAME: + ee.$on(READY_PROP_NAME, callback); break; default: ee.$trigger(ERROR_PROP_NAME, new JsonqlError(CB_FN_NAME, ("Unknown event name " + evtName + "!"))); @@ -9889,32 +9889,26 @@ function generator$1(opts, nspMap, ee) { var nspSet = nspMap.nspSet; var useCallbackStyle = opts.useCallbackStyle; + var enableAuth = opts.enableAuth; var args = [getMappedObj]; if (useCallbackStyle) { args.push(function (obj) { return createCallbackHandler(obj, ee, nspSet); }); } else { args.push( function (obj1) { return createNamespaceErrorHandler(obj1, ee, nspSet); }, - function (obj2) { return createOnReadyhandler(obj2, ee); }, - function (obj3) { return createOnLoginhandler(obj3, ee, opts); } + function (obj2) { return createOnReadyhandler(obj2, ee); } ); + if (enableAuth) { + args.push(function (obj3) { return createOnLoginhandler(obj3, ee, opts); }); + } + } + // this only apply to when enableAuth = true + if (enableAuth) { + args.push(function (obj4) { return createAuthMethods$1(obj4, ee, opts); }); } - args.push(function (obj4) { return createAuthMethods$1(obj4, ee, opts); }); // run it var executor = Reflect.apply(chainProcessPromises, null, args); return executor(opts, nspMap, ee) - - /* - return getMappedObj(opts, nspMap, ee) - // add error handler - .then(obj1 => createNamespaceErrorHandler(obj1, ee, nspSet)) - // add onReady handler - .then(obj2 => createOnReadyhandler(obj2, ee, nspSet)) - // add onLogin handler -- this is optional - .then(obj3 => createOnLoginhandler(obj3, ee, opts)) - // Auth related methods -- this is optional - .then(obj4 => createAuthMethods(obj4, ee, opts)) - */ } var obj$9, obj$1$1; @@ -9987,7 +9981,7 @@ } // the top level API - + var dummyLogger = function () {}; /** * The main interface which will generate the socket clients and map all events * @param {object} socketClientResolver this is the one method export by various clients @@ -9998,7 +9992,7 @@ if ( constProps === void 0 ) constProps = {}; var log = constProps.log; // 1.3.9 if we pass a log method here then we use this - var logger = log && typeof log === 'function' ? log : function () {}; + var logger = log && typeof log === 'function' ? log : dummyLogger; // we need to inject property to this client later // therefore we need to do it this way return function (opts) { @@ -10075,7 +10069,7 @@ } return uri.replace('http', 'ws') } - return uri; + return uri }; /** @@ -10107,7 +10101,7 @@ return new WebSocket(uri) } catch(e) { console.error('WebSocket Connection Error', e); - return false; + return false } } } @@ -10186,7 +10180,7 @@ if ( opts === void 0 ) opts = {}; var useCallbackStyle = opts.useCallbackStyle; - var ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME$1; + var ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME; namespaces.forEach( function (namespace) { ee.$call(createEvt(namespace, ERROR_SUBFIX), [{ message: message, namespace: namespace }]); }); @@ -10203,8 +10197,8 @@ */ var notLoginWsHandler = function (namespace, ee, opts) { var useCallbackStyle = opts.useCallbackStyle; - var ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME$1; - var RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME$1; + var ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME; + var RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME; ee.$only( createEvt(namespace, EMIT_EVT), function notLoginHandlerCallback(resolverName, args) { @@ -10294,9 +10288,9 @@ var data = payload.data; if (data) { var result = keys$1.filter(function (key) { return isObjectHasKey$1(data, key); }); - return (result.length === keys$1.length) ? data : false; + return (result.length === keys$1.length) ? data : false } - return false; + return false }; /** @@ -10313,13 +10307,13 @@ resolverName: fdata[WS_EVT_NAME], data: fdata[WS_DATA_NAME], type: fdata[WS_REPLY_TYPE] - }; + } } throw new JsonqlError('payload can not be decoded', payload) }; // the WebSocket main handler - var dummyLogger = function () {}; + var dummyLogger$1 = function () {}; /** * under extremely circumstances we might not even have a resolverName, then * we issue a global error for the developer to catch it @@ -10353,14 +10347,16 @@ */ function wsMainHandler(namespace, ws, ee, isPrivate, opts) { - var debugFn = opts.log || dummyLogger; + var debugFn = opts.log || dummyLogger$1; + + debugFn("wsMainHandler log test"); var useCallbackStyle = opts.useCallbackStyle; - var READY_EVT_NAME = useCallbackStyle ? READY_PROP_NAME$1 : ON_READY_PROP_NAME; + var READY_EVT_NAME = useCallbackStyle ? READY_PROP_NAME : ON_READY_PROP_NAME; var LOGIN_EVT_NAME = useCallbackStyle ? LOGIN_PROP_NAME : ON_LOGIN_PROP_NAME; - var MESSAGE_EVT_NAME = useCallbackStyle ? MESSAGE_PROP_NAME : ON_MESSAGE_PROP_NAME$1; - var RESULT_EVT_NAME = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME$1; - var ERROR_EVT_NAME = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME$1; + var MESSAGE_EVT_NAME = useCallbackStyle ? MESSAGE_PROP_NAME : ON_MESSAGE_PROP_NAME; + var RESULT_EVT_NAME = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME; + var ERROR_EVT_NAME = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME; // connection open ws.onopen = function onOpenCallback() { debugFn('ws.onopen listened'); @@ -10368,7 +10364,7 @@ ee.$call(READY_EVT_NAME, namespace); // need an extra parameter here to id the private nsp if (isPrivate) { - console.log(("isPrivate and fire the " + LOGIN_EVT_NAME)); + debugFn(("isPrivate and fire the " + LOGIN_EVT_NAME)); ee.$call(LOGIN_EVT_NAME, namespace); } // add listener only after the open is called diff --git a/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js.map b/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js.map index f88a4499..423b9eb6 100644 --- a/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js.map +++ b/packages/@jsonql/client/tests/dist/jsonql-client-ws.debug.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client-ws.debug.js","sources":["../../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/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-utils/src/contract.js","../../node_modules/nb-event-service/src/hash-code.js","../../node_modules/jsonql-client/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/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","../../node_modules/jsonql-utils/src/timestamp.js","../../node_modules/store/plugins/defaults.js","../../node_modules/jsonql-client/src/stores/local-store.js","../../node_modules/jsonql-client/src/stores/session-store.js","../../node_modules/jsonql-client/src/stores/index.js","../../node_modules/jsonql-utils/src/params-api.js","../../node_modules/jsonql-utils/src/results.js","../../node_modules/jsonql-client/src/base/store-cls.js","../../node_modules/jsonql-client/src/base/http-cls.js","../../node_modules/jsonql-client/src/base/contract-cls.js","../../node_modules/jsonql-client/src/base/auth-cls.js","../../node_modules/jsonql-client/src/base/base-cls.js","../../node_modules/jsonql-client/src/base/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","../../node_modules/jsonql-client/src/ee.js","../../node_modules/jsonql-client/src/core/methods-generator.js","../../node_modules/jsonql-client/src/core/jsonql-api-generator.js","../../node_modules/jsonql-client/src/options/base-options.js","../../node_modules/jsonql-client/src/options/check-options-async.js","../../node_modules/jsonql-client/src/options/index.js","../../node_modules/jsonql-client/module.js","../../node_modules/jsonql-utils/src/chain-promises.js","../../node_modules/jsonql-utils/src/pre-config-check.js","../../node_modules/jsonql-client/opt.js","../../node_modules/jsonql-ws-client-core/src/options/constants.js","../../node_modules/jsonql-ws-client-core/src/utils/ee.js","../../node_modules/jsonql-ws-client-core/src/utils/process-contract.js","../../node_modules/jsonql-ws-client-core/src/utils/helpers.js","../../node_modules/jsonql-ws-client-core/src/core/respond-handler.js","../../node_modules/jsonql-ws-client-core/src/core/action-call.js","../../node_modules/jsonql-ws-client-core/src/core/setup-callback-api.js","../../node_modules/jsonql-ws-client-core/src/core/setup-resolver.js","../../node_modules/jsonql-ws-client-core/src/core/resolver-methods.js","../../node_modules/jsonql-ws-client-core/src/core/setup-auth-methods.js","../../node_modules/jsonql-ws-client-core/src/core/generator.js","../../node_modules/jsonql-ws-client-core/src/options/index.js","../../node_modules/jsonql-ws-client-core/src/api.js","../../node_modules/@jsonql/ws/src/options/index.js","../../node_modules/@jsonql/ws/src/core/create-ws-client.js","../../node_modules/jsonql-ws-client/src/options/constants.js","../../node_modules/jsonql-ws-client/src/share/create-nsp-client.js","../../node_modules/jsonql-ws-client/src/utils/helpers.js","../../node_modules/jsonql-ws-client/src/share/trigger-namespaces-on-error.js","../../node_modules/jsonql-ws-client/src/share/client-event-handler.js","../../node_modules/@jsonql/ws/src/core/extract-ws-payload.js","../../node_modules/@jsonql/ws/src/core/ws-main-handler.js","../../node_modules/@jsonql/ws/src/core/create-client.js","../../node_modules/@jsonql/ws/src/core/create-client-resolver.js","../../node_modules/@jsonql/ws/src/ws-client-resolver.js","../../node_modules/@jsonql/ws/index.js","../../node_modules/jsonql-ws-client/src/options/index.js","../../node_modules/@jsonql/ws/opt.js","../../ws.js"],"sourcesContent":["/**\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","/**\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","// 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","// 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 * construct the actual end user method, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfigAsync = function(validateSync) {\n /**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n/**\n * copy of above but it's sync, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n getCheckConfigAsync,\n getCheckConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\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// construct the final output 1.5.2\nexport const checkConfigAsync = jsonqlOptions.getCheckConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.getCheckConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/options/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 // cache\n this.__userdata__ = null;\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.__userdata__ = this.decoder(token)\n this.jsonqlUserdata = this.__userdata__\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 \n return { token, userdata: this.__userdata__ }\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","// 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","// 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, userdata}) => {\n ee.$trigger(LOGIN_NAME, token)\n // 1.5.6 return the decoded userdata instead\n return userdata\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) { // this one has a server side logout\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 { // this is only for client side logout\n // @TODO should allow to login particular profile\n auth[logoutHandlerName] = function logoutHandlerFn(profileId = null) {\n jsonqlInstance.postLogoutAction(KEY_WORD, profileId)\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 // 1.5.2 change it to a getter to return a method, pass a name to id which one is which\n client.getLogger = (name) => (...args) => Reflect.apply(jsonqlInstance.log, jsonqlInstance, [name].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","// new module interface for @jsonql/client\n// this will be use with the @jsonql/ws, @jsonql/socketio\nimport { SOCKET_NAME } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\nimport JsonqlBaseClient from './src/base'\nimport getEventEmitter from './src/ee'\nimport generator from './src/core/jsonql-api-generator'\nimport { checkOptionsAsync } from './src/options'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { isObjectHasKey } from 'jsonql-utils/src/generic'\nimport { getContractFromConfig } from './src/utils'\n\n/**\n * Check if the contract has socket field and the socket client is suplied\n * @param {object} client the http client\n * @param {object} contract the json\n * @param {object} config the checked configuration\n * @param {object} socketClient from the original config\n * @return {object} the completed client\n */\nfunction initSocketClient(client, contract, config, socketClient) {\n if (isObjectHasKey(contract, SOCKET_NAME)) {\n if (socketClient) {\n // pass the contract here one more time in case the constProps overwritten it\n config.log = client.getLogger(`jsonql-client:${config.serverType}`)\n config.contract = contract\n config.eventEmitter = client.eventEmitter\n return socketClient(config)\n .then(sc => {\n client[SOCKET_NAME] = sc\n return client\n })\n } else {\n throw new JsonqlError(`initSocketClient`, `socketClient is missing!`)\n }\n }\n return client\n}\n\n/**\n * Main interface for jsonql fetch api\n * @1.4.8 change this to named export to diff this from the other\n * and this is only use with the @jsonql/client to construct the client with ws\n * @param {object} Fly the http engine\n * @param {object} [config={}] configuration\n * @return {object} jsonqlClient\n */\nfunction jsonqlClientModule(fly, config = {}) {\n const { socketClient, debugOn } = config;\n const ee = getEventEmitter(debugOn)\n return checkOptionsAsync(config)\n .then(opts => (\n {\n opts,\n baseClient: new JsonqlBaseClient(fly, opts)\n }\n ))\n // make sure the contract is presented\n .then(({opts, baseClient}) => getContractFromConfig(baseClient, opts.contract)\n .then(contract => (\n {\n opts,\n contract,\n client: generator(baseClient, opts, contract, ee)\n }\n )\n )\n )\n // finally generate the websocket client if any\n .then(({opts, contract, client}) => (\n initSocketClient(client, contract, opts, socketClient)\n ))\n}\n// export it\nexport { jsonqlClientModule }\n","// break it out on its own because\n// it's building from the lodash-es from scratch\n// according to this discussion https://github.com/lodash/lodash/issues/3298\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport merge from 'lodash-es/merge'\n\n/**\n * previously we already make sure the order of the namespaces\n * and attach the auth client to it\n * @param {array} promises array of unresolved promises\n * @param {boolean} asObject if true then merge the result object\n * @return {object} promise resolved with the array of promises resolved results\n */\nexport function chainPromises(promises, asObject = false) {\n return promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResults => (\n currentTask.then(currentResult => (\n asObject === false ? [...chainResults, currentResult] : merge(chainResults, currentResult)\n ))\n ))\n ), Promise.resolve(\n asObject === false ? [] : (isPlainObject(asObject) ? asObject : {})\n ))\n}\n\n\n/**\n * This one return a different result from the chainPromises\n * it will be the same like chainFns that take one promise resolve as the next fn parameter\n * @param {function} initPromise a function that accept param and resolve result\n * @param {array} promises array of function pass that resolve promises\n * @return {promise} resolve the processed result\n */\nexport function chainProcessPromises(initPromise, ...promises) {\n return (...args) => (\n promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResult => (\n currentTask(chainResult)\n )\n )\n ), Reflect.apply(initPromise, null, args))\n )\n}\n","// this will replace the preConfigCheck in jsonql-koa\n// also this will get use in the client as well\n// basically this is just a wrapper method to load everything together\n// and then add the CHECKED_KEY to it\nimport { CHECKED_KEY } from 'jsonql-constants'\n\nimport { chainFns } from './chain-fns'\nimport { timestamp } from './timestamp'\nimport { injectToFn } from './obj-define-props'\n\n/**\n * the rest of the argument will be functions that\n * need to add to the process chain,\n * finally return a function to accept the config\n * @param {object} defaultOptions prepared before hand\n * @param {object} constProps prepare before hand\n * @param {array} fns arguments see description\n * @return {function} to perform the final configuration check\n */\nexport function preConfigCheck(defaultOptions, constProps, ...fns) {\n // should have just add the method to the last\n const finalFn = opt => injectToFn(opt, CHECKED_KEY, timestamp())\n // if there is more than one then chain it otherwise just return the zero idx one\n const fn = Reflect.apply(chainFns, null, fns.concat(finalFn))\n // 0.8.8 add a default property empty object\n return (config = {}) => fn(config, defaultOptions, constProps)\n}\n","// export the options for the pre-check to use\nimport { preConfigCheck } from 'jsonql-utils/module'\nimport { checkConfig } from 'jsonql-params-validator'\nimport merge from 'lodash-es/merge'\n\nimport { appProps, constProps } from './src/options/base-options'\n// just export the function here for use to save repeat coding\n\n/**\n * This will combine the socket client options and merge this one\n * then do a pre-check on both at the same time\n * @param {object} [extraProps = {}]\n * @param {object} [extraConstProps = {}]\n * @return {function} to process the developer options\n */\nexport function getPreConfigCheck(extraProps = {}, extraConstProps = {}) {\n const aProps = merge({}, appProps, extraProps)\n const cProps = merge({}, constProps, extraConstProps)\n\n return preConfigCheck(aProps, cProps, checkConfig)\n}\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME;\nconst WS = JS_WS_NAME;\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!';\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!';\n\nconst MISSING_PROP_ERR = 'Missing property in contract!';\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!';\n\nconst EMIT_EVT = EMIT_REPLY_TYPE;\n\nconst NAMESPACE_KEY = 'namespaceMap';\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!';\n\nconst NOT_ALLOW_OP = 'This operation is not allow!';\n\nconst MY_NAMESPACE = 'myNamespace'\n\nconst CB_FN_NAME = 'on'\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME\n}\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// create a clone version so we know which one we actually is using\nexport default class JsonqlWsEvt extends NBEventService {\n\n constructor(logger) {\n // this ee will always come with the logger\n // because we should take the ee from the configuration\n super({ logger })\n }\n\n get name() {\n return'jsonql-ws-client'\n }\n}\n","// mapping the resolver to their respective nsp\nimport { JSONQL_PATH, NSP_SET, PUBLIC_NAMESPACE } from 'jsonql-constants'\nimport { groupByNamespace, extractSocketPart } from 'jsonql-utils/module'\nimport { JsonqlResolverNotFoundError } from 'jsonql-errors'\n\nimport { MISSING_PROP_ERR } from '../options/constants'\n\n/**\n * Just make sure the object contain what we are looking for\n * @param {object} opts configuration from checkOptions\n * @return {object} the target content\n */\nconst getResolverList = contract => {\n const result = extractSocketPart(contract)\n if (result !== false) {\n return result\n }\n throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR)\n}\n\n/**\n * process the contract first\n * @param {object} opts configuration\n * @return {object} sorted list\n */\nexport default function processContract(opts) {\n const { contract, enableAuth } = opts;\n if (enableAuth) {\n return groupByNamespace(contract)\n }\n return {\n [NSP_SET]: { [JSONQL_PATH]: getResolverList(contract) },\n [PUBLIC_NAMESPACE]: JSONQL_PATH\n }\n}\n","// group all the small functions here\nimport { JS_WS_SOCKET_IO_NAME, JS_WS_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/src/generic'\n\n// we shouldn't do this anymore\nexport const fixWss = (url, serverType) => {\n // ws only allow ws:// path\n if (serverType === JS_WS_NAME) {\n return url.replace('http://', 'ws://')\n }\n return url;\n}\n\n/**\n * get a stock host name from browser\n */\nexport const getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n throw new JsonqlValidationError(e)\n }\n}\n\n/**\n * Unbind the event\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nexport const clearMainEmitEvt = (ee, namespace) => {\n let nsps = toArray(namespace)\n nsps.forEach(n => {\n ee.$off(createEvt(n, EMIT_REPLY_TYPE))\n })\n}\n\n/**\n * @param {object} nsps namespace as key\n * @param {string} type of server\n */\nexport const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => {\n try {\n // @TODO need to figure out a better way here?\n const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate';\n for (let namespace in nsps) {\n let nsp = nsps[namespace]\n if (nsp && nsp[method]) {\n Reflect.apply(nsp[method], null, [])\n }\n }\n } catch(e) {\n // socket.io throw a this.destroy of undefined?\n console.error('Disconnect call failed', e)\n }\n}\n","// breaking it up further to share between methods\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { UNKNOWN_RESULT } from '../options/constants'\nimport { isObjectHasKey } from '../utils'\n\n/**\n * break out to use in different places to handle the return from server\n * @param {object} data from server\n * @param {function} resolver NOT from promise\n * @param {function} rejecter NOT from promise\n * @return {void} nothing\n */\nexport function respondHandler(data, resolver, rejecter) {\n if (isObjectHasKey(data, ERROR_KEY)) {\n // debugFn('-- rejecter called --', data[ERROR_KEY])\n rejecter(data[ERROR_KEY])\n } else if (isObjectHasKey(data, DATA_KEY)) {\n // debugFn('-- resolver called --', data[DATA_KEY])\n resolver(data[DATA_KEY])\n } else {\n // debugFn('-- UNKNOWN_RESULT --', data)\n rejecter({message: UNKNOWN_RESULT, error: data})\n }\n}\n","// the actual trigger call method\nimport { ON_RESULT_PROP_NAME, RESULT_PROP_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { createEvt, toArray } from '../utils'\nimport { respondHandler } from './respond-handler'\n\n/**\n * just wrapper\n * @param {object} ee EventEmitter\n * @param {string} namespace where this belongs\n * @param {string} resolverName resolver\n * @param {boolean} useCallbackStyle use on or not\n * @param {array} args arguments\n * @return {void} nothing\n */\nexport function actionCall(ee, namespace, resolverName, useCallbackStyle, args = []) {\n const eventName = createEvt(namespace, EMIT_REPLY_TYPE)\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME\n // debugFn(`actionCall: ${eventName} --> ${resolverName}`, args)\n ee.$trigger(eventName, [resolverName, toArray(args)])\n // once we trigger there is nothing return from the resolve\n // @TODO if we need the next then call to have the result back\n // then we need to listen to the event callback here as well\n return new Promise((resolver, rejecter) => {\n ee.$on(\n createEvt(namespace, resolverName, RESULT_SUBFIX),\n function actionCallResultHandler(result) {\n // debugFn(`got the first result`, result)\n respondHandler(result, resolver, rejecter)\n }\n )\n })\n}\n","// @TODO using the obj.on syntax to do the same thing\n/*\nThe new callback style `useCallbackStyle` set to true then use this one\nclient.resolverName.on(EVENT_NAME, cb)\n*/\nimport { JsonqlValidationError, JsonqlError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME\n} from 'jsonql-constants'\nimport { CB_FN_NAME } from '../options/constants'\n\nimport { respondHandler } from './respond-handler'\nimport { chainFns, injectToFn, createEvt, toArray, isFunc, isString } from '../utils'\n\n/**\n * Add extra property to the resolver via the getter\n * @param {function} fn the resolver itself\n * @param {object} ee event emitter\n * @param {string} namespace the namespace this belongs to\n * @param {string} resolverName resolver namee\n * @param {object} params from the contract\n * @return {array} same as what goes in\n */\nexport function setupCallbackApi(fn, ee, namespace, resolverName, params) {\n return [\n injectToFn(fn, CB_FN_NAME, function(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch(evtName) {\n case RESULT_PROP_NAME:\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n // register the handler for this message event\n case MESSAGE_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME),\n function onMessageCallback(args) {\n respondHandler(args, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n case READY_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n callback\n )\n break;\n default:\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n new JsonqlError(resolverName, `Unknown event name ${evtName}!`)\n )\n }\n }\n }),\n ee,\n namespace,\n resolverName,\n params\n ]\n}\n","// break up the original setup resolver method here\nimport { JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\nimport { MY_NAMESPACE } from '../options/constants'\nimport { chainFns, objDefineProps, injectToFn, createEvt, toArray, isFunc } from '../utils'\n\nimport { respondHandler } from './respond-handler'\nimport { setupSend } from './setup-send'\nimport { setupCallbackApi } from './setup-callback-api'\n\n/**\n * The first one in the chain\n * @return {array}\n */\nconst setupNamespace = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n injectToFn(fn, MY_NAMESPACE, namespace),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// onResult handler\nconst setupOnResult = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_RESULT_PROP_NAME, function(resultCallback) {\n if (isFunc(resultCallback)) {\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, resultCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// we do need to add the send prop back because it's the only way to deal with\n// bi-directional data stream\nconst setupOnMessage = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_MESSAGE_PROP_NAME, function(messageCallback) {\n // we expect this to be a function\n if (isFunc(messageCallback)) {\n // did that add to the callback\n let onMessageCallback = (args) => {\n respondHandler(args, messageCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n // register the handler for this message event\n ee.$only(createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME), onMessageCallback)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// add an ON_ERROR_PROP_NAME handler\nconst setupOnError = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_ERROR_PROP_NAME, function(resolverErrorHandler) {\n if (isFunc(resolverErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n ee.$only(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), resolverErrorHandler)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n/**\n * Add extra property to the resolver\n * @param {string} namespace where this belongs\n * @param {string} resolverName name as event name\n * @param {object} params from contract\n * @param {function} fn resolver function\n * @param {object} ee EventEmitter\n * @param {boolean} useCallbackStyle new callback style\n * @return {function} resolver\n */\nexport function setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle) {\n // also need to setup a getter to get back the namespace of this resolver\n let args = [setupNamespace]\n useCallbackStyle ? args.push(setupCallbackApi) : args.push(setupOnResult, setupOnMessage, setupOnError)\n args.push(setupSend)\n // get the executor\n const executor = Reflect.apply(chainFns, null, args)\n\n return Reflect.apply(executor, null, [fn, ee, namespace, resolverName, params, useCallbackStyle])\n}\n","// put all the resolver related methods here to make it more clear\n\n// this will be a mini client server architect\n// The reason is when the enableAuth setup - the private route\n// might not be validated, but we need the callable point is ready\n// therefore this part will always take the contract and generate\n// callable api for the developer to setup their front end\n// the only thing is - when they call they might get an error or\n// NOT_LOGIN_IN and they can react to this error accordingly\nimport { JsonqlError, JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n ERROR_PROP_NAME,\n LOGIN_PROP_NAME,\n READY_PROP_NAME,\n ON_ERROR_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n ON_READY_PROP_NAME\n} from 'jsonql-constants'\nimport { actionCall } from './action-call'\nimport {\n createEvt,\n toArray,\n injectToFn,\n objDefineProps,\n chainFns,\n isString,\n isFunc,\n isObjectHasKey\n} from '../utils'\nimport { CB_FN_NAME } from '../options/constants'\n\n/**\n * create the actual function to send message to server\n * @param {object} ee EventEmitter instance\n * @param {string} namespace this resolver end point\n * @param {string} resolverName name of resolver as event name\n * @param {object} params from contract\n * @param {boolean} useCallbackStyle on style or not\n * @return {function} resolver\n */\nexport function createResolver(ee, namespace, resolverName, params, useCallbackStyle) {\n // note we pass the new withResult=true option\n return function(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => actionCall(ee, namespace, resolverName, useCallbackStyle, _args))\n .catch(finalCatch)\n }\n}\n\n/**\n * The problem is the namespace can have more than one\n * and we only have on onError message\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @param {boolean} useCallbackStyle use cb or not\n * @return {object} obj with onError prop\n */\nexport function createNamespaceErrorHandler(obj, ee, nspSet) {\n // using the onError as name\n // @TODO we should follow the convention earlier\n // make this a setter for the obj itself\n return objDefineProps(obj, ON_ERROR_PROP_NAME, function namespaceErrorCallbackHandler(namespaceErrorHandler) {\n if (isFunc(namespaceErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n for (let namespace in nspSet) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ON_ERROR_PROP_NAME), namespaceErrorHandler)\n }\n }\n })\n}\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @return {object} obj with onReady prop\n */\nexport function createOnReadyhandler(obj, ee, nspSet) {\n return objDefineProps(obj, ON_READY_PROP_NAME, function onReadyCallbackHandler(onReadyCallback) {\n if (isFunc(onReadyCallback)) {\n // reduce it down to just one flat level\n ee.$on(ON_READY_PROP_NAME, onReadyCallback)\n }\n })\n}\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * Plus this will check if it's the private namespace that fired the event\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} opts configuration\n * @return {object} obj with onLogin prop\n */\nexport function createOnLoginhandler(obj, ee, opts) {\n if (opts.enableAuth) {\n return objDefineProps(obj, ON_LOGIN_PROP_NAME, function onLoginCallbackHandler(onLoginCallback) {\n if (isFunc(onLoginCallback)) {\n // only one callback can registered with it, TBC\n ee.$only(ON_LOGIN_PROP_NAME, onLoginCallback)\n }\n })\n }\n // just skip it\n return obj\n}\n\n/**\n * when useCallbackStyle=true use this instead of the above method\n * @param {object} obj the base object to attach to\n * @param {object} ee EventEmitter\n * @param {object} nspSet the map\n * @param {object} opts configuration\n * @return {object} obj\n */\nexport function createCallbackHandler(obj, ee, nspSet, opts) {\n return injectToFn(obj, CB_FN_NAME, function onHandler(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch (evtName) {\n case ERROR_PROP_NAME:\n for (let namespace in nspSet) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ERROR_PROP_NAME), callback)\n }\n break;\n case LOGIN_PROP_NAME:\n ee.$only(LOGIN_PROP_NAME, callback)\n break;\n case READY_PROP_NAME:\n ee.$on(READY_PROP_NAME, callback)\n break;\n default:\n ee.$trigger(ERROR_PROP_NAME, new JsonqlError(CB_FN_NAME, `Unknown event name ${evtName}!`))\n }\n }\n // @TODO need to issue another error here!\n })\n}\n","// take out from the resolver-methods\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { injectToFn, chainFns, isString } from '../utils'\n\n/**\n * @TODO this is now become unnecessary because the login is a slave to the\n * http-client - but keep this for now and see what we want to do with it later\n * break out from createAuthMethods to allow chaining call\n * @param {object} obj the main client object\n * @param {object} ee event emitter\n * @param {object} opts configuration\n * @return {array} modified input\n */\nconst setupLoginHandler = (obj, ee, opts) => [\n injectToFn(obj, opts.loginHandlerName, function loginHandler(token) {\n if (token && isString(token)) {\n return ee.$trigger(LOGIN_EVENT_NAME, [token])\n }\n // should trigger a global error instead @TODO\n throw new JsonqlValidationError(opts.loginHandlerName, `Unexpected token ${token}`)\n }),\n ee,\n opts\n]\n\n/**\n * break out from createAuthMethods to allow chaining call - final in chain\n * @param {object} obj the main client object\n * @param {object} ee event emitter\n * @param {object} opts configuration\n * @return {object} the modified obj\n */\nconst setupLogoutHandler = (obj, ee, opts) => (\n injectToFn(obj, opts.logoutHandlerName, function logoutHandler(...args) {\n ee.$trigger(LOGOUT_EVENT_NAME, args)\n })\n)\n\n/**\n * Create auth related methods\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} opts configuration\n * @return {object} obj with auth methods if any\n */\nexport function createAuthMethods(obj, ee, opts) {\n if (opts.enableAuth) {\n return chainFns(setupLoginHandler, setupLogoutHandler)(obj, ee, opts)\n }\n return obj;\n}\n","// resolvers generator\n// we change the interface to return promise from v1.0.3\n// this way we make sure the obj return is correct and timely\nimport { setupResolver } from './setup-resolver'\nimport {\n createResolver,\n createNamespaceErrorHandler,\n createOnReadyhandler,\n createOnLoginhandler,\n createCallbackHandler\n} from './resolver-methods'\nimport { createAuthMethods } from './setup-auth-methods'\nimport { injectToFn, chainProcessPromises } from '../utils'\n\n/**\n * step one get the obj map with the namespace\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {promise} resolve the obj mapped, and start the chain\n */\nfunction getMappedObj(opts, nspMap, ee) {\n let obj = {};\n // let resolverNames = [];\n const { nspSet } = nspMap;\n const { useCallbackStyle } = opts; // @1.2.1\n for (let namespace in nspSet) {\n let list = nspSet[namespace]\n for (let resolverName in list) {\n // resolverNames.push(resolverName)\n let params = list[resolverName]\n let fn = createResolver(ee, namespace, resolverName, params, useCallbackStyle)\n // this should set as a getter therefore can not be overwrite by accident\n // obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee)\n obj = injectToFn(obj, resolverName, setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle))\n }\n }\n // move this two method down to helpers\n // we want these methods visible in debug or console.log\n obj.devHelpers = {\n // this is a helper method for the developer to know the namespace inside\n getNsp: () => Object.keys(nspSet),\n // simple get version trick\n getVer: () => opts.version || 'NOT SET'\n // not really necessary because the dev can query the contract\n // getResolverNames: () => resolverNames\n }\n // resolve the obj to start the chain\n // chain the result to allow the chain processing\n return Promise.resolve(obj)\n}\n\n/**\n * prepare the methods\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {object} of resolvers\n * @public\n */\nexport function generator(opts, nspMap, ee) {\n const { nspSet } = nspMap\n const { useCallbackStyle } = opts;\n let args = [getMappedObj]\n if (useCallbackStyle) {\n args.push(obj => createCallbackHandler(obj, ee, nspSet, opts))\n } else {\n args.push(\n obj1 => createNamespaceErrorHandler(obj1, ee, nspSet),\n obj2 => createOnReadyhandler(obj2, ee, nspSet),\n obj3 => createOnLoginhandler(obj3, ee, opts),\n )\n }\n args.push(obj4 => createAuthMethods(obj4, ee, opts))\n // run it\n const executor = Reflect.apply(chainProcessPromises, null, args)\n return executor(opts, nspMap, ee)\n\n /*\n return getMappedObj(opts, nspMap, ee)\n // add error handler\n .then(obj1 => createNamespaceErrorHandler(obj1, ee, nspSet))\n // add onReady handler\n .then(obj2 => createOnReadyhandler(obj2, ee, nspSet))\n // add onLogin handler -- this is optional\n .then(obj3 => createOnLoginhandler(obj3, ee, opts))\n // Auth related methods -- this is optional\n .then(obj4 => createAuthMethods(obj4, ee, opts))\n */\n}\n","// create options\nimport { checkConfigAsync, isNotEmpty } from 'jsonql-params-validator'\nimport { CHECKED_KEY } from 'jsonql-constants'\n// import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors'\n// this should be remove - we have to make it generic\nimport { defaultOptions } from './defaults'\nimport { fixWss, getHostName, objHasProp } from '../utils'\n\n// constant props\nconst defaultConstProps = {\n eventEmitter: null,\n // we unify the two different client into one now\n // only expect different parameter\n nspClient: null,\n nspAuthClient: null,\n // contructed path\n wssPath: ''\n}\n// for export\nconst jsonqlWsDefaultOptions = defaultOptions\nconst jsonqlWsDefaultConstProps = defaultConstProps\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config\n * @param {object} dOpt\n * @param {object} cProps\n * @return {promise} resolve to the checked opitons\n */\nfunction checkOptionsWrapper(config, dOpt, cProps) {\n if (objHasProp(config, CHECKED_KEY)) {\n return Promise.resolve(config)\n }\n return checkConfigAsync(config, dOpt, cProps)\n}\n\n/**\n * check the configuration\n * @param {object} config user supplied configuration\n * @param {object} constProps developer supplied configuration\n * @return {object} after checked\n */\nfunction checkOptions(config, constProps) {\n return checkOptionsWrapper(config, defaultOptions, Object.assign(defaultConstProps, constProps))\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // debug('CONFIGURATION OPTIONS', opts)\n return opts;\n })\n}\n\nexport {\n jsonqlWsDefaultConstProps,\n jsonqlWsDefaultOptions,\n checkOptions\n}\n","// the top level API\n// The goal is to create a generic method that will able to handle\n// any kind of clients\n// import { injectToFn } from 'jsonql-utils'\nimport { generator } from './core'\nimport { checkOptions } from './options'\nimport { ee, processContract } from './utils'\n\n/**\n * The main interface which will generate the socket clients and map all events\n * @param {object} socketClientResolver this is the one method export by various clients\n * @param {object} [constProps={}] add this to supply the constProps from the downstream client\n * @return {object} the wsClient instance with all the available API\n */\nexport default function wsClient(socketClientResolver, constProps = {}) {\n const { log } = constProps // 1.3.9 if we pass a log method here then we use this\n const logger = log && typeof log === 'function' ? log : () => {}\n // we need to inject property to this client later\n // therefore we need to do it this way\n return (opts) => {\n const { eventEmitter } = opts; // pass from the next level up\n return checkOptions(opts, constProps)\n .then(opts => {\n opts.logger = logger\n return opts;\n })\n .then(opts => ({\n opts,\n nspMap: processContract(opts),\n ee: eventEmitter || new ee(logger)\n }))\n .then(\n ({opts, nspMap, ee}) => socketClientResolver(opts, nspMap, ee)\n )\n .then(\n ({opts, nspMap, ee}) => generator(opts, nspMap, ee)\n )\n .catch(err => {\n console.error(`jsonql-ws-client init error`, err)\n })\n }\n}\n","// where all the base options are\n// create options\nimport { JS_WS_NAME } from 'jsonql-constants'\n// constant props\nconst constProps = {\n version: '__PLACEHOLDER__', // will get replace\n serverType: JS_WS_NAME\n}\n\nexport { constProps }\n","// pass the different type of ws to generate the client\nimport { TOKEN_PARAM_NAME } from 'jsonql-constants'\n/**\n * WebSocket is strict about the path, therefore we need to make sure before it goes in\n * @param {string} url input url\n * @return {string} url with correct path name\n */\nconst fixWss = url => {\n const uri = url.toLowerCase()\n if (uri.indexOf('http') > -1) {\n if (uri.indexOf('https') > -1) {\n return uri.replace('https', 'wss')\n }\n return uri.replace('http', 'ws')\n }\n return uri;\n}\n\n/**\n * The bug was in the wsOptions where ws doesn't need it but socket.io do\n * therefore the object was pass as second parameter!\n * @param {object} WebSocket the client or node version of ws\n * @param {boolean} auth if it's auth then 3 param or just one\n */\nexport function createWsClient(WebSocket, auth = false) {\n if (auth === false) {\n return function createWsClientHandler(url) {\n return new WebSocket(fixWss(url))\n }\n }\n\n /**\n * Create a client with auth token\n * @param {string} url start with ws:// @TODO check this?\n * @param {string} token the jwt token\n * @return {object} ws instance\n */\n return function createWsAuthClientHandler(url, token) {\n const ws_url = fixWss(url)\n // console.log('what happen here?', url, ws_url, token)\n const uri = token && typeof token === 'string' ? `${ws_url}?${TOKEN_PARAM_NAME}=${token}` : ws_url;\n try {\n return new WebSocket(uri)\n } catch(e) {\n console.error('WebSocket Connection Error', e)\n return false;\n }\n }\n}\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME;\nconst WS = JS_WS_NAME;\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!';\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!';\n\nconst MISSING_PROP_ERR = 'Missing property in contract!';\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!';\n\nconst EMIT_EVT = EMIT_REPLY_TYPE;\n\nconst NAMESPACE_KEY = 'namespaceMap';\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!';\n\nconst NOT_ALLOW_OP = 'This operation is not allow!';\n\nconst MY_NAMESPACE = 'myNamespace'\n\nconst CB_FN_NAME = 'on'\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME\n}\n","// since both the ws and io version are\n// pre-defined in the client-generator\n// and this one will have the same parameters\n// and the callback is identical\n\n/**\n * wrapper method to create a nsp without login\n * @param {string|boolean} namespace namespace url could be false\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspClient(namespace, opts) {\n const { hostname, wssPath, wsOptions, nspClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n return nspClient(url, wsOptions)\n}\n\n/**\n * wrapper method to create a nsp with token auth\n * @param {string} namespace namespace url\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspAuthClient(namespace, opts) {\n const { hostname, wssPath, token, wsOptions, nspAuthClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n if (token && typeof token !== 'string') {\n throw new Error(`Expect token to be string, but got ${token}`)\n }\n return nspAuthClient(url, token, wsOptions)\n}\n\nexport {\n createNspClient,\n createNspAuthClient\n}\n","// group all the small functions here\nimport { JS_WS_SOCKET_IO_NAME, JS_WS_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/src/generic'\n\n// we shouldn't do this anymore\nexport const fixWss = (url, serverType) => {\n // ws only allow ws:// path\n if (serverType === JS_WS_NAME) {\n return url.replace('http://', 'ws://')\n }\n return url;\n}\n\n/**\n * get a stock host name from browser\n */\nexport const getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n throw new JsonqlValidationError(e)\n }\n}\n\n/**\n * Unbind the event\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nexport const clearMainEmitEvt = (ee, namespace) => {\n let nsps = toArray(namespace)\n nsps.forEach(n => {\n ee.$off(createEvt(n, EMIT_REPLY_TYPE))\n })\n}\n\n/**\n * @param {object} nsps namespace as key\n * @param {string} type of server\n */\nexport const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => {\n try {\n // @TODO need to figure out a better way here?\n const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate';\n for (let namespace in nsps) {\n let nsp = nsps[namespace]\n if (nsp && nsp[method]) {\n Reflect.apply(nsp[method], null, [])\n }\n }\n } catch(e) {\n // socket.io throw a this.destroy of undefined?\n console.error('Disconnect call failed', e)\n }\n}\n","// this use by client-event-handler\nimport { ON_ERROR_PROP_NAME, ERROR_PROP_NAME } from 'jsonql-constants'\nimport { createEvt } from '../utils'\n\n/**\n * trigger errors on all the namespace onError handler\n * @param {object} ee Event Emitter\n * @param {array} namespaces nsps string\n * @param {string} message optional\n * @param {object} opts configuration\n * @return {void}\n */\nexport function triggerNamespacesOnError(ee, namespaces, message, opts = {}) {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n namespaces.forEach( namespace => {\n ee.$call(createEvt(namespace, ERROR_SUBFIX), [{ message, namespace }])\n })\n}\n","// This is share between different clients so we export it\n// @TODO port what is in the ws-main-handler\n// because all the client side call are via the ee\n// and that makes it re-usable between different client setup\nimport {\n ERROR_PROP_NAME,\n RESULT_PROP_NAME,\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n NOT_LOGIN_ERR_MSG,\n ON_ERROR_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n} from 'jsonql-constants'\nimport { EMIT_EVT, SOCKET_IO, WS } from '../options/constants'\nimport { createEvt, clearMainEmitEvt } from '../utils'\nimport { triggerNamespacesOnError } from './trigger-namespaces-on-error'\n\n/**\n * A fake ee handler\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nconst notLoginWsHandler = (namespace, ee, opts) => {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function notLoginHandlerCallback(resolverName, args) {\n opts.logger('noLoginHandler hijack the ws call', namespace, resolverName, args)\n let error = {\n message: NOT_LOGIN_ERR_MSG\n }\n // It should just throw error here and should not call the result\n // because that's channel for handling normal event not the fake one\n ee.$call(createEvt(namespace, resolverName, ERROR_SUBFIX), [error])\n // also trigger the result handler, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, RESULT_SUBFIX), [{ error }])\n }\n )\n}\n\n/**\n * get the private namespace\n * @param {array} namespaces array\n * @return {*} string on success\n */\nconst getPrivateNamespace = (namespaces) => (\n namespaces.length > 1 ? namespaces[0] : false\n)\n\n/**\n * centralize all the comm in one place\n * @param {object} opts configuration\n * @param {array} namespaces namespace(s)\n * @param {object} ee Event Emitter instance\n * @param {function} bindWsHandler binding the ee to ws --> this is the core bit\n * @param {array} namespaces array of namespace available\n * @param {object} nsps namespaced nsp\n * @return {void} nothing\n */\nexport function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) {\n // @1.1.3 add isPrivate prop to id which namespace is the private nsp\n // then we can use this prop to determine if we need to fire the ON_LOGIN_PROP_NAME event\n const privateNamespace = getPrivateNamespace(namespaces)\n let isPrivate = false;\n // loop\n // @BUG for io this has to be in order the one with auth need to get call first\n // The order of login is very import we need to run a waterfall here to make sure\n // one is execute then the other\n namespaces.forEach(namespace => {\n isPrivate = privateNamespace === namespace;\n if (nsps[namespace]) {\n opts.logger('call bindWsHandler', isPrivate, namespace)\n let args = [namespace, nsps[namespace], ee, isPrivate, opts]\n if (opts.serverType === SOCKET_IO) {\n let { nspSet } = nspMap;\n args.push(nspSet[namespace])\n }\n Reflect.apply(bindWsHandler, null, args)\n } else {\n // a dummy placeholder\n notLoginWsHandler(namespace, ee, opts)\n }\n })\n // this will be available regardless enableAuth\n // because the server can log the client out\n ee.$on(LOGOUT_EVENT_NAME, function logoutEvtHandler() {\n opts.logger('LOGOUT_EVENT_NAME')\n // disconnect(nsps, opts.serverType)\n // we need to issue error to all the namespace onError handler\n triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME)\n // rebind all of the handler to the fake one\n namespaces.forEach( namespace => {\n clearMainEmitEvt(ee, namespace)\n // clear out the nsp\n nsps[namespace] = false;\n // add a NOT LOGIN error if call\n notLoginWsHandler(namespace, ee, opts)\n })\n })\n}\n","// take the ws reply data for use\nimport { WS_EVT_NAME, WS_DATA_NAME, WS_REPLY_TYPE } from 'jsonql-constants'\nimport { isString } from 'jsonql-params-validator'\nimport { isObjectHasKey } from 'jsonql-utils/module'\nimport { JsonqlError, clientErrorsHandler } from 'jsonql-errors'\n\nconst keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ]\n\n/**\n * @param {object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nconst isWsReply = payload => {\n const { data } = payload;\n if (data) {\n let result = keys.filter(key => isObjectHasKey(data, key))\n return (result.length === keys.length) ? data : false;\n }\n return false;\n}\n\n/**\n * @param {object} payload This is the entire ws Event Object\n * @return {object} false on failed\n */\nconst extractWsPayload = payload => {\n const { data } = payload;\n let json = isString(data) ? JSON.parse(data) : data;\n // debugFn('extractWsPayload', json)\n let fdata;\n if ((fdata = isWsReply(json)) !== false) {\n return {\n resolverName: fdata[WS_EVT_NAME],\n data: fdata[WS_DATA_NAME],\n type: fdata[WS_REPLY_TYPE]\n };\n }\n throw new JsonqlError('payload can not be decoded', payload)\n}\n// export it\nexport default extractWsPayload\n","// the WebSocket main handler\nimport {\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n ACKNOWLEDGE_REPLY_TYPE,\n EMIT_REPLY_TYPE,\n ERROR_TYPE,\n\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_READY_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME,\n READY_PROP_NAME,\n LOGIN_PROP_NAME\n} from 'jsonql-constants'\nimport { createQueryStr, createEvt } from 'jsonql-utils/module'\nimport extractWsPayload from './extract-ws-payload'\nconst dummyLogger = () => {}\n/**\n * under extremely circumstances we might not even have a resolverName, then\n * we issue a global error for the developer to catch it\n * @param {object} ee event emitter\n * @param {string} namespace nsp\n * @param {string} resolverName resolver\n * @param {object} json decoded payload or error object\n * @param {string} ERROR_EVT_NAME the error event name\n * @return {undefined} nothing return\n */\nconst errorTypeHandler = (ee, namespace, resolverName, json, ERROR_EVT_NAME) => {\n let evt = [namespace]\n if (resolverName) {\n evt.push(resolverName)\n }\n evt.push(ERROR_EVT_NAME)\n let evtName = Reflect.apply(createEvt, null, evt)\n // test if there is a data field\n let payload = json.data || json;\n ee.$trigger(evtName, [payload])\n}\n\n/**\n * Binding the even to socket normally\n * @param {string} namespace\n * @param {object} ws the nsp\n * @param {object} ee EventEmitter\n * @param {boolean} isPrivate to id if this namespace is private or not\n * @param {object} opts configuration\n * @return {object} promise resolve after the onopen event\n */\nexport function wsMainHandler(namespace, ws, ee, isPrivate, opts) {\n\n const debugFn = opts.log || dummyLogger\n\n const { useCallbackStyle } = opts;\n const READY_EVT_NAME = useCallbackStyle ? READY_PROP_NAME : ON_READY_PROP_NAME;\n const LOGIN_EVT_NAME = useCallbackStyle ? LOGIN_PROP_NAME : ON_LOGIN_PROP_NAME;\n const MESSAGE_EVT_NAME = useCallbackStyle ? MESSAGE_PROP_NAME : ON_MESSAGE_PROP_NAME;\n const RESULT_EVT_NAME = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n const ERROR_EVT_NAME = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n // connection open\n ws.onopen = function onOpenCallback() {\n debugFn('ws.onopen listened')\n // we just call the onReady\n ee.$call(READY_EVT_NAME, namespace)\n // need an extra parameter here to id the private nsp\n if (isPrivate) {\n console.log(`isPrivate and fire the ${LOGIN_EVT_NAME}`)\n ee.$call(LOGIN_EVT_NAME, namespace)\n }\n // add listener only after the open is called\n ee.$only(\n createEvt(namespace, EMIT_REPLY_TYPE),\n function wsMainOnEvtHandler(resolverName, args) {\n debugFn('calling server', resolverName, args)\n ws.send(\n createQueryStr(resolverName, args)\n )\n }\n )\n }\n\n // reply\n // If we change it to the event callback style\n // then the payload will just be the payload and fucks up the extractWsPayload call @TODO\n ws.onmessage = function onMessageCallback(payload) {\n // console.log(`on.message`, typeof payload, payload)\n try {\n const json = extractWsPayload(payload)\n const { resolverName, type } = json;\n debugFn('Hear from server', type, json)\n switch (type) {\n case EMIT_REPLY_TYPE:\n let e1 = createEvt(namespace, resolverName, MESSAGE_EVT_NAME)\n let r = ee.$trigger(e1, [json])\n debugFn(`EMIT_REPLY_TYPE`, e1, r)\n break;\n case ACKNOWLEDGE_REPLY_TYPE:\n let e2 = createEvt(namespace, resolverName, RESULT_EVT_NAME)\n let x = ee.$trigger(e2, [json])\n // debugFn(`ACKNOWLEDGE_REPLY_TYPE`, e2, json)\n break;\n case ERROR_TYPE:\n // this is handled error and we won't throw it\n // we need to extract the error from json\n debugFn(`ERROR_TYPE`)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\n break;\n // @TODO there should be an error type instead of roll into the other two types? TBC\n default:\n // if this happen then we should throw it and halt the operation all together\n debugFn('Unhandled event!', json)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\n // let error = {error: {'message': 'Unhandled event!', type}};\n // ee.$trigger(createEvt(namespace, resolverName, ON_RESULT_PROP_NAME), [error])\n }\n } catch(e) {\n console.error(`ws.onmessage error`, e)\n errorTypeHandler(ee, namespace, false, e, ERROR_EVT_NAME)\n }\n }\n // when the server close the connection\n ws.onclose = function onCloseCallback() {\n debugFn('ws.onclose callback')\n // @TODO what to do with this\n // ee.$trigger(LOGOUT_EVENT_NAME, [namespace])\n }\n // listen to the LOGOUT_EVENT_NAME\n ee.$on(LOGOUT_EVENT_NAME, function closeEvtHandler() {\n try {\n debugFn('terminate ws connection')\n ws.terminate()\n } catch(e) {\n console.error('ws.terminate error', e)\n }\n })\n}\n","// actually binding the event client to the socket client\nimport { getNameFromPayload, getNamespaceInOrder } from 'jsonql-utils/module'\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, JS_WS_NAME } from 'jsonql-constants'\nimport {\n createNspClient,\n createNspAuthClient,\n clientEventHandler,\n triggerNamespacesOnError,\n clearMainEmitEvt,\n disconnect\n} from 'jsonql-ws-client/share'\nimport { wsMainHandler } from './ws-main-handler'\n\n/**\n * Because the nsps can be throw away so it doesn't matter the scope\n * this will get reuse again\n * @param {object} opts configuration\n * @param {object} nspMap from contract\n * @param {string|null} token whether we have the token at run time\n * @return {object} nsps namespace with namespace as key\n */\nconst createNsps = function(opts, nspMap, token) {\n let { nspSet, publicNamespace } = nspMap;\n let login = false;\n let namespaces = [];\n let nsps = {};\n // first we need to binding all the events handler\n if (opts.enableAuth) { // && opts.useJwt\n login = true; // just saying we need to listen to login event\n namespaces = getNamespaceInOrder(nspSet, publicNamespace)\n nsps = namespaces.map((namespace, i) => {\n if (i === 0) {\n if (token) {\n opts.token = token;\n // console.log('create createNspAuthClient at run time', opts)\n return {[namespace]: createNspAuthClient(namespace, opts)}\n }\n return {[namespace]: false}\n }\n return {[namespace]: createNspClient(namespace, opts)}\n }).reduce((first, next) => Object.assign(first, next), {})\n } else {\n let namespace = getNameFromPayload(nspSet)\n namespaces.push(namespace)\n // standard without login\n // the stock version should not have a namespace\n nsps[namespace] = createNspClient(false, opts)\n }\n // return\n return { nsps, namespaces, login }\n}\n\n/**\n * create a ws client\n * @param {object} opts configuration\n * @param {object} nspMap namespace with resolvers\n * @param {object} ee EventEmitter to pass through\n * @return {object} what comes in what goes out\n */\nexport function createClient(opts, nspMap, ee) {\n // arguments that don't change\n const args = [opts, nspMap, ee, wsMainHandler]\n // now create the nsps\n const { token } = opts;\n const { nsps, namespaces, login } = createNsps(opts, nspMap, token)\n // binding the listeners - and it will listen to LOGOUT event\n // to unbind itself, and the above call will bind it again\n Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps]))\n // setup listener\n if (login) {\n ee.$only(LOGIN_EVENT_NAME, function loginEventHandler(tokenLater) {\n // debugFn(`LOGIN_EVENT_NAME called with token:`, tokenLater)\n // @BUG this keep causing an \"Disconnect call failed TypeError: Cannot read property 'readyState' of null\"\n // I think that is because it's not login then it can not be disconnect\n // how do we track this state globally\n // disconnect(nsps, JS_WS_NAME)\n\n // @TODO should we trigger error on this one?\n // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME)\n clearMainEmitEvt(ee, namespaces)\n // console.log('LOGIN_EVENT_NAME', token)\n const newNsps = createNsps(opts, nspMap, tokenLater)\n // rebind it\n Reflect.apply(\n clientEventHandler,\n null,\n args.concat([newNsps.namespaces, newNsps.nsps])\n )\n })\n }\n // return what input\n return { opts, nspMap, ee }\n}\n","// share method to create the wsClientResolver\n\nimport { createWsClient } from './create-ws-client'\nimport { createClient } from './create-client'\n\n/**\n * combine the create client resolver\n * @param {object} ws the different WebSocket module\n * @return {function} the wsClientResolver\n */\nexport default function createClientResolver(ws) {\n const client = createWsClient(ws)\n const authClient = createWsClient(ws, true)\n /**\n * wsClientResolver\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\n return function(opts, nspMap, ee) {\n opts.nspClient = client;\n opts.nspAuthClient = authClient;\n\n // console.log(`contract`, opts.contract)\n\n return createClient(opts, nspMap, ee)\n }\n}\n","// this will be the news style interface that will pass to the jsonql-ws-client\n// then return a function for accepting an opts to generate the final\n// client api\nimport WebSocket from './core/ws'\nimport createClientResolver from './core/create-client-resolver'\n\n/**\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\nexport default createClientResolver(WebSocket)\n","// this is the module entry point for ES6 for client\n// the main will point to the node.js server side setup\nimport { jsonqlWsClientCore } from 'jsonql-ws-client-core'\n\nimport { constProps } from './src/options'\nimport wsClientResolver from './src/ws-client-resolver'\n\n// export back the function and that's it\nexport default jsonqlWsClientCore(wsClientResolver, constProps)\n","// create options\nimport { checkConfigAsync, isNotEmpty } from 'jsonql-params-validator'\nimport { CHECKED_KEY } from 'jsonql-constants'\n// import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors'\n// this should be remove - we have to make it generic\nimport { defaultOptions } from './defaults'\nimport { fixWss, getHostName, objHasProp } from '../utils'\n\n// constant props\nconst defaultConstProps = {\n eventEmitter: null,\n // we unify the two different client into one now\n // only expect different parameter\n nspClient: null,\n nspAuthClient: null,\n // contructed path\n wssPath: ''\n}\n// for export\nconst jsonqlWsDefaultOptions = defaultOptions\nconst jsonqlWsDefaultConstProps = defaultConstProps\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config\n * @param {object} dOpt\n * @param {object} cProps\n * @return {promise} resolve to the checked opitons\n */\nfunction checkOptionsWrapper(config, dOpt, cProps) {\n if (objHasProp(config, CHECKED_KEY)) {\n return Promise.resolve(config)\n }\n return checkConfigAsync(config, dOpt, cProps)\n}\n\n/**\n * check the configuration\n * @param {object} config user supplied configuration\n * @param {object} constProps developer supplied configuration\n * @return {object} after checked\n */\nfunction checkOptions(config, constProps) {\n return checkOptionsWrapper(config, defaultOptions, Object.assign(defaultConstProps, constProps))\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // debug('CONFIGURATION OPTIONS', opts)\n return opts;\n })\n}\n\nexport {\n jsonqlWsDefaultConstProps,\n jsonqlWsDefaultOptions,\n checkOptions\n}\n","// export the required options here to merge with the http client to do a combine check\nimport { jsonqlWsDefaultConstProps, jsonqlWsDefaultOptions } from 'jsonql-ws-client'\nimport { constProps as localConstProps } from './src/options'\n\nconst defaultOptions = jsonqlWsDefaultOptions\nconst constProps = Object.assign(jsonqlWsDefaultConstProps, localConstProps)\n\n\nexport {\n defaultOptions,\n constProps\n}\n","// this is the jsonql client with ws\n// use like import jsonqlClient from '@jsonql/client/ws'\nimport { jsonqlClientModule } from 'jsonql-client/module'\nimport { getPreConfigCheck } from 'jsonql-client/opt'\nimport jsonqlWsClient from '@jsonql/ws'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport {\n defaultOptions as wsDefaultOptions,\n constProps as wsConstProps\n} from '@jsonql/ws/opt'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-client:test:ws')\n// debugFn(jsonqlWsClient)\n\n/**\n * @param {object} Fly the fly module\n * @param {object} [config={}] developer supply options\n * @return {object} the jsonql browser client with ws socket\n * @public\n */\nexport default function createJsonqlHttpWsClient(Fly, config = {}) {\n // @NOTE it return a function to accept the config\n const fn = getPreConfigCheck(wsDefaultOptions, wsConstProps)\n const opts = fn(config)\n opts.socketClient = jsonqlWsClient\n // init the client\n return jsonqlClientModule(Fly, opts)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;ECAA;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"jsonql-client-ws.debug.js","sources":["../../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/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-utils/src/contract.js","../../node_modules/nb-event-service/src/hash-code.js","../../node_modules/jsonql-client/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/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","../../node_modules/jsonql-utils/src/timestamp.js","../../node_modules/store/plugins/defaults.js","../../node_modules/jsonql-client/src/stores/local-store.js","../../node_modules/jsonql-client/src/stores/session-store.js","../../node_modules/jsonql-client/src/stores/index.js","../../node_modules/jsonql-utils/src/params-api.js","../../node_modules/jsonql-utils/src/results.js","../../node_modules/jsonql-client/src/base/store-cls.js","../../node_modules/jsonql-client/src/base/http-cls.js","../../node_modules/jsonql-client/src/base/contract-cls.js","../../node_modules/jsonql-client/src/base/auth-cls.js","../../node_modules/jsonql-client/src/base/base-cls.js","../../node_modules/jsonql-client/src/base/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","../../node_modules/jsonql-client/src/ee.js","../../node_modules/jsonql-client/src/core/methods-generator.js","../../node_modules/jsonql-client/src/core/jsonql-api-generator.js","../../node_modules/jsonql-client/src/options/base-options.js","../../node_modules/jsonql-client/src/options/check-options-async.js","../../node_modules/jsonql-client/src/options/index.js","../../node_modules/jsonql-client/module.js","../../node_modules/jsonql-utils/src/chain-promises.js","../../node_modules/jsonql-utils/src/pre-config-check.js","../../node_modules/jsonql-client/opt.js","../../node_modules/jsonql-ws-client-core/src/options/constants.js","../../node_modules/jsonql-ws-client-core/src/utils/ee.js","../../node_modules/jsonql-ws-client-core/src/utils/process-contract.js","../../node_modules/jsonql-ws-client-core/src/utils/helpers.js","../../node_modules/jsonql-ws-client-core/src/core/respond-handler.js","../../node_modules/jsonql-ws-client-core/src/core/action-call.js","../../node_modules/jsonql-ws-client-core/src/core/setup-callback-api.js","../../node_modules/jsonql-ws-client-core/src/core/setup-resolver.js","../../node_modules/jsonql-ws-client-core/src/core/resolver-methods.js","../../node_modules/jsonql-ws-client-core/src/core/setup-auth-methods.js","../../node_modules/jsonql-ws-client-core/src/core/generator.js","../../node_modules/jsonql-ws-client-core/src/options/index.js","../../node_modules/jsonql-ws-client-core/src/api.js","../../node_modules/@jsonql/ws/src/options/index.js","../../node_modules/@jsonql/ws/src/core/create-ws-client.js","../../node_modules/jsonql-ws-client/src/options/constants.js","../../node_modules/jsonql-ws-client/src/share/create-nsp-client.js","../../node_modules/jsonql-ws-client/src/utils/helpers.js","../../node_modules/jsonql-ws-client/src/share/trigger-namespaces-on-error.js","../../node_modules/jsonql-ws-client/src/share/client-event-handler.js","../../node_modules/@jsonql/ws/src/core/extract-ws-payload.js","../../node_modules/@jsonql/ws/src/core/ws-main-handler.js","../../node_modules/@jsonql/ws/src/core/create-client.js","../../node_modules/@jsonql/ws/src/core/create-client-resolver.js","../../node_modules/@jsonql/ws/src/ws-client-resolver.js","../../node_modules/@jsonql/ws/index.js","../../node_modules/jsonql-ws-client/src/options/index.js","../../node_modules/@jsonql/ws/opt.js","../../ws.js"],"sourcesContent":["/**\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","/**\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","// 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","// 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 * construct the actual end user method, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfigAsync = function(validateSync) {\n /**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n/**\n * copy of above but it's sync, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n getCheckConfigAsync,\n getCheckConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\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// construct the final output 1.5.2\nexport const checkConfigAsync = jsonqlOptions.getCheckConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.getCheckConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/options/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 // cache\n this.__userdata__ = null;\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.__userdata__ = this.decoder(token)\n this.jsonqlUserdata = this.__userdata__\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 \n return { token, userdata: this.__userdata__ }\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","// 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","// 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, userdata}) => {\n ee.$trigger(LOGIN_NAME, token)\n // 1.5.6 return the decoded userdata instead\n return userdata\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) { // this one has a server side logout\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 { // this is only for client side logout\n // @TODO should allow to login particular profile\n auth[logoutHandlerName] = function logoutHandlerFn(profileId = null) {\n jsonqlInstance.postLogoutAction(KEY_WORD, profileId)\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 // 1.5.2 change it to a getter to return a method, pass a name to id which one is which\n client.getLogger = (name) => (...args) => Reflect.apply(jsonqlInstance.log, jsonqlInstance, [name].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","// new module interface for @jsonql/client\n// this will be use with the @jsonql/ws, @jsonql/socketio\nimport { SOCKET_NAME } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\nimport JsonqlBaseClient from './src/base'\nimport getEventEmitter from './src/ee'\nimport generator from './src/core/jsonql-api-generator'\nimport { checkOptionsAsync } from './src/options'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { isObjectHasKey } from 'jsonql-utils/src/generic'\nimport { getContractFromConfig } from './src/utils'\n\n/**\n * Check if the contract has socket field and the socket client is suplied\n * @param {object} client the http client\n * @param {object} contract the json\n * @param {object} config the checked configuration\n * @param {object} socketClient from the original config\n * @return {object} the completed client\n */\nfunction initSocketClient(client, contract, config, socketClient) {\n if (isObjectHasKey(contract, SOCKET_NAME)) {\n if (socketClient) {\n // pass the contract here one more time in case the constProps overwritten it\n config.log = client.getLogger(`jsonql-client:${config.serverType}`)\n config.contract = contract\n config.eventEmitter = client.eventEmitter\n return socketClient(config)\n .then(sc => {\n client[SOCKET_NAME] = sc\n return client\n })\n } else {\n throw new JsonqlError(`initSocketClient`, `socketClient is missing!`)\n }\n }\n return client\n}\n\n/**\n * Main interface for jsonql fetch api\n * @1.4.8 change this to named export to diff this from the other\n * and this is only use with the @jsonql/client to construct the client with ws\n * @param {object} Fly the http engine\n * @param {object} [config={}] configuration\n * @return {object} jsonqlClient\n */\nfunction jsonqlClientModule(fly, config = {}) {\n const { socketClient, debugOn } = config;\n const ee = getEventEmitter(debugOn)\n return checkOptionsAsync(config)\n .then(opts => (\n {\n opts,\n baseClient: new JsonqlBaseClient(fly, opts)\n }\n ))\n // make sure the contract is presented\n .then(({opts, baseClient}) => getContractFromConfig(baseClient, opts.contract)\n .then(contract => (\n {\n opts,\n contract,\n client: generator(baseClient, opts, contract, ee)\n }\n )\n )\n )\n // finally generate the websocket client if any\n .then(({opts, contract, client}) => (\n initSocketClient(client, contract, opts, socketClient)\n ))\n}\n// export it\nexport { jsonqlClientModule }\n","// break it out on its own because\n// it's building from the lodash-es from scratch\n// according to this discussion https://github.com/lodash/lodash/issues/3298\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport merge from 'lodash-es/merge'\n\n/**\n * previously we already make sure the order of the namespaces\n * and attach the auth client to it\n * @param {array} promises array of unresolved promises\n * @param {boolean} asObject if true then merge the result object\n * @return {object} promise resolved with the array of promises resolved results\n */\nexport function chainPromises(promises, asObject = false) {\n return promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResults => (\n currentTask.then(currentResult => (\n asObject === false ? [...chainResults, currentResult] : merge(chainResults, currentResult)\n ))\n ))\n ), Promise.resolve(\n asObject === false ? [] : (isPlainObject(asObject) ? asObject : {})\n ))\n}\n\n\n/**\n * This one return a different result from the chainPromises\n * it will be the same like chainFns that take one promise resolve as the next fn parameter\n * @param {function} initPromise a function that accept param and resolve result\n * @param {array} promises array of function pass that resolve promises\n * @return {promise} resolve the processed result\n */\nexport function chainProcessPromises(initPromise, ...promises) {\n return (...args) => (\n promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResult => (\n currentTask(chainResult)\n )\n )\n ), Reflect.apply(initPromise, null, args))\n )\n}\n","// this will replace the preConfigCheck in jsonql-koa\n// also this will get use in the client as well\n// basically this is just a wrapper method to load everything together\n// and then add the CHECKED_KEY to it\nimport { CHECKED_KEY } from 'jsonql-constants'\n\nimport { chainFns } from './chain-fns'\nimport { timestamp } from './timestamp'\nimport { injectToFn } from './obj-define-props'\n\n/**\n * the rest of the argument will be functions that\n * need to add to the process chain,\n * finally return a function to accept the config\n * @param {object} defaultOptions prepared before hand\n * @param {object} constProps prepare before hand\n * @param {array} fns arguments see description\n * @return {function} to perform the final configuration check\n */\nexport function preConfigCheck(defaultOptions, constProps, ...fns) {\n // should have just add the method to the last\n const finalFn = opt => injectToFn(opt, CHECKED_KEY, timestamp())\n // if there is more than one then chain it otherwise just return the zero idx one\n const fn = Reflect.apply(chainFns, null, fns.concat(finalFn))\n // 0.8.8 add a default property empty object\n return (config = {}) => fn(config, defaultOptions, constProps)\n}\n","// export the options for the pre-check to use\nimport { preConfigCheck } from 'jsonql-utils/module'\nimport { checkConfig } from 'jsonql-params-validator'\nimport merge from 'lodash-es/merge'\n\nimport { appProps, constProps } from './src/options/base-options'\n// just export the function here for use to save repeat coding\n\n/**\n * This will combine the socket client options and merge this one\n * then do a pre-check on both at the same time\n * @param {object} [extraProps = {}]\n * @param {object} [extraConstProps = {}]\n * @return {function} to process the developer options\n */\nexport function getPreConfigCheck(extraProps = {}, extraConstProps = {}) {\n const aProps = merge({}, appProps, extraProps)\n const cProps = merge({}, constProps, extraConstProps)\n\n return preConfigCheck(aProps, cProps, checkConfig)\n}\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME;\nconst WS = JS_WS_NAME;\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!';\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!';\n\nconst MISSING_PROP_ERR = 'Missing property in contract!';\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!';\n\nconst EMIT_EVT = EMIT_REPLY_TYPE;\n\nconst NAMESPACE_KEY = 'namespaceMap';\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!';\n\nconst NOT_ALLOW_OP = 'This operation is not allow!';\n\nconst MY_NAMESPACE = 'myNamespace'\n\nconst CB_FN_NAME = 'on'\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME\n}\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// create a clone version so we know which one we actually is using\nexport default class JsonqlWsEvt extends NBEventService {\n\n constructor(logger) {\n // this ee will always come with the logger\n // because we should take the ee from the configuration\n super({ logger })\n }\n\n get name() {\n return'jsonql-ws-client'\n }\n}\n","// mapping the resolver to their respective nsp\nimport { JSONQL_PATH, NSP_SET, PUBLIC_NAMESPACE } from 'jsonql-constants'\nimport { groupByNamespace, extractSocketPart } from 'jsonql-utils/module'\nimport { JsonqlResolverNotFoundError } from 'jsonql-errors'\n\nimport { MISSING_PROP_ERR } from '../options/constants'\n\n/**\n * Just make sure the object contain what we are looking for\n * @param {object} opts configuration from checkOptions\n * @return {object} the target content\n */\nconst getResolverList = contract => {\n const result = extractSocketPart(contract)\n if (result !== false) {\n return result\n }\n throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR)\n}\n\n/**\n * process the contract first\n * @param {object} opts configuration\n * @return {object} sorted list\n */\nexport default function processContract(opts) {\n const { contract, enableAuth } = opts;\n if (enableAuth) {\n return groupByNamespace(contract)\n }\n return {\n [NSP_SET]: { [JSONQL_PATH]: getResolverList(contract) },\n [PUBLIC_NAMESPACE]: JSONQL_PATH\n }\n}\n","// group all the small functions here\nimport { JS_WS_SOCKET_IO_NAME, JS_WS_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/src/generic'\n\n// we shouldn't do this anymore\nexport const fixWss = (url, serverType) => {\n // ws only allow ws:// path\n if (serverType === JS_WS_NAME) {\n return url.replace('http://', 'ws://')\n }\n return url;\n}\n\n/**\n * get a stock host name from browser\n */\nexport const getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n throw new JsonqlValidationError(e)\n }\n}\n\n/**\n * Unbind the event\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nexport const clearMainEmitEvt = (ee, namespace) => {\n let nsps = toArray(namespace)\n nsps.forEach(n => {\n ee.$off(createEvt(n, EMIT_REPLY_TYPE))\n })\n}\n\n/**\n * @param {object} nsps namespace as key\n * @param {string} type of server\n */\nexport const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => {\n try {\n // @TODO need to figure out a better way here?\n const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate';\n for (let namespace in nsps) {\n let nsp = nsps[namespace]\n if (nsp && nsp[method]) {\n Reflect.apply(nsp[method], null, [])\n }\n }\n } catch(e) {\n // socket.io throw a this.destroy of undefined?\n console.error('Disconnect call failed', e)\n }\n}\n","// breaking it up further to share between methods\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { UNKNOWN_RESULT } from '../options/constants'\nimport { isObjectHasKey } from '../utils'\n\n/**\n * break out to use in different places to handle the return from server\n * @param {object} data from server\n * @param {function} resolver NOT from promise\n * @param {function} rejecter NOT from promise\n * @return {void} nothing\n */\nexport function respondHandler(data, resolver, rejecter) {\n if (isObjectHasKey(data, ERROR_KEY)) {\n // debugFn('-- rejecter called --', data[ERROR_KEY])\n rejecter(data[ERROR_KEY])\n } else if (isObjectHasKey(data, DATA_KEY)) {\n // debugFn('-- resolver called --', data[DATA_KEY])\n resolver(data[DATA_KEY])\n } else {\n // debugFn('-- UNKNOWN_RESULT --', data)\n rejecter({message: UNKNOWN_RESULT, error: data})\n }\n}\n","// the actual trigger call method\nimport { ON_RESULT_PROP_NAME, RESULT_PROP_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { createEvt, toArray } from '../utils'\nimport { respondHandler } from './respond-handler'\n\n/**\n * just wrapper\n * @param {object} ee EventEmitter\n * @param {string} namespace where this belongs\n * @param {string} resolverName resolver\n * @param {boolean} useCallbackStyle use on or not\n * @param {array} args arguments\n * @return {void} nothing\n */\nexport function actionCall(ee, namespace, resolverName, useCallbackStyle, args = []) {\n const eventName = createEvt(namespace, EMIT_REPLY_TYPE)\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME\n // debugFn(`actionCall: ${eventName} --> ${resolverName}`, args)\n ee.$trigger(eventName, [resolverName, toArray(args)])\n // once we trigger there is nothing return from the resolve\n // @TODO if we need the next then call to have the result back\n // then we need to listen to the event callback here as well\n return new Promise((resolver, rejecter) => {\n ee.$on(\n createEvt(namespace, resolverName, RESULT_SUBFIX),\n function actionCallResultHandler(result) {\n // debugFn(`got the first result`, result)\n respondHandler(result, resolver, rejecter)\n }\n )\n })\n}\n","// @TODO using the obj.on syntax to do the same thing\n/*\nThe new callback style `useCallbackStyle` set to true then use this one\nclient.resolverName.on(EVENT_NAME, cb)\n*/\nimport { JsonqlValidationError, JsonqlError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME,\n READY_PROP_NAME,\n ON_ERROR_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_MESSAGE_PROP_NAME\n} from 'jsonql-constants'\nimport { CB_FN_NAME } from '../options/constants'\n\nimport { respondHandler } from './respond-handler'\nimport { chainFns, injectToFn, createEvt, toArray, isFunc, isString } from '../utils'\n\n/**\n * Add extra property to the resolver via the getter\n * @param {function} fn the resolver itself\n * @param {object} ee event emitter\n * @param {string} namespace the namespace this belongs to\n * @param {string} resolverName resolver namee\n * @param {object} params from the contract\n * @return {array} same as what goes in\n */\nexport function setupCallbackApi(fn, ee, namespace, resolverName, params) {\n return [\n injectToFn(fn, CB_FN_NAME, function(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch(evtName) {\n case RESULT_PROP_NAME:\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n // register the handler for this message event\n case MESSAGE_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME),\n function onMessageCallback(args) {\n respondHandler(args, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n case READY_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n callback\n )\n break;\n default:\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n new JsonqlError(resolverName, `Unknown event name ${evtName}!`)\n )\n }\n }\n }),\n ee,\n namespace,\n resolverName,\n params\n ]\n}\n","// break up the original setup resolver method here\nimport { JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\nimport { MY_NAMESPACE } from '../options/constants'\nimport { chainFns, objDefineProps, injectToFn, createEvt, toArray, isFunc } from '../utils'\n\nimport { respondHandler } from './respond-handler'\nimport { setupSend } from './setup-send'\nimport { setupCallbackApi } from './setup-callback-api'\n\n/**\n * The first one in the chain\n * @return {array}\n */\nconst setupNamespace = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n injectToFn(fn, MY_NAMESPACE, namespace),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// onResult handler\nconst setupOnResult = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_RESULT_PROP_NAME, function(resultCallback) {\n if (isFunc(resultCallback)) {\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, resultCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// we do need to add the send prop back because it's the only way to deal with\n// bi-directional data stream\nconst setupOnMessage = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_MESSAGE_PROP_NAME, function(messageCallback) {\n // we expect this to be a function\n if (isFunc(messageCallback)) {\n // did that add to the callback\n let onMessageCallback = (args) => {\n respondHandler(args, messageCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n // register the handler for this message event\n ee.$only(createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME), onMessageCallback)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// add an ON_ERROR_PROP_NAME handler\nconst setupOnError = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_ERROR_PROP_NAME, function(resolverErrorHandler) {\n if (isFunc(resolverErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n ee.$only(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), resolverErrorHandler)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n/**\n * Add extra property to the resolver\n * @param {string} namespace where this belongs\n * @param {string} resolverName name as event name\n * @param {object} params from contract\n * @param {function} fn resolver function\n * @param {object} ee EventEmitter\n * @param {boolean} useCallbackStyle new callback style\n * @return {function} resolver\n */\nexport function setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle) {\n // also need to setup a getter to get back the namespace of this resolver\n let args = [setupNamespace]\n useCallbackStyle ? args.push(setupCallbackApi) : args.push(setupOnResult, setupOnMessage, setupOnError)\n args.push(setupSend)\n // get the executor\n const executor = Reflect.apply(chainFns, null, args)\n\n return Reflect.apply(executor, null, [fn, ee, namespace, resolverName, params, useCallbackStyle])\n}\n","// put all the resolver related methods here to make it more clear\n\n// this will be a mini client server architect\n// The reason is when the enableAuth setup - the private route\n// might not be validated, but we need the callable point is ready\n// therefore this part will always take the contract and generate\n// callable api for the developer to setup their front end\n// the only thing is - when they call they might get an error or\n// NOT_LOGIN_IN and they can react to this error accordingly\nimport { JsonqlError, JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n ERROR_PROP_NAME,\n LOGIN_PROP_NAME,\n READY_PROP_NAME,\n ON_ERROR_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n ON_READY_PROP_NAME\n} from 'jsonql-constants'\nimport { actionCall } from './action-call'\nimport {\n createEvt,\n toArray,\n injectToFn,\n objDefineProps,\n chainFns,\n isString,\n isFunc,\n isObjectHasKey\n} from '../utils'\nimport { CB_FN_NAME } from '../options/constants'\n\n/**\n * create the actual function to send message to server\n * @param {object} ee EventEmitter instance\n * @param {string} namespace this resolver end point\n * @param {string} resolverName name of resolver as event name\n * @param {object} params from contract\n * @param {boolean} useCallbackStyle on style or not\n * @return {function} resolver\n */\nexport function createResolver(ee, namespace, resolverName, params, useCallbackStyle) {\n // note we pass the new withResult=true option\n return function(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => actionCall(ee, namespace, resolverName, useCallbackStyle, _args))\n .catch(finalCatch)\n }\n}\n\n/**\n * The problem is the namespace can have more than one\n * and we only have on onError message\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @param {boolean} useCallbackStyle use cb or not\n * @return {object} obj with onError prop\n */\nexport function createNamespaceErrorHandler(obj, ee, nspSet) {\n // using the onError as name\n // @TODO we should follow the convention earlier\n // make this a setter for the obj itself\n return objDefineProps(obj, ON_ERROR_PROP_NAME, function namespaceErrorCallbackHandler(namespaceErrorHandler) {\n if (isFunc(namespaceErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n for (let namespace in nspSet) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ON_ERROR_PROP_NAME), namespaceErrorHandler)\n }\n }\n })\n}\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @return {object} obj with onReady prop\n */\nexport function createOnReadyhandler(obj, ee, nspSet) {\n return objDefineProps(obj, ON_READY_PROP_NAME, function onReadyCallbackHandler(onReadyCallback) {\n if (isFunc(onReadyCallback)) {\n // reduce it down to just one flat level\n ee.$on(ON_READY_PROP_NAME, onReadyCallback)\n }\n })\n}\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * Plus this will check if it's the private namespace that fired the event\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} opts configuration\n * @return {object} obj with onLogin prop\n */\nexport function createOnLoginhandler(obj, ee, opts) {\n if (opts.enableAuth) {\n return objDefineProps(obj, ON_LOGIN_PROP_NAME, function onLoginCallbackHandler(onLoginCallback) {\n if (isFunc(onLoginCallback)) {\n // only one callback can registered with it, TBC\n ee.$only(ON_LOGIN_PROP_NAME, onLoginCallback)\n }\n })\n }\n // just skip it\n return obj\n}\n\n/**\n * when useCallbackStyle=true use this instead of the above method\n * @param {object} obj the base object to attach to\n * @param {object} ee EventEmitter\n * @param {object} nspSet the map\n * @param {object} opts configuration\n * @return {object} obj\n */\nexport function createCallbackHandler(obj, ee, nspSet, opts) {\n return injectToFn(obj, CB_FN_NAME, function onHandler(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch (evtName) {\n case ERROR_PROP_NAME:\n for (let namespace in nspSet) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ERROR_PROP_NAME), callback)\n }\n break;\n case LOGIN_PROP_NAME: // @TODO should only available when enableAuth=true\n ee.$only(LOGIN_PROP_NAME, callback)\n break;\n case READY_PROP_NAME:\n ee.$on(READY_PROP_NAME, callback)\n break;\n default:\n ee.$trigger(ERROR_PROP_NAME, new JsonqlError(CB_FN_NAME, `Unknown event name ${evtName}!`))\n }\n }\n // @TODO need to issue another error here!\n })\n}\n","// take out from the resolver-methods\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { injectToFn, chainFns, isString } from '../utils'\n\n/**\n * @TODO this is now become unnecessary because the login is a slave to the\n * http-client - but keep this for now and see what we want to do with it later\n * break out from createAuthMethods to allow chaining call\n * @param {object} obj the main client object\n * @param {object} ee event emitter\n * @param {object} opts configuration\n * @return {array} modified input\n */\nconst setupLoginHandler = (obj, ee, opts) => [\n injectToFn(obj, opts.loginHandlerName, function loginHandler(token) {\n if (token && isString(token)) {\n return ee.$trigger(LOGIN_EVENT_NAME, [token])\n }\n // should trigger a global error instead @TODO\n throw new JsonqlValidationError(opts.loginHandlerName, `Unexpected token ${token}`)\n }),\n ee,\n opts\n]\n\n/**\n * break out from createAuthMethods to allow chaining call - final in chain\n * @param {object} obj the main client object\n * @param {object} ee event emitter\n * @param {object} opts configuration\n * @return {object} the modified obj\n */\nconst setupLogoutHandler = (obj, ee, opts) => (\n injectToFn(obj, opts.logoutHandlerName, function logoutHandler(...args) {\n ee.$trigger(LOGOUT_EVENT_NAME, args)\n })\n)\n\n/**\n * Create auth related methods\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} opts configuration\n * @return {object} obj with auth methods if any\n */\nexport function createAuthMethods(obj, ee, opts) {\n if (opts.enableAuth) {\n return chainFns(setupLoginHandler, setupLogoutHandler)(obj, ee, opts)\n }\n return obj;\n}\n","// resolvers generator\n// we change the interface to return promise from v1.0.3\n// this way we make sure the obj return is correct and timely\nimport { setupResolver } from './setup-resolver'\nimport {\n createResolver,\n createNamespaceErrorHandler,\n createOnReadyhandler,\n createOnLoginhandler,\n createCallbackHandler\n} from './resolver-methods'\nimport { createAuthMethods } from './setup-auth-methods'\nimport { injectToFn, chainProcessPromises } from '../utils'\n\n/**\n * step one get the obj map with the namespace\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {promise} resolve the obj mapped, and start the chain\n */\nfunction getMappedObj(opts, nspMap, ee) {\n let obj = {};\n // let resolverNames = [];\n const { nspSet } = nspMap;\n const { useCallbackStyle } = opts; // @1.2.1\n for (let namespace in nspSet) {\n let list = nspSet[namespace]\n for (let resolverName in list) {\n // resolverNames.push(resolverName)\n let params = list[resolverName]\n let fn = createResolver(ee, namespace, resolverName, params, useCallbackStyle)\n // this should set as a getter therefore can not be overwrite by accident\n // obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee)\n obj = injectToFn(obj, resolverName, setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle))\n }\n }\n // move this two method down to helpers\n // we want these methods visible in debug or console.log\n obj.devHelpers = {\n // this is a helper method for the developer to know the namespace inside\n getNsp: () => Object.keys(nspSet),\n // simple get version trick\n getVer: () => opts.version || 'NOT SET'\n // not really necessary because the dev can query the contract\n // getResolverNames: () => resolverNames\n }\n // resolve the obj to start the chain\n // chain the result to allow the chain processing\n return Promise.resolve(obj)\n}\n\n/**\n * prepare the methods\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {object} of resolvers\n * @public\n */\nexport function generator(opts, nspMap, ee) {\n const { nspSet } = nspMap\n const { useCallbackStyle, enableAuth } = opts;\n let args = [getMappedObj]\n if (useCallbackStyle) {\n args.push(obj => createCallbackHandler(obj, ee, nspSet, opts))\n } else {\n args.push(\n obj1 => createNamespaceErrorHandler(obj1, ee, nspSet),\n obj2 => createOnReadyhandler(obj2, ee, nspSet),\n )\n if (enableAuth) {\n args.push(obj3 => createOnLoginhandler(obj3, ee, opts))\n }\n }\n // this only apply to when enableAuth = true\n if (enableAuth) {\n args.push(obj4 => createAuthMethods(obj4, ee, opts))\n }\n // run it\n const executor = Reflect.apply(chainProcessPromises, null, args)\n return executor(opts, nspMap, ee)\n}\n","// create options\nimport { checkConfigAsync, isNotEmpty } from 'jsonql-params-validator'\nimport { CHECKED_KEY } from 'jsonql-constants'\n// import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors'\n// this should be remove - we have to make it generic\nimport { defaultOptions } from './defaults'\nimport { fixWss, getHostName, objHasProp } from '../utils'\n\n// constant props\nconst defaultConstProps = {\n eventEmitter: null,\n // we unify the two different client into one now\n // only expect different parameter\n nspClient: null,\n nspAuthClient: null,\n // contructed path\n wssPath: ''\n}\n// for export\nconst jsonqlWsDefaultOptions = defaultOptions\nconst jsonqlWsDefaultConstProps = defaultConstProps\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config\n * @param {object} dOpt\n * @param {object} cProps\n * @return {promise} resolve to the checked opitons\n */\nfunction checkOptionsWrapper(config, dOpt, cProps) {\n if (objHasProp(config, CHECKED_KEY)) {\n return Promise.resolve(config)\n }\n return checkConfigAsync(config, dOpt, cProps)\n}\n\n/**\n * check the configuration\n * @param {object} config user supplied configuration\n * @param {object} constProps developer supplied configuration\n * @return {object} after checked\n */\nfunction checkOptions(config, constProps) {\n return checkOptionsWrapper(config, defaultOptions, Object.assign(defaultConstProps, constProps))\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // debug('CONFIGURATION OPTIONS', opts)\n return opts;\n })\n}\n\nexport {\n jsonqlWsDefaultConstProps,\n jsonqlWsDefaultOptions,\n checkOptions\n}\n","// the top level API\n// The goal is to create a generic method that will able to handle\n// any kind of clients\n// import { injectToFn } from 'jsonql-utils'\nimport { generator } from './core'\nimport { checkOptions } from './options'\nimport { ee, processContract } from './utils'\nconst dummyLogger = () => {}\n/**\n * The main interface which will generate the socket clients and map all events\n * @param {object} socketClientResolver this is the one method export by various clients\n * @param {object} [constProps={}] add this to supply the constProps from the downstream client\n * @return {object} the wsClient instance with all the available API\n */\nexport default function wsClient(socketClientResolver, constProps = {}) {\n const { log } = constProps // 1.3.9 if we pass a log method here then we use this\n const logger = log && typeof log === 'function' ? log : dummyLogger\n // we need to inject property to this client later\n // therefore we need to do it this way\n return (opts) => {\n const { eventEmitter } = opts; // pass from the next level up\n return checkOptions(opts, constProps)\n .then(opts => {\n opts.logger = logger\n return opts;\n })\n .then(opts => ({\n opts,\n nspMap: processContract(opts),\n ee: eventEmitter || new ee(logger)\n }))\n .then(\n ({opts, nspMap, ee}) => socketClientResolver(opts, nspMap, ee)\n )\n .then(\n ({opts, nspMap, ee}) => generator(opts, nspMap, ee)\n )\n .catch(err => {\n console.error(`jsonql-ws-client init error`, err)\n })\n }\n}\n","// where all the base options are\n// create options\nimport { JS_WS_NAME } from 'jsonql-constants'\n// constant props\nconst constProps = {\n version: '__PLACEHOLDER__', // will get replace\n serverType: JS_WS_NAME\n}\n\nexport { constProps }\n","// pass the different type of ws to generate the client\nimport { TOKEN_PARAM_NAME } from 'jsonql-constants'\n/**\n * WebSocket is strict about the path, therefore we need to make sure before it goes in\n * @param {string} url input url\n * @return {string} url with correct path name\n */\nconst fixWss = url => {\n const uri = url.toLowerCase()\n if (uri.indexOf('http') > -1) {\n if (uri.indexOf('https') > -1) {\n return uri.replace('https', 'wss')\n }\n return uri.replace('http', 'ws')\n }\n return uri\n}\n\n/**\n * The bug was in the wsOptions where ws doesn't need it but socket.io do\n * therefore the object was pass as second parameter!\n * @param {object} WebSocket the client or node version of ws\n * @param {boolean} auth if it's auth then 3 param or just one\n */\nexport function createWsClient(WebSocket, auth = false) {\n if (auth === false) {\n return function createWsClientHandler(url) {\n return new WebSocket(fixWss(url))\n }\n }\n\n /**\n * Create a client with auth token\n * @param {string} url start with ws:// @TODO check this?\n * @param {string} token the jwt token\n * @return {object} ws instance\n */\n return function createWsAuthClientHandler(url, token) {\n const ws_url = fixWss(url)\n // console.log('what happen here?', url, ws_url, token)\n const uri = token && typeof token === 'string' ? `${ws_url}?${TOKEN_PARAM_NAME}=${token}` : ws_url\n try {\n return new WebSocket(uri)\n } catch(e) {\n console.error('WebSocket Connection Error', e)\n return false\n }\n }\n}\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME;\nconst WS = JS_WS_NAME;\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!';\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!';\n\nconst MISSING_PROP_ERR = 'Missing property in contract!';\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!';\n\nconst EMIT_EVT = EMIT_REPLY_TYPE;\n\nconst NAMESPACE_KEY = 'namespaceMap';\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!';\n\nconst NOT_ALLOW_OP = 'This operation is not allow!';\n\nconst MY_NAMESPACE = 'myNamespace'\n\nconst CB_FN_NAME = 'on'\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME\n}\n","// since both the ws and io version are\n// pre-defined in the client-generator\n// and this one will have the same parameters\n// and the callback is identical\n\n/**\n * wrapper method to create a nsp without login\n * @param {string|boolean} namespace namespace url could be false\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspClient(namespace, opts) {\n const { hostname, wssPath, wsOptions, nspClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n return nspClient(url, wsOptions)\n}\n\n/**\n * wrapper method to create a nsp with token auth\n * @param {string} namespace namespace url\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspAuthClient(namespace, opts) {\n const { hostname, wssPath, token, wsOptions, nspAuthClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n if (token && typeof token !== 'string') {\n throw new Error(`Expect token to be string, but got ${token}`)\n }\n return nspAuthClient(url, token, wsOptions)\n}\n\nexport {\n createNspClient,\n createNspAuthClient\n}\n","// group all the small functions here\nimport { JS_WS_SOCKET_IO_NAME, JS_WS_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/src/generic'\n\n// we shouldn't do this anymore\nexport const fixWss = (url, serverType) => {\n // ws only allow ws:// path\n if (serverType === JS_WS_NAME) {\n return url.replace('http://', 'ws://')\n }\n return url;\n}\n\n/**\n * get a stock host name from browser\n */\nexport const getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n throw new JsonqlValidationError(e)\n }\n}\n\n/**\n * Unbind the event\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nexport const clearMainEmitEvt = (ee, namespace) => {\n let nsps = toArray(namespace)\n nsps.forEach(n => {\n ee.$off(createEvt(n, EMIT_REPLY_TYPE))\n })\n}\n\n/**\n * @param {object} nsps namespace as key\n * @param {string} type of server\n */\nexport const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => {\n try {\n // @TODO need to figure out a better way here?\n const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate';\n for (let namespace in nsps) {\n let nsp = nsps[namespace]\n if (nsp && nsp[method]) {\n Reflect.apply(nsp[method], null, [])\n }\n }\n } catch(e) {\n // socket.io throw a this.destroy of undefined?\n console.error('Disconnect call failed', e)\n }\n}\n","// this use by client-event-handler\nimport { ON_ERROR_PROP_NAME, ERROR_PROP_NAME } from 'jsonql-constants'\nimport { createEvt } from '../utils'\n\n/**\n * trigger errors on all the namespace onError handler\n * @param {object} ee Event Emitter\n * @param {array} namespaces nsps string\n * @param {string} message optional\n * @param {object} opts configuration\n * @return {void}\n */\nexport function triggerNamespacesOnError(ee, namespaces, message, opts = {}) {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n namespaces.forEach( namespace => {\n ee.$call(createEvt(namespace, ERROR_SUBFIX), [{ message, namespace }])\n })\n}\n","// This is share between different clients so we export it\n// @TODO port what is in the ws-main-handler\n// because all the client side call are via the ee\n// and that makes it re-usable between different client setup\nimport {\n ERROR_PROP_NAME,\n RESULT_PROP_NAME,\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n NOT_LOGIN_ERR_MSG,\n ON_ERROR_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n} from 'jsonql-constants'\nimport { EMIT_EVT, SOCKET_IO, WS } from '../options/constants'\nimport { createEvt, clearMainEmitEvt } from '../utils'\nimport { triggerNamespacesOnError } from './trigger-namespaces-on-error'\n\n/**\n * A fake ee handler\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nconst notLoginWsHandler = (namespace, ee, opts) => {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function notLoginHandlerCallback(resolverName, args) {\n opts.logger('noLoginHandler hijack the ws call', namespace, resolverName, args)\n let error = {\n message: NOT_LOGIN_ERR_MSG\n }\n // It should just throw error here and should not call the result\n // because that's channel for handling normal event not the fake one\n ee.$call(createEvt(namespace, resolverName, ERROR_SUBFIX), [error])\n // also trigger the result handler, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, RESULT_SUBFIX), [{ error }])\n }\n )\n}\n\n/**\n * get the private namespace\n * @param {array} namespaces array\n * @return {*} string on success\n */\nconst getPrivateNamespace = (namespaces) => (\n namespaces.length > 1 ? namespaces[0] : false\n)\n\n/**\n * centralize all the comm in one place\n * @param {object} opts configuration\n * @param {array} namespaces namespace(s)\n * @param {object} ee Event Emitter instance\n * @param {function} bindWsHandler binding the ee to ws --> this is the core bit\n * @param {array} namespaces array of namespace available\n * @param {object} nsps namespaced nsp\n * @return {void} nothing\n */\nexport function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) {\n // @1.1.3 add isPrivate prop to id which namespace is the private nsp\n // then we can use this prop to determine if we need to fire the ON_LOGIN_PROP_NAME event\n const privateNamespace = getPrivateNamespace(namespaces)\n let isPrivate = false;\n // loop\n // @BUG for io this has to be in order the one with auth need to get call first\n // The order of login is very import we need to run a waterfall here to make sure\n // one is execute then the other\n namespaces.forEach(namespace => {\n isPrivate = privateNamespace === namespace;\n if (nsps[namespace]) {\n opts.logger('call bindWsHandler', isPrivate, namespace)\n let args = [namespace, nsps[namespace], ee, isPrivate, opts]\n if (opts.serverType === SOCKET_IO) {\n let { nspSet } = nspMap;\n args.push(nspSet[namespace])\n }\n Reflect.apply(bindWsHandler, null, args)\n } else {\n // a dummy placeholder\n notLoginWsHandler(namespace, ee, opts)\n }\n })\n // this will be available regardless enableAuth\n // because the server can log the client out\n ee.$on(LOGOUT_EVENT_NAME, function logoutEvtHandler() {\n opts.logger('LOGOUT_EVENT_NAME')\n // disconnect(nsps, opts.serverType)\n // we need to issue error to all the namespace onError handler\n triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME)\n // rebind all of the handler to the fake one\n namespaces.forEach( namespace => {\n clearMainEmitEvt(ee, namespace)\n // clear out the nsp\n nsps[namespace] = false;\n // add a NOT LOGIN error if call\n notLoginWsHandler(namespace, ee, opts)\n })\n })\n}\n","// take the ws reply data for use\nimport { WS_EVT_NAME, WS_DATA_NAME, WS_REPLY_TYPE } from 'jsonql-constants'\nimport { isString } from 'jsonql-params-validator'\nimport { isObjectHasKey } from 'jsonql-utils/module'\nimport { JsonqlError, clientErrorsHandler } from 'jsonql-errors'\n\nconst keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ]\n\n/**\n * @param {object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nconst isWsReply = payload => {\n const { data } = payload\n if (data) {\n let result = keys.filter(key => isObjectHasKey(data, key))\n return (result.length === keys.length) ? data : false\n }\n return false\n}\n\n/**\n * @param {object} payload This is the entire ws Event Object\n * @return {object} false on failed\n */\nconst extractWsPayload = payload => {\n const { data } = payload;\n let json = isString(data) ? JSON.parse(data) : data\n // debugFn('extractWsPayload', json)\n let fdata;\n if ((fdata = isWsReply(json)) !== false) {\n return {\n resolverName: fdata[WS_EVT_NAME],\n data: fdata[WS_DATA_NAME],\n type: fdata[WS_REPLY_TYPE]\n }\n }\n throw new JsonqlError('payload can not be decoded', payload)\n}\n// export it\nexport default extractWsPayload\n","// the WebSocket main handler\nimport {\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n ACKNOWLEDGE_REPLY_TYPE,\n EMIT_REPLY_TYPE,\n ERROR_TYPE,\n\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_READY_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME,\n READY_PROP_NAME,\n LOGIN_PROP_NAME\n} from 'jsonql-constants'\nimport { createQueryStr, createEvt } from 'jsonql-utils/module'\nimport extractWsPayload from './extract-ws-payload'\nconst dummyLogger = () => {}\n/**\n * under extremely circumstances we might not even have a resolverName, then\n * we issue a global error for the developer to catch it\n * @param {object} ee event emitter\n * @param {string} namespace nsp\n * @param {string} resolverName resolver\n * @param {object} json decoded payload or error object\n * @param {string} ERROR_EVT_NAME the error event name\n * @return {undefined} nothing return\n */\nconst errorTypeHandler = (ee, namespace, resolverName, json, ERROR_EVT_NAME) => {\n let evt = [namespace]\n if (resolverName) {\n evt.push(resolverName)\n }\n evt.push(ERROR_EVT_NAME)\n let evtName = Reflect.apply(createEvt, null, evt)\n // test if there is a data field\n let payload = json.data || json;\n ee.$trigger(evtName, [payload])\n}\n\n/**\n * Binding the even to socket normally\n * @param {string} namespace\n * @param {object} ws the nsp\n * @param {object} ee EventEmitter\n * @param {boolean} isPrivate to id if this namespace is private or not\n * @param {object} opts configuration\n * @return {object} promise resolve after the onopen event\n */\nexport function wsMainHandler(namespace, ws, ee, isPrivate, opts) {\n\n const debugFn = opts.log || dummyLogger\n\n debugFn(`wsMainHandler log test`)\n\n const { useCallbackStyle } = opts;\n const READY_EVT_NAME = useCallbackStyle ? READY_PROP_NAME : ON_READY_PROP_NAME;\n const LOGIN_EVT_NAME = useCallbackStyle ? LOGIN_PROP_NAME : ON_LOGIN_PROP_NAME;\n const MESSAGE_EVT_NAME = useCallbackStyle ? MESSAGE_PROP_NAME : ON_MESSAGE_PROP_NAME;\n const RESULT_EVT_NAME = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n const ERROR_EVT_NAME = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n // connection open\n ws.onopen = function onOpenCallback() {\n debugFn('ws.onopen listened')\n // we just call the onReady\n ee.$call(READY_EVT_NAME, namespace)\n // need an extra parameter here to id the private nsp\n if (isPrivate) {\n debugFn(`isPrivate and fire the ${LOGIN_EVT_NAME}`)\n ee.$call(LOGIN_EVT_NAME, namespace)\n }\n // add listener only after the open is called\n ee.$only(\n createEvt(namespace, EMIT_REPLY_TYPE),\n function wsMainOnEvtHandler(resolverName, args) {\n debugFn('calling server', resolverName, args)\n ws.send(\n createQueryStr(resolverName, args)\n )\n }\n )\n }\n\n // reply\n // If we change it to the event callback style\n // then the payload will just be the payload and fucks up the extractWsPayload call @TODO\n ws.onmessage = function onMessageCallback(payload) {\n // console.log(`on.message`, typeof payload, payload)\n try {\n const json = extractWsPayload(payload)\n const { resolverName, type } = json;\n debugFn('Hear from server', type, json)\n switch (type) {\n case EMIT_REPLY_TYPE:\n let e1 = createEvt(namespace, resolverName, MESSAGE_EVT_NAME)\n let r = ee.$trigger(e1, [json])\n debugFn(`EMIT_REPLY_TYPE`, e1, r)\n break;\n case ACKNOWLEDGE_REPLY_TYPE:\n let e2 = createEvt(namespace, resolverName, RESULT_EVT_NAME)\n let x = ee.$trigger(e2, [json])\n // debugFn(`ACKNOWLEDGE_REPLY_TYPE`, e2, json)\n break;\n case ERROR_TYPE:\n // this is handled error and we won't throw it\n // we need to extract the error from json\n debugFn(`ERROR_TYPE`)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\n break;\n // @TODO there should be an error type instead of roll into the other two types? TBC\n default:\n // if this happen then we should throw it and halt the operation all together\n debugFn('Unhandled event!', json)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\n // let error = {error: {'message': 'Unhandled event!', type}};\n // ee.$trigger(createEvt(namespace, resolverName, ON_RESULT_PROP_NAME), [error])\n }\n } catch(e) {\n console.error(`ws.onmessage error`, e)\n errorTypeHandler(ee, namespace, false, e, ERROR_EVT_NAME)\n }\n }\n // when the server close the connection\n ws.onclose = function onCloseCallback() {\n debugFn('ws.onclose callback')\n // @TODO what to do with this\n // ee.$trigger(LOGOUT_EVENT_NAME, [namespace])\n }\n // listen to the LOGOUT_EVENT_NAME\n ee.$on(LOGOUT_EVENT_NAME, function closeEvtHandler() {\n try {\n debugFn('terminate ws connection')\n ws.terminate()\n } catch(e) {\n console.error('ws.terminate error', e)\n }\n })\n}\n","// actually binding the event client to the socket client\nimport { getNameFromPayload, getNamespaceInOrder } from 'jsonql-utils/module'\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, JS_WS_NAME } from 'jsonql-constants'\nimport {\n createNspClient,\n createNspAuthClient,\n clientEventHandler,\n triggerNamespacesOnError,\n clearMainEmitEvt,\n disconnect\n} from 'jsonql-ws-client/share'\nimport { wsMainHandler } from './ws-main-handler'\n\n/**\n * Because the nsps can be throw away so it doesn't matter the scope\n * this will get reuse again\n * @param {object} opts configuration\n * @param {object} nspMap from contract\n * @param {string|null} token whether we have the token at run time\n * @return {object} nsps namespace with namespace as key\n */\nconst createNsps = function(opts, nspMap, token) {\n let { nspSet, publicNamespace } = nspMap\n let login = false\n let namespaces = []\n let nsps = {}\n // first we need to binding all the events handler\n if (opts.enableAuth) { // && opts.useJwt\n login = true; // just saying we need to listen to login event\n namespaces = getNamespaceInOrder(nspSet, publicNamespace)\n nsps = namespaces.map((namespace, i) => {\n if (i === 0) {\n if (token) {\n opts.token = token\n // console.log('create createNspAuthClient at run time', opts)\n return {[namespace]: createNspAuthClient(namespace, opts)}\n }\n return {[namespace]: false}\n }\n return {[namespace]: createNspClient(namespace, opts)}\n }).reduce((first, next) => Object.assign(first, next), {})\n } else {\n let namespace = getNameFromPayload(nspSet)\n namespaces.push(namespace)\n // standard without login\n // the stock version should not have a namespace\n nsps[namespace] = createNspClient(false, opts)\n }\n // return\n return { nsps, namespaces, login }\n}\n\n/**\n * create a ws client\n * @param {object} opts configuration\n * @param {object} nspMap namespace with resolvers\n * @param {object} ee EventEmitter to pass through\n * @return {object} what comes in what goes out\n */\nexport function createClient(opts, nspMap, ee) {\n // arguments that don't change\n const args = [opts, nspMap, ee, wsMainHandler]\n // now create the nsps\n const { token } = opts\n const { nsps, namespaces, login } = createNsps(opts, nspMap, token)\n // binding the listeners - and it will listen to LOGOUT event\n // to unbind itself, and the above call will bind it again\n Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps]))\n // setup listener\n if (login) {\n ee.$only(LOGIN_EVENT_NAME, function loginEventHandler(tokenLater) {\n // debugFn(`LOGIN_EVENT_NAME called with token:`, tokenLater)\n // @BUG this keep causing an \"Disconnect call failed TypeError: Cannot read property 'readyState' of null\"\n // I think that is because it's not login then it can not be disconnect\n // how do we track this state globally\n // disconnect(nsps, JS_WS_NAME)\n\n // @TODO should we trigger error on this one?\n // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME)\n clearMainEmitEvt(ee, namespaces)\n // console.log('LOGIN_EVENT_NAME', token)\n const newNsps = createNsps(opts, nspMap, tokenLater)\n // rebind it\n Reflect.apply(\n clientEventHandler,\n null,\n args.concat([newNsps.namespaces, newNsps.nsps])\n )\n })\n }\n // return what input\n return { opts, nspMap, ee }\n}\n","// share method to create the wsClientResolver\n\nimport { createWsClient } from './create-ws-client'\nimport { createClient } from './create-client'\n\n/**\n * combine the create client resolver\n * @param {object} ws the different WebSocket module\n * @return {function} the wsClientResolver\n */\nexport default function createClientResolver(ws) {\n const client = createWsClient(ws)\n const authClient = createWsClient(ws, true)\n /**\n * wsClientResolver\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\n return function(opts, nspMap, ee) {\n opts.nspClient = client;\n opts.nspAuthClient = authClient;\n\n // console.log(`contract`, opts.contract)\n\n return createClient(opts, nspMap, ee)\n }\n}\n","// this will be the news style interface that will pass to the jsonql-ws-client\n// then return a function for accepting an opts to generate the final\n// client api\nimport WebSocket from './core/ws'\nimport createClientResolver from './core/create-client-resolver'\n\n/**\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\nexport default createClientResolver(WebSocket)\n","// this is the module entry point for ES6 for client\n// the main will point to the node.js server side setup\nimport { jsonqlWsClientCore } from 'jsonql-ws-client-core'\n\nimport { constProps } from './src/options'\nimport wsClientResolver from './src/ws-client-resolver'\n\n// export back the function and that's it\nexport default jsonqlWsClientCore(wsClientResolver, constProps)\n","// create options\nimport { checkConfigAsync, isNotEmpty } from 'jsonql-params-validator'\nimport { CHECKED_KEY } from 'jsonql-constants'\n// import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors'\n// this should be remove - we have to make it generic\nimport { defaultOptions } from './defaults'\nimport { fixWss, getHostName, objHasProp } from '../utils'\n\n// constant props\nconst defaultConstProps = {\n eventEmitter: null,\n // we unify the two different client into one now\n // only expect different parameter\n nspClient: null,\n nspAuthClient: null,\n // contructed path\n wssPath: ''\n}\n// for export\nconst jsonqlWsDefaultOptions = defaultOptions\nconst jsonqlWsDefaultConstProps = defaultConstProps\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config\n * @param {object} dOpt\n * @param {object} cProps\n * @return {promise} resolve to the checked opitons\n */\nfunction checkOptionsWrapper(config, dOpt, cProps) {\n if (objHasProp(config, CHECKED_KEY)) {\n return Promise.resolve(config)\n }\n return checkConfigAsync(config, dOpt, cProps)\n}\n\n/**\n * check the configuration\n * @param {object} config user supplied configuration\n * @param {object} constProps developer supplied configuration\n * @return {object} after checked\n */\nfunction checkOptions(config, constProps) {\n return checkOptionsWrapper(config, defaultOptions, Object.assign(defaultConstProps, constProps))\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // debug('CONFIGURATION OPTIONS', opts)\n return opts;\n })\n}\n\nexport {\n jsonqlWsDefaultConstProps,\n jsonqlWsDefaultOptions,\n checkOptions\n}\n","// export the required options here to merge with the http client to do a combine check\nimport { jsonqlWsDefaultConstProps, jsonqlWsDefaultOptions } from 'jsonql-ws-client'\nimport { constProps as localConstProps } from './src/options'\n\nconst defaultOptions = jsonqlWsDefaultOptions\nconst constProps = Object.assign(jsonqlWsDefaultConstProps, localConstProps)\n\n\nexport {\n defaultOptions,\n constProps\n}\n","// this is the jsonql client with ws\n// use like import jsonqlClient from '@jsonql/client/ws'\nimport { jsonqlClientModule } from 'jsonql-client/module'\nimport { getPreConfigCheck } from 'jsonql-client/opt'\nimport jsonqlWsClient from '@jsonql/ws'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport {\n defaultOptions as wsDefaultOptions,\n constProps as wsConstProps\n} from '@jsonql/ws/opt'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-client:test:ws')\n// debugFn(jsonqlWsClient)\n\n/**\n * @param {object} Fly the fly module\n * @param {object} [config={}] developer supply options\n * @return {object} the jsonql browser client with ws socket\n * @public\n */\nexport default function createJsonqlHttpWsClient(Fly, config = {}) {\n // @NOTE it return a function to accept the config\n const fn = getPreConfigCheck(wsDefaultOptions, wsConstProps)\n const opts = fn(config)\n opts.socketClient = jsonqlWsClient\n // init the client\n return jsonqlClientModule(Fly, opts)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;ECAA;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js b/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js index c582eb93..5c6d5f77 100644 --- a/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js +++ b/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js @@ -31,14 +31,14 @@ QUnit.test('jsonql client should have http and ws clients', function(assert) { }) }) // listen to the onLogin event - client.socket.onLogin = function(ns) { + client.socket.onLogin = function testOnLoginHandler(ns) { console.info('--- onLogin ---', ns) done[3]() } - client.socket.onReady = function(ns) { + client.socket.onReady = function testOnReadyHandler(ns) { console.info('--- onReady ---', ns) - + } }) diff --git a/packages/http-client/core.js b/packages/http-client/core.js index c445a491..271b7a3a 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 L(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)}},Lt=Ut;Dt.InvalidTokenError=Lt;var Ht="[object String]";function Kt(t){return"string"==typeof t||!b(t)&&N(t)&&C(t)==Ht}var Bt=function(t){return""!==ht(t)&&Kt(t)},Gt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Vt(t){if(Bt(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!Kt(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 Bt;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!(!Le(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(!Le(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(!Le(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(!Le(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,Li=di.create,Hi=di.slice,Ki=function(){var t=Li(Bi,{_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 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,Ui(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Hi(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,Ki,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),this.__userdata__=null}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.__userdata__=this.decoder(t),this.jsonqlUserdata=this.__userdata__},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,{token:t,userdata:this.__userdata__}},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),Kt(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(Kt(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){var e=t.token,n=t.userdata;return r.$trigger("login",e),n}))}),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(t){void 0===t&&(t=null),e.postLogoutAction("continue",t),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.6",o.getLogger=function(e){return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return Reflect.apply(t.log,t,[e].concat(r))}},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)}})); +!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 L(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)}},Lt=Ut;Dt.InvalidTokenError=Lt;var Ht="[object String]";function Kt(t){return"string"==typeof t||!b(t)&&N(t)&&C(t)==Ht}var Bt=function(t){return""!==ht(t)&&Kt(t)},Gt=function(t){void 0===t&&(t=!1);var e=Date.now();return t?Math.floor(e/1e3):e};function Vt(t){if(Bt(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!Kt(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 Bt;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!(!Le(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(!Le(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(!Le(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(!Le(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,Li=di.create,Hi=di.slice,Ki=function(){var t=Li(Bi,{_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 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,Ui(this,(function(){e.apply(this,arguments),this.off(r)})))},fire:function(t){var e=Hi(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,Ki,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;t.splice(0,n),Reflect.apply(console[r[n]],console,t)}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Vt),this.__userdata__=null}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.__userdata__=this.decoder(t),this.jsonqlUserdata=this.__userdata__},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,{token:t,userdata:this.__userdata__}},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),Kt(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(Kt(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){var e=t.token,n=t.userdata;return r.$trigger("login",e),n}))}),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(t){void 0===t&&(t=null),e.postLogoutAction("continue",t),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.7",o.getLogger=function(e){return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return Reflect.apply(t.log,t,[e].concat(r))}},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/dist/jsonql-client.static.js b/packages/http-client/dist/jsonql-client.static.js index 12b65e30..4c80a6a6 100644 --- a/packages/http-client/dist/jsonql-client.static.js +++ b/packages/http-client/dist/jsonql-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="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){var e=t.token,n=t.userdata;return r.$trigger("login",e),n}))}),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(t){void 0===t&&(t=null),e.postLogoutAction("continue",t),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.6",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),this.__userdata__=null}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.__userdata__=this.decoder(t),this.jsonqlUserdata=this.__userdata__},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,{token:t,userdata:this.__userdata__}},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)}})); +!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){var e=t.token,n=t.userdata;return r.$trigger("login",e),n}))}),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(t){void 0===t&&(t=null),e.postLogoutAction("continue",t),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.7",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;t.splice(0,n),Reflect.apply(console[r[n]],console,t)}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=ki),this.__userdata__=null}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.__userdata__=this.decoder(t),this.jsonqlUserdata=this.__userdata__},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,{token:t,userdata:this.__userdata__}},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.umd.js b/packages/http-client/dist/jsonql-client.umd.js index 8c3132dd..cd645a31 100644 --- a/packages/http-client/dist/jsonql-client.umd.js +++ b/packages/http-client/dist/jsonql-client.umd.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).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 U="[object Object]",D=Function.prototype,L=Object.prototype,H=D.toString,B=L.hasOwnProperty,K=H.call(Object);function G(t){if(!J(t)||M(t)!=U)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&&H.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 Ut=function(t,e){return void 0===e&&(e={}),It(e)?Promise.resolve(e):t.getContract()},Dt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function Lt(t){this.message=t}Lt.prototype=new Error,Lt.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 Lt("'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 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(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 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,Ue=Je?(Ne=Je,function(t){return Ne(t)}):function(t){return J(t)&&$e(t.length)&&!!ze[M(t)]},De=Object.prototype.hasOwnProperty;function Le(t,e){var r=S(t),n=!r&&Oe(t),o=!r&&!n&&xe(t),i=!r&&!n&&!o&&Ue(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)?Le(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||!Li(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:Ui,remove:Di,clearAll:function(){Ui((function(t,e){Di(e)}))}},Ji=bi.Global.document;function Ui(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 Di(t){t&&Li(t)&&(Ji.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Li(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Ji.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 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=[Hi,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=[Hi,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),this.__userdata__=null}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.__userdata__=this.decoder(t),this.jsonqlUserdata=this.__userdata__},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,{token:t,userdata:this.__userdata__}},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){var e=t.token,n=t.userdata;return r.$trigger("login",e),n}))}),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(t){void 0===t&&(t=null),e.postLogoutAction("continue",t),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.6",o.getLogger=function(e){return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return Reflect.apply(t.log,t,[e].concat(r))}},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 Ut(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)}})); +!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 U="[object Object]",D=Function.prototype,L=Object.prototype,H=D.toString,B=L.hasOwnProperty,K=H.call(Object);function G(t){if(!J(t)||M(t)!=U)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&&H.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 Ut=function(t,e){return void 0===e&&(e={}),It(e)?Promise.resolve(e):t.getContract()},Dt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function Lt(t){this.message=t}Lt.prototype=new Error,Lt.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 Lt("'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 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(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 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,Ue=Je?(Ne=Je,function(t){return Ne(t)}):function(t){return J(t)&&$e(t.length)&&!!ze[M(t)]},De=Object.prototype.hasOwnProperty;function Le(t,e){var r=S(t),n=!r&&Oe(t),o=!r&&!n&&xe(t),i=!r&&!n&&!o&&Ue(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)?Le(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||!Li(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:Ui,remove:Di,clearAll:function(){Ui((function(t,e){Di(e)}))}},Ji=bi.Global.document;function Ui(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 Di(t){t&&Li(t)&&(Ji.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Li(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Ji.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 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=[Hi,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=[Hi,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;t.splice(0,n),Reflect.apply(console[r[n]],console,t)}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=Zt),this.__userdata__=null}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.__userdata__=this.decoder(t),this.jsonqlUserdata=this.__userdata__},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,{token:t,userdata:this.__userdata__}},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){var e=t.token,n=t.userdata;return r.$trigger("login",e),n}))}),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(t){void 0===t&&(t=null),e.postLogoutAction("continue",t),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.7",o.getLogger=function(e){return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return Reflect.apply(t.log,t,[e].concat(r))}},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 Ut(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/package.json b/packages/http-client/package.json index af435387..de6dad2d 100755 --- a/packages/http-client/package.json +++ b/packages/http-client/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-client", - "version": "1.5.6", + "version": "1.5.7", "description": "jsonql http browser client using Fly.js", "main": "core.js", "module": "index.js", diff --git a/packages/http-client/src/base/base-cls.js b/packages/http-client/src/base/base-cls.js index 798cc4d4..21de43d8 100644 --- a/packages/http-client/src/base/base-cls.js +++ b/packages/http-client/src/base/base-cls.js @@ -26,13 +26,16 @@ export default class JsonqlBaseClient extends AuthCls { } /** - * simple log + * simple log control by the debugOn option + * @param {array<*>} args + * @return {void} */ log(...args) { if (this.opts.debugOn === true) { const fns = ['info', 'error'] const idx = (args[0] === LOG_ERROR_SWITCH) ? 1 : 0 - Reflect.apply(console[fns[idx]], console, args.splice(0, idx)) + args.splice(0, idx) + Reflect.apply(console[fns[idx]], console, args) } } diff --git a/packages/http-client/src/core/jsonql-api-generator.js b/packages/http-client/src/core/jsonql-api-generator.js index 514ec3d2..a53d0e9a 100644 --- a/packages/http-client/src/core/jsonql-api-generator.js +++ b/packages/http-client/src/core/jsonql-api-generator.js @@ -46,7 +46,7 @@ const generator = (jsonqlInstance, config, contract, ee) => { jsonqlInstance.profileIndex = idx } // new in 1.5.1 to return different profiles - client.getProfiles = (idx = false) => jsonqlInstance.getProfiles(idx); + client.getProfiles = (idx = false) => jsonqlInstance.getProfiles(idx) } // this will pass to the ws-client if needed // client.eventEmitter = ee; @@ -67,13 +67,13 @@ const generator = (jsonqlInstance, config, contract, ee) => { client.persistDel = (key = false) => {} } // this is for the ws to use later - but this could be dangerous because it's expose the internal - client.eventEmitter = ee; - client.version = '__VERSION__'; + client.eventEmitter = ee + client.version = '__VERSION__' // use this method then we can hook into the debugOn at the same time // 1.5.2 change it to a getter to return a method, pass a name to id which one is which - client.getLogger = (name) => (...args) => Reflect.apply(jsonqlInstance.log, jsonqlInstance, [name].concat(args)) + client.getLogger = (name) => (...args) => Reflect.apply(jsonqlInstance.log, jsonqlInstance, [name, ...args]) // output - return client; + return client } // export export default generator diff --git a/packages/http-client/static.js b/packages/http-client/static.js index adeb1efb..8edf0968 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}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){var e=t.token,n=t.userdata;return r.$trigger("login",e),n}))}),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(t){void 0===t&&(t=null),e.postLogoutAction("continue",t),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.6",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),this.__userdata__=null}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.__userdata__=this.decoder(t),this.jsonqlUserdata=this.__userdata__},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,{token:t,userdata:this.__userdata__}},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}})); +!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){var e=t.token,n=t.userdata;return r.$trigger("login",e),n}))}),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(t){void 0===t&&(t=null),e.postLogoutAction("continue",t),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.7",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;t.splice(0,n),Reflect.apply(console[r[n]],console,t)}},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){t.call(this,e),e.enableAuth&&(this.setDecoder=mi),this.__userdata__=null}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.__userdata__=this.decoder(t),this.jsonqlUserdata=this.__userdata__},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,{token:t,userdata:this.__userdata__}},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/tests/qunit/tests/base-test.js b/packages/http-client/tests/qunit/tests/base-test.js index 49912693..5c7cbb08 100644 --- a/packages/http-client/tests/qunit/tests/base-test.js +++ b/packages/http-client/tests/qunit/tests/base-test.js @@ -1,6 +1,7 @@ // The basic test copy from main.test.js QUnit.test('jsonqlClient should able to connect to server', function(assert) { + var done1 = assert.async() var done2 = assert.async() var done3 = assert.async() -- Gitee