UNPKG

@hsui/sdk

Version:

Hundsun frontend framework JSSDK

1,492 lines (1,354 loc) 209 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sdk = {})); }(this, (function (exports) { 'use strict'; var errors = { INVALID_KEY: 'invalid ${ key }', INVALID_PARAMETERS: 'invalid parameters', INVALID_REQUEST: 'invalid request', INVALID_SDK_CALL: 'invalid sdk call ${ method }', NOT_FOUND: '${ key } not found', UNKNOWN_ERROR: 'unknown error' }; function runningError() { var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'UNKNOWN_ERROR'; var payload = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (errors.hasOwnProperty(type)) { return tpl(errors[type])(payload); } return tpl(errors['UNKNOWN_ERROR'])(payload); } function tpl(string) { return function (params) { Object.keys(params).forEach(function (key) { string = string.replace('${ ' + key + ' }', params[key]); }); return string; }; } function _typeof$2(obj) { "@babel/helpers - typeof"; return _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$2(obj); } function isObject$2(value) { var type = _typeof$2(value); return value != null && (type == 'object' || type == 'function'); } /** * Redux isPlainObject */ function isPlainObject$1(obj) { if (_typeof$2(obj) !== 'object' || obj === null) return false; var proto = obj; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(obj) === proto; } function getPlatform() { if (isUcf()) { return 'ucf'; } else { return 'web'; } } function isUcf() { var pattern = /ucf/; if (navigator && pattern.test(navigator.userAgent.toLowerCase())) { // 增加跨平台的保护,避免客户端没有实现 ucf 的跨平台接口 return window.usdk ? true : false; } else { return false; } } function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty$1(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var isArray$1 = Array.isArray; function report(error_code, error_message, extra) { return _objectSpread2({ error_code: error_code, error_message: isArray$1(error_message) && error_message.length ? error_message[0] : error_message }, isPlainObject$1(extra) ? extra : {}); } var ajaxSchema = { type: 'object', properties: { url: { type: 'string', required: true }, method: { type: 'string', enum: ['get', 'post'] }, data: { type: ['string', 'number', 'object'] }, timeout: { type: 'number' }, headers: { type: 'object' } } }; var storageSchema = { type: 'object', properties: { key: { type: 'string', required: true }, value: { type: ['string', 'number', 'object'] }, scope: { type: 'string' } } }; function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } // 格式化要获取的对象属性参数 function compilePointer(pointer) { if (typeof pointer === 'string') { pointer = pointer.split('/'); if (pointer[0] === '') return pointer.slice(1); throw new Error('Invalid JSON pointer.'); } else if (Array.isArray(pointer)) { var _iterator = _createForOfIteratorHelper(pointer), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var part = _step.value; if (typeof part !== 'string' && typeof part !== 'number') { throw new Error('Invalid JSON pointer. Must be of type string or number.'); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return pointer; } throw new Error('Invalid JSON pointer.'); } function get(obj, pointer) { if (_typeof$2(obj) !== 'object') throw new Error('Invalid input object.'); pointer = compilePointer(pointer); var len = pointer.length; if (len === 0) return obj; for (var p = 0; p < len;) { obj = obj[pointer[p++]]; if (len === p) return obj; if (_typeof$2(obj) !== 'object' || obj === null) return undefined; } } var jsonpointer = { get: get }; /** 根据传入的 schema 校验对象是否符合要求 * 校验对象支持 object 类型,对象的属性支持 string number object array 类型 * import validator from './is-json-valid'; * const it = validator(schema); 返回一个函数 * it(data); 传入需要校验的对象 * it.errors; */ function compile(schema, opts) { var validate = function validate(data) { validate.errors = null; var type = schema.type; var errors = []; // 判断对象类型的参数 if (type === 'object') { var dataType = _typeof$2(data); dataType === 'object' && (dataType = Array.isArray(data) ? 'array' : 'object'); if (dataType !== 'object') { errors.push({ field: 'data', message: 'is the wrong type', schemaPath: [], type: 'object', value: data }); } else { var schemaPropertiesKeys = Object.keys(schema.properties); // 循环 schema 的 key for (var i = 0; i < schemaPropertiesKeys.length; i++) { var schemaItemRules = schema.properties[schemaPropertiesKeys[i]]; var itemType = schemaItemRules.type, itemRequired = schemaItemRules.required, itemEnum = schemaItemRules.enum; // 如果该属性是必需项,但是未定义该属性,需要抛出错误 if (itemRequired === true && !data.hasOwnProperty(schemaPropertiesKeys[i])) { errors.push({ field: schemaPropertiesKeys[i], message: 'is required', schemaPath: ['properties', schemaPropertiesKeys[i]], type: itemType, value: undefined }); continue; } // 如果属性存在判断类型是否符合 if (itemType && data.hasOwnProperty(schemaPropertiesKeys[i])) { // 支持校验的数据类型 string number object array var dataItemType = _typeof$2(data[schemaPropertiesKeys[i]]); if (dataItemType === 'object') { dataItemType = Array.isArray(data[schemaPropertiesKeys[i]]) ? 'array' : 'object'; } // 对于 undefined 类型数据,认为是无效值不校验 if (dataItemType !== 'undefined' && !(itemType === dataItemType || itemType.indexOf(dataItemType) !== -1)) { errors.push({ field: schemaPropertiesKeys[i], message: 'is the wrong type', schemaPath: ['properties', schemaPropertiesKeys[i]], type: itemType, value: data[schemaPropertiesKeys[i]] }); continue; } } // 如果属性存在且规定取值范围判断值是否符合 if (itemEnum && data.hasOwnProperty(schemaPropertiesKeys[i]) && itemEnum.indexOf(data[schemaPropertiesKeys[i]]) === -1) { errors.push({ field: schemaPropertiesKeys[i], message: 'must be an enum value', schemaPath: ['properties', schemaPropertiesKeys[i]], type: itemType, value: data[schemaPropertiesKeys[i]] }); continue; } } } } // 如果有不符合规则的情况,吧错误信息挂载函数上 errors.length > 0 && (validate.errors = errors); }; return validate; } function validator$2 (schema, opts) { if (typeof schema === 'string') schema = JSON.parse(schema); return compile(schema); } function validate(schema, data) { var it = validator$2(schema); it(data); var errors = it.errors; if (errors) { errors = errors.map(function (_ref) { var field = _ref.field, message = _ref.message; _ref.value; var type = _ref.type, schemaPath = _ref.schemaPath; var property = field.replace('data.', ''); if (Array.isArray(type)) { type = type.join(); } if (message === 'is required') { return "".concat(property, " is required"); } if (message === 'is the wrong type') { return "".concat(property, " is the wrong type, expect ").concat(type); } if (message === 'must be an enum value') { var enumvalue = jsonpointer.get(schema, schemaPath.concat('enum')).join(); return "".concat(property, " must be one of ").concat(enumvalue); } return message; }); } return errors; } function _regeneratorRuntime() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof$2(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function setConfig$2() { // 无需实现 } function ajax$2(_x) { return _ajax.apply(this, arguments); } function _ajax() { _ajax = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(options) { return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return new Promise(function (resolve, reject) { var validationError = validate(ajaxSchema, options); if (validationError) { throw report('-1', validationError); } var url = options.url, _options$method = options.method, method = _options$method === void 0 ? 'post' : _options$method, _options$data = options.data, data = _options$data === void 0 ? {} : _options$data, _options$timeout = options.timeout, timeout = _options$timeout === void 0 ? 5000 : _options$timeout, _options$headers = options.headers, headers = _options$headers === void 0 ? {} : _options$headers; var requestConfig = { url: url, method: method, data: data, timeout: timeout, headers: headers // request headers }; try { usdk.sendAsync(requestConfig, function (result) { if (result) { var _JSON$parse = JSON.parse(result), _data = _JSON$parse.data, info = _JSON$parse.info; if (info) { var error_code = info.error_code, error_message = info.error_message; if (error_code == 0) { if (_data) { _data = JSON.parse(_data); // 这里需要再做一次转换 var _result4 = {}; if (options.forceWrappedInData) { _result4.data = _data; } else { _result4 = _data; } if (isPlainObject$1(_result4)) { // request config if (options.includeRequestConfig) { _result4.config = requestConfig; } } resolve(_result4); } else { reject(report('-1', runningError('INVALID_KEY', { key: 'data' }))); } } else { reject(report(error_code, error_message)); } } else { reject(report('-1', runningError('INVALID_KEY', { key: 'info' }))); } } else { reject(report('-1', runningError('INVALID_SDK_CALL', { method: 'sendAsync' }))); } }); } catch (error) { reject(report('-1', runningError('INVALID_SDK_CALL', { method: 'sendAsync' }))); } }); case 2: return _context4.abrupt("return", _context4.sent); case 3: case "end": return _context4.stop(); } }, _callee4); })); return _ajax.apply(this, arguments); } var storage$2 = { setData: function setData(options) { return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: _context.next = 2; return new Promise(function (resolve, reject) { var validationError = validate(storageSchema, options); if (validationError) { throw report('-1', validationError); } var key = options.key, value = options.value, scope = options.scope; try { usdk.writeData({ key: key, value: value, scope: scope }, function (result) { if (result) { result = JSON.parse(result); var _result = result, data = _result.data, info = _result.info; if (info) { var error_code = info.error_code, error_message = info.error_message; if (error_code == 0) { resolve(); } else { reject(report(error_code, error_message)); } } else { reject(report('-1', runningError('INVALID_KEY', { key: 'info' }))); } } else { reject(report('-1', runningError('INVALID_SDK_CALL', { method: 'writeData' }))); } }); } catch (error) { reject(report('-1', runningError('INVALID_SDK_CALL', { method: 'writeData' }))); } }); case 2: return _context.abrupt("return", _context.sent); case 3: case "end": return _context.stop(); } }, _callee); }))(); }, getData: function getData(options) { return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return new Promise(function (resolve, reject) { var validationError = validate(storageSchema, options); if (validationError) { throw report('-1', validationError); } var key = options.key, scope = options.scope; try { usdk.readData({ key: key, scope: scope }, function (result) { if (result) { result = JSON.parse(result); var _result2 = result, data = _result2.data, info = _result2.info; if (info) { var error_code = info.error_code, error_message = info.error_message; if (error_code == 0) { if (data) { try { data = JSON.parse(data); } catch (error) { // may not be a json string } resolve(data); } else { reject(report('-1', runningError('INVALID_KEY', { key: 'data' }))); } } else { reject(report(error_code, error_message)); } } else { reject(report('-1', runningError('INVALID_KEY', { key: 'info' }))); } } else { reject(report('-1', runningError('INVALID_SDK_CALL', { method: 'readData' }))); } }); } catch (error) { reject(report('-1', runningError('INVALID_SDK_CALL', { method: 'readData' }))); } }); case 2: return _context2.abrupt("return", _context2.sent); case 3: case "end": return _context2.stop(); } }, _callee2); }))(); }, deleteData: function deleteData(options) { return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return new Promise(function (resolve, reject) { var validationError = validate(storageSchema, options); if (validationError) { throw report('-1', validationError); } var key = options.key, scope = options.scope; try { usdk.deleteData({ key: key, scope: scope }, function (result) { if (result) { result = JSON.parse(result); var _result3 = result, data = _result3.data, info = _result3.info; if (info) { var error_code = info.error_code, error_message = info.error_message; if (error_code == 0) { resolve(); } else { reject(report(error_code, error_message)); } } else { reject(report('-1', runningError('INVALID_KEY', { key: 'info' }))); } } else { reject(report('-1', runningError('INVALID_SDK_CALL', { method: 'deleteData' }))); } }); } catch (error) { reject(report('-1', runningError('INVALID_SDK_CALL', { method: 'deleteData' }))); } }); case 2: return _context3.abrupt("return", _context3.sent); case 3: case "end": return _context3.stop(); } }, _callee3); }))(); } }; var ucfSdk = /*#__PURE__*/Object.freeze({ __proto__: null, setConfig: setConfig$2, ajax: ajax$2, storage: storage$2 }); var axios$2 = {exports: {}}; var bind$2 = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; var bind$1 = bind$2; // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; // eslint-disable-next-line func-names var kindOf = (function(cache) { // eslint-disable-next-line func-names return function(thing) { var str = toString.call(thing); return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); }; })(Object.create(null)); function kindOfTest(type) { type = type.toLowerCase(); return function isKindOf(thing) { return kindOf(thing) === type; }; } /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return Array.isArray(val); } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is a Buffer * * @param {Object} val The value to test * @returns {boolean} True if value is a Buffer, otherwise false */ function isBuffer(val) { return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); } /** * Determine if a value is an ArrayBuffer * * @function * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ var isArrayBuffer = kindOfTest('ArrayBuffer'); /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { var result; if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { result = ArrayBuffer.isView(val); } else { result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); } return result; } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber$1(val) { return typeof val === 'number'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject$1(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a plain Object * * @param {Object} val The value to test * @return {boolean} True if value is a plain Object, otherwise false */ function isPlainObject(val) { if (kindOf(val) !== 'object') { return false; } var prototype = Object.getPrototypeOf(val); return prototype === null || prototype === Object.prototype; } /** * Determine if a value is a Date * * @function * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ var isDate = kindOfTest('Date'); /** * Determine if a value is a File * * @function * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ var isFile = kindOfTest('File'); /** * Determine if a value is a Blob * * @function * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ var isBlob = kindOfTest('Blob'); /** * Determine if a value is a FileList * * @function * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ var isFileList = kindOfTest('FileList'); /** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ function isFunction(val) { return toString.call(val) === '[object Function]'; } /** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */ function isStream(val) { return isObject$1(val) && isFunction(val.pipe); } /** * Determine if a value is a FormData * * @param {Object} thing The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(thing) { var pattern = '[object FormData]'; return thing && ( (typeof FormData === 'function' && thing instanceof FormData) || toString.call(thing) === pattern || (isFunction(thing.toString) && thing.toString() === pattern) ); } /** * Determine if a value is a URLSearchParams object * @function * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ var isURLSearchParams = kindOfTest('URLSearchParams'); /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * navigator.product -> 'ReactNative' * nativescript * navigator.product -> 'NativeScript' or 'NS' */ function isStandardBrowserEnv() { if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { return false; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } if (isArray(obj)) { // Iterate over array values for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (isPlainObject(result[key]) && isPlainObject(val)) { result[key] = merge(result[key], val); } else if (isPlainObject(val)) { result[key] = merge({}, val); } else if (isArray(val)) { result[key] = val.slice(); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */ function extend$1(a, b, thisArg) { forEach(b, function assignValue(val, key) { if (thisArg && typeof val === 'function') { a[key] = bind$1(val, thisArg); } else { a[key] = val; } }); return a; } /** * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * * @param {string} content with BOM * @return {string} content value without BOM */ function stripBOM(content) { if (content.charCodeAt(0) === 0xFEFF) { content = content.slice(1); } return content; } /** * Inherit the prototype methods from one constructor into another * @param {function} constructor * @param {function} superConstructor * @param {object} [props] * @param {object} [descriptors] */ function inherits(constructor, superConstructor, props, descriptors) { constructor.prototype = Object.create(superConstructor.prototype, descriptors); constructor.prototype.constructor = constructor; props && Object.assign(constructor.prototype, props); } /** * Resolve object with deep prototype chain to a flat object * @param {Object} sourceObj source object * @param {Object} [destObj] * @param {Function} [filter] * @returns {Object} */ function toFlatObject(sourceObj, destObj, filter) { var props; var i; var prop; var merged = {}; destObj = destObj || {}; do { props = Object.getOwnPropertyNames(sourceObj); i = props.length; while (i-- > 0) { prop = props[i]; if (!merged[prop]) { destObj[prop] = sourceObj[prop]; merged[prop] = true; } } sourceObj = Object.getPrototypeOf(sourceObj); } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); return destObj; } /* * determines whether a string ends with the characters of a specified string * @param {String} str * @param {String} searchString * @param {Number} [position= 0] * @returns {boolean} */ function endsWith(str, searchString, position) { str = String(str); if (position === undefined || position > str.length) { position = str.le