UNPKG

@pisell/pisellos

Version:

一个可扩展的前端模块化SDK框架,支持插件系统

603 lines (584 loc) 38.1 kB
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(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(o, minLen); } function _arrayLikeToArray(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 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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _isNativeFunction(fn) { try { return Function.toString.call(fn).indexOf("[native code]") !== -1; } catch (e) { return typeof fn === "function"; } } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /** * RequestPlugin 接口定义 */ export var RequestModeENUM = /*#__PURE__*/function (RequestModeENUM) { RequestModeENUM["LOCAL"] = "local"; RequestModeENUM["REMOTE"] = "remote"; RequestModeENUM["LOCAL_REMOTE"] = "local_remote"; RequestModeENUM["REMOTE_LOCAL"] = "remote_local"; RequestModeENUM["OS_SERVER"] = "os_server"; return RequestModeENUM; }({}); // 请求模式 /** * 请求配置 */ /** * 响应接口 */ /** * 请求错误 */ export var RequestError = /*#__PURE__*/function (_Error) { _inherits(RequestError, _Error); var _super = _createSuper(RequestError); function RequestError(message, config, request, response) { var _this; _classCallCheck(this, RequestError); _this = _super.call(this, message); _defineProperty(_assertThisInitialized(_this), "response", void 0); _defineProperty(_assertThisInitialized(_this), "request", void 0); _defineProperty(_assertThisInitialized(_this), "config", void 0); _this.name = 'RequestError'; _this.config = config; _this.request = request; _this.response = response; return _this; } return _createClass(RequestError); }( /*#__PURE__*/_wrapNativeSuper(Error)); /** * RequestPlugin 实现 */ var RequestPluginImpl = /*#__PURE__*/function () { function RequestPluginImpl() { _classCallCheck(this, RequestPluginImpl); _defineProperty(this, "name", 'request'); _defineProperty(this, "version", '1.0.0'); _defineProperty(this, "core", null); /** * 默认请求选项 */ _defineProperty(this, "defaultOptions", { method: 'GET', headers: { 'Content-Type': 'application/json' }, timeout: 30000, responseType: 'json' }); /** * 全局拦截器 */ _defineProperty(this, "interceptors", { request: [], response: [], error: [] }); } _createClass(RequestPluginImpl, [{ key: "initialize", value: // 初始化方法 function initialize() { this.core = globalThis.pisellOS; console.log('[RequestPlugin] 初始化完成'); } // 销毁方法 }, { key: "destroy", value: function destroy() { console.log('[RequestPlugin] 已销毁'); } /** * 添加请求拦截器 */ }, { key: "addRequestInterceptor", value: function addRequestInterceptor(interceptor) { this.interceptors.request.push(interceptor); } /** * 添加响应拦截器 */ }, { key: "addResponseInterceptor", value: function addResponseInterceptor(interceptor) { this.interceptors.response.push(interceptor); } /** * 添加错误拦截器 */ }, { key: "addErrorInterceptor", value: function addErrorInterceptor(interceptor) { this.interceptors.error.push(interceptor); } /** * GET 请求 */ }, { key: "get", value: function get(url) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return this.request(_objectSpread(_objectSpread({}, options), {}, { url: url, method: 'GET' })); } /** * POST 请求 */ }, { key: "post", value: function post(url, data) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return this.request(_objectSpread(_objectSpread({}, options), {}, { url: url, method: 'POST', data: data })); } /** * PUT 请求 */ }, { key: "put", value: function put(url, data) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return this.request(_objectSpread(_objectSpread({}, options), {}, { url: url, method: 'PUT', data: data })); } /** * DELETE 请求 */ }, { key: "delete", value: function _delete(url) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return this.request(_objectSpread(_objectSpread({}, options), {}, { url: url, method: 'DELETE' })); } /** * 通用请求方法 */ }, { key: "request", value: (function () { var _request = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(options) { var config, windowPlugin, _iterator, _step, _interceptor, _requestError2, _processedError2, _iterator5, _step5, _errorInterceptor2, _response, processedResponse, _iterator2, _step2, interceptor, requestError, processedError, _iterator3, _step3, errorInterceptor, _requestError, _processedError, _iterator4, _step4, _errorInterceptor; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: // 合并默认选项 config = _objectSpread(_objectSpread(_objectSpread({}, this.defaultOptions), options), {}, { headers: _objectSpread(_objectSpread({}, this.defaultOptions.headers), options.headers) }); if (!config.headers['authorization'] && this.core) { windowPlugin = this.core.getPlugin('window'); if (windowPlugin) { config.headers['authorization'] = windowPlugin.localStorage.getItem('token') || ''; } } // 应用请求拦截器 _iterator = _createForOfIteratorHelper(this.interceptors.request); _context.prev = 3; _iterator.s(); case 5: if ((_step = _iterator.n()).done) { _context.next = 43; break; } _interceptor = _step.value; _context.prev = 7; _context.next = 10; return Promise.resolve(_interceptor(config)); case 10: config = _context.sent; _context.next = 41; break; case 13: _context.prev = 13; _context.t0 = _context["catch"](7); _requestError2 = _context.t0 instanceof RequestError ? _context.t0 : new RequestError(_context.t0 instanceof Error ? _context.t0.message : '请求拦截器错误', config); // 应用错误拦截器 _processedError2 = _requestError2; _iterator5 = _createForOfIteratorHelper(this.interceptors.error); _context.prev = 18; _iterator5.s(); case 20: if ((_step5 = _iterator5.n()).done) { _context.next = 32; break; } _errorInterceptor2 = _step5.value; _context.prev = 22; _context.next = 25; return Promise.resolve(_errorInterceptor2(_processedError2)); case 25: _processedError2 = _context.sent; _context.next = 30; break; case 28: _context.prev = 28; _context.t1 = _context["catch"](22); case 30: _context.next = 20; break; case 32: _context.next = 37; break; case 34: _context.prev = 34; _context.t2 = _context["catch"](18); _iterator5.e(_context.t2); case 37: _context.prev = 37; _iterator5.f(); return _context.finish(37); case 40: throw _processedError2; case 41: _context.next = 5; break; case 43: _context.next = 48; break; case 45: _context.prev = 45; _context.t3 = _context["catch"](3); _iterator.e(_context.t3); case 48: _context.prev = 48; _iterator.f(); return _context.finish(48); case 51: _context.prev = 51; _context.next = 54; return this.performRequest(config); case 54: _response = _context.sent; // 应用响应拦截器 processedResponse = _response; _iterator2 = _createForOfIteratorHelper(this.interceptors.response); _context.prev = 57; _iterator2.s(); case 59: if ((_step2 = _iterator2.n()).done) { _context.next = 97; break; } interceptor = _step2.value; _context.prev = 61; _context.next = 64; return Promise.resolve(interceptor(processedResponse)); case 64: processedResponse = _context.sent; _context.next = 95; break; case 67: _context.prev = 67; _context.t4 = _context["catch"](61); requestError = _context.t4 instanceof RequestError ? _context.t4 : new RequestError(_context.t4 instanceof Error ? _context.t4.message : '响应拦截器错误', config, null, _response); // 应用错误拦截器 processedError = requestError; _iterator3 = _createForOfIteratorHelper(this.interceptors.error); _context.prev = 72; _iterator3.s(); case 74: if ((_step3 = _iterator3.n()).done) { _context.next = 86; break; } errorInterceptor = _step3.value; _context.prev = 76; _context.next = 79; return Promise.resolve(errorInterceptor(processedError)); case 79: processedError = _context.sent; _context.next = 84; break; case 82: _context.prev = 82; _context.t5 = _context["catch"](76); case 84: _context.next = 74; break; case 86: _context.next = 91; break; case 88: _context.prev = 88; _context.t6 = _context["catch"](72); _iterator3.e(_context.t6); case 91: _context.prev = 91; _iterator3.f(); return _context.finish(91); case 94: throw processedError; case 95: _context.next = 59; break; case 97: _context.next = 102; break; case 99: _context.prev = 99; _context.t7 = _context["catch"](57); _iterator2.e(_context.t7); case 102: _context.prev = 102; _iterator2.f(); return _context.finish(102); case 105: return _context.abrupt("return", processedResponse.data); case 108: _context.prev = 108; _context.t8 = _context["catch"](51); _requestError = _context.t8 instanceof RequestError ? _context.t8 : new RequestError(_context.t8 instanceof Error ? _context.t8.message : '请求错误', config); // 应用错误拦截器 _processedError = _requestError; _iterator4 = _createForOfIteratorHelper(this.interceptors.error); _context.prev = 113; _iterator4.s(); case 115: if ((_step4 = _iterator4.n()).done) { _context.next = 127; break; } _errorInterceptor = _step4.value; _context.prev = 117; _context.next = 120; return Promise.resolve(_errorInterceptor(_processedError)); case 120: _processedError = _context.sent; _context.next = 125; break; case 123: _context.prev = 123; _context.t9 = _context["catch"](117); case 125: _context.next = 115; break; case 127: _context.next = 132; break; case 129: _context.prev = 129; _context.t10 = _context["catch"](113); _iterator4.e(_context.t10); case 132: _context.prev = 132; _iterator4.f(); return _context.finish(132); case 135: throw _processedError; case 136: case "end": return _context.stop(); } }, _callee, this, [[3, 45, 48, 51], [7, 13], [18, 34, 37, 40], [22, 28], [51, 108], [57, 99, 102, 105], [61, 67], [72, 88, 91, 94], [76, 82], [113, 129, 132, 135], [117, 123]]); })); function request(_x) { return _request.apply(this, arguments); } return request; }() /** * 执行实际的请求 * 这里实现了一个基于 fetch API 的请求 */ ) }, { key: "performRequest", value: (function () { var _performRequest = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(config) { var url, method, headers, data, params, timeout, responseType, withCredentials, fullUrl, queryString, fetchOptions, timeoutId, timeoutPromise, fetchPromise, _response2, responseHeaders, responseData, result; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: url = config.url, method = config.method, headers = config.headers, data = config.data, params = config.params, timeout = config.timeout, responseType = config.responseType, withCredentials = config.withCredentials; if (url) { _context2.next = 3; break; } throw new RequestError('URL不能为空', config); case 3: // 处理 URL 参数 fullUrl = url; if (params && Object.keys(params).length > 0) { queryString = Object.entries(params).map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], value = _ref2[1]; return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(String(value))); }).join('&'); fullUrl += (url.includes('?') ? '&' : '?') + queryString; } // 准备请求选项 fetchOptions = { method: method, headers: _objectSpread({}, headers), credentials: withCredentials ? 'include' : 'same-origin' }; // 处理请求体 if (data !== undefined && method !== 'GET' && method !== 'HEAD') { if (data instanceof FormData) { fetchOptions.body = data; // 当使用 FormData 时,删除 Content-Type,让浏览器自动设置 delete fetchOptions.headers['Content-Type']; } else if (_typeof(data) === 'object') { fetchOptions.body = JSON.stringify(data); } else { fetchOptions.body = data; } } // 处理超时 timeoutPromise = new Promise(function (_, reject) { if (timeout) { timeoutId = setTimeout(function () { reject(new RequestError("\u8BF7\u6C42\u8D85\u65F6: ".concat(timeout, "ms"), config)); }, timeout); } }); _context2.prev = 8; // 发起请求,并竞争超时 fetchPromise = typeof fetch !== 'undefined' ? fetch(fullUrl, fetchOptions) : Promise.reject(new RequestError('当前环境不支持 fetch API', config)); _context2.next = 12; return Promise.race([fetchPromise, timeoutPromise]); case 12: _response2 = _context2.sent; // 解析响应头 responseHeaders = {}; _response2.headers.forEach(function (value, key) { responseHeaders[key] = value; }); // 解析响应内容 if (!(responseType === 'json')) { _context2.next = 29; break; } _context2.prev = 16; _context2.next = 19; return _response2.json(); case 19: responseData = _context2.sent; _context2.next = 27; break; case 22: _context2.prev = 22; _context2.t0 = _context2["catch"](16); _context2.next = 26; return _response2.text(); case 26: responseData = _context2.sent; case 27: _context2.next = 58; break; case 29: if (!(responseType === 'text')) { _context2.next = 35; break; } _context2.next = 32; return _response2.text(); case 32: responseData = _context2.sent; _context2.next = 58; break; case 35: if (!(responseType === 'arraybuffer')) { _context2.next = 41; break; } _context2.next = 38; return _response2.arrayBuffer(); case 38: responseData = _context2.sent; _context2.next = 58; break; case 41: if (!(responseType === 'blob')) { _context2.next = 47; break; } _context2.next = 44; return _response2.blob(); case 44: responseData = _context2.sent; _context2.next = 58; break; case 47: _context2.prev = 47; _context2.next = 50; return _response2.json(); case 50: responseData = _context2.sent; _context2.next = 58; break; case 53: _context2.prev = 53; _context2.t1 = _context2["catch"](47); _context2.next = 57; return _response2.text(); case 57: responseData = _context2.sent; case 58: // 构建响应对象 result = { data: responseData, status: _response2.status, statusText: _response2.statusText, headers: responseHeaders, config: config }; // 处理非成功状态码 if (_response2.ok) { _context2.next = 61; break; } throw new RequestError("\u8BF7\u6C42\u5931\u8D25\uFF0C\u72B6\u6001\u7801: ".concat(_response2.status), config, fetchOptions, result); case 61: return _context2.abrupt("return", result); case 62: _context2.prev = 62; // 清除超时计时器 if (timeoutId) { clearTimeout(timeoutId); } return _context2.finish(62); case 65: case "end": return _context2.stop(); } }, _callee2, null, [[8,, 62, 65], [16, 22], [47, 53]]); })); function performRequest(_x2) { return _performRequest.apply(this, arguments); } return performRequest; }()) }]); return RequestPluginImpl; }(); export default new RequestPluginImpl();