UNPKG

@vyron/uni-network

Version:

为 uni-app 打造的基于 Promise 的 HTTP 客户端

1,099 lines (1,070 loc) 36 kB
import statuses from 'statuses-es'; import qs from 'fast-querystring'; import merge from 'lodash.merge'; const version = "0.21.4"; var __defProp$7 = Object.defineProperty; var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$4 = (obj, key, value) => __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value); const _UnError = class _UnError extends Error { constructor(message, code, config, task, response) { var _a; super(message); __publicField$4(this, "code"); __publicField$4(this, "config"); __publicField$4(this, "task"); __publicField$4(this, "response"); __publicField$4(this, "isUnError"); __publicField$4(this, "status"); __publicField$4(this, "cause"); this.name = "UnError"; this.message = message != null ? message : ""; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error().stack; } this.code = code; this.config = config; this.task = task; if (response) { this.response = response; this.status = (_a = response.status) != null ? _a : void 0; } this.isUnError = true; } toJSON() { return { message: this.message, name: this.name, // @ts-expect-error no types description: this.description, // @ts-expect-error no types number: this.number, // @ts-expect-error no types fileName: this.fileName, // @ts-expect-error no types lineNumber: this.lineNumber, // @ts-expect-error no types columnNumber: this.columnNumber, stack: this.stack, config: this.config, code: this.code, status: this.status }; } static from(error, code, config, task, response, customProps) { const urError = new _UnError(error == null ? void 0 : error.message, code, config, task, response); if (customProps) { Object.assign(urError, customProps); } return urError; } }; __publicField$4(_UnError, "ERR_FR_TOO_MANY_REDIRECTS", "ERR_FR_TOO_MANY_REDIRECTS"); __publicField$4(_UnError, "ERR_BAD_OPTION_VALUE", "ERR_BAD_OPTION_VALUE"); __publicField$4(_UnError, "ERR_BAD_OPTION", "ERR_BAD_OPTION"); __publicField$4(_UnError, "ERR_NETWORK", "ERR_NETWORK"); __publicField$4(_UnError, "ERR_DEPRECATED", "ERR_DEPRECATED"); __publicField$4(_UnError, "ERR_BAD_RESPONSE", "ERR_BAD_RESPONSE"); __publicField$4(_UnError, "ERR_BAD_REQUEST", "ERR_BAD_REQUEST"); __publicField$4(_UnError, "ERR_NOT_SUPPORT", "ERR_NOT_SUPPORT"); __publicField$4(_UnError, "ERR_INVALID_URL", "ERR_INVALID_URL"); __publicField$4(_UnError, "ERR_CANCELED", "ERR_CANCELED"); __publicField$4(_UnError, "ECONNABORTED", "ECONNABORTED"); __publicField$4(_UnError, "ETIMEDOUT", "ETIMEDOUT"); let UnError = _UnError; var __defProp$6 = Object.defineProperty; var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$3 = (obj, key, value) => __defNormalProp$6(obj, key + "" , value); class UnCanceledError extends UnError { constructor(message, config, task) { super(message != null ? message : "canceled"); __publicField$3(this, "isUnCanceledError", true); this.name = "CanceledError"; this.message = message != null ? message : "canceled"; this.code = UnError.ERR_CANCELED; this.config = config; this.task = task; } } UnCanceledError.prototype.isUnCanceledError = true; const settle = (resolve, reject, response) => { var _a; const validateStatus = (_a = response == null ? void 0 : response.config) == null ? void 0 : _a.validateStatus; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { reject( new UnError( `Request failed with status code ${response.status}`, [UnError.ERR_BAD_REQUEST, UnError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.task, response ) ); } }; const combineUrls = (baseUrl, relativeUrl) => { return relativeUrl ? `${baseUrl.replace(/\/?\/$/, "")}/${relativeUrl.replace(/^\/+/, "")}` : baseUrl; }; const isAbsoluteUrl = (url) => { return /^([a-z][\d+.a-z-]*:)\/\//i.test(url); }; const buildFullPath = (baseUrl, requestedUrl, allowAbsoluteUrls) => { const isRelativeUrl = !isAbsoluteUrl(requestedUrl); if (baseUrl && (isRelativeUrl || !allowAbsoluteUrls)) { return combineUrls(baseUrl, requestedUrl); } return requestedUrl; }; const buildUrl = (url, params, paramsSerializer) => { if (!params) { return url; } let newUrl = url; const hashIndex = url.indexOf("#"); if (hashIndex !== -1) { newUrl = newUrl.slice(0, hashIndex); } const serializerParams = paramsSerializer ? paramsSerializer(params) : Object.prototype.toString.call(params).includes("URLSearchParams") ? params.toString() : qs.stringify(params); if (serializerParams) { newUrl += (newUrl.includes("?") ? "&" : "?") + serializerParams; } return newUrl; }; const buildDownloadConfig = (config) => { var _a, _b, _c; return { url: buildUrl( buildFullPath( (_a = config.baseUrl) != null ? _a : "", (_b = config.url) != null ? _b : "", (_c = config.allowAbsoluteUrls) != null ? _c : true ), config.params, config.paramsSerializer ), header: config.headers, timeout: config.timeout, filePath: config.filePath }; }; const buildRequestConfig = (config) => { var _a, _b, _c, _d, _e; return { url: buildUrl( buildFullPath( (_a = config.baseUrl) != null ? _a : "", (_b = config.url) != null ? _b : "", (_c = config.allowAbsoluteUrls) != null ? _c : true ), config.params, config.paramsSerializer ), data: config.data, header: config.headers, method: (_e = (_d = config.method) == null ? void 0 : _d.toUpperCase()) != null ? _e : "GET", timeout: config.timeout, dataType: config.dataType, responseType: config.responseType, enableHttp2: config.enableHttp2, enableQuic: config.enableQuic, enableCache: config.enableCache, enableHttpDNS: config.enableHttpDNS, httpDNSServiceId: config.httpDNSServiceId, enableChunked: config.enableChunked, forceCellularNetwork: config.forceCellularNetwork, sslVerify: config.sslVerify, withCredentials: config.withCredentials, firstIpv4: config.firstIpv4 }; }; const buildUploadConfig = (config) => { var _a, _b, _c; return { url: buildUrl( buildFullPath( (_a = config.baseUrl) != null ? _a : "", (_b = config.url) != null ? _b : "", (_c = config.allowAbsoluteUrls) != null ? _c : true ), config.params, config.paramsSerializer ), files: config.files, fileType: config.fileType, file: config.file, filePath: config.filePath, name: config.name, header: config.headers, timeout: config.timeout, formData: config.formData }; }; function forEach(obj, fn, { allOwnKeys = false } = {}) { if (obj === null || obj === void 0) return; let i; let l; const object = typeof obj !== "object" ? [obj] : obj; if (Array.isArray(object)) { for (i = 0, l = object.length; i < l; i++) { fn.call(null, object[i], i, object); } } else { const keys = allOwnKeys ? Object.getOwnPropertyNames(object).filter( (key2) => key2 !== "constructor" && !key2.startsWith("_") ) : Object.keys(object); const len = keys.length; let key; for (i = 0; i < len; i++) { key = keys[i]; fn.call(null, object[key], key, object); } } } const extend = (a, b, thisArg, { allOwnKeys = false } = {}) => { forEach( b, (val, key) => { a[key] = thisArg && typeof val === "function" ? val.bind(thisArg) : val; }, { allOwnKeys } ); return a; }; function mergeConfig(config1, config2) { return merge({}, config1 != null ? config1 : {}, config2 != null ? config2 : {}); } var __defProp$5 = Object.defineProperty; var __defProps$3 = Object.defineProperties; var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols; var __hasOwnProp$3 = Object.prototype.hasOwnProperty; var __propIsEnum$3 = Object.prototype.propertyIsEnumerable; var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$3 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$3.call(b, prop)) __defNormalProp$5(a, prop, b[prop]); if (__getOwnPropSymbols$3) for (var prop of __getOwnPropSymbols$3(b)) { if (__propIsEnum$3.call(b, prop)) __defNormalProp$5(a, prop, b[prop]); } return a; }; var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b)); const downloadAdapter = (config) => new Promise((resolve, reject) => { var _a, _b, _c, _d; const { onHeadersReceived, cancelToken, signal } = config; const onProgressUpdate = (_c = (_b = (_a = config == null ? void 0 : config.onDownloadProgress) != null ? _a : config == null ? void 0 : config.onDownloadProgressUpdate) != null ? _b : config == null ? void 0 : config.onProgress) != null ? _c : config == null ? void 0 : config.onProgressUpdate; const downloadConfig = buildDownloadConfig(config); let onCanceled; const done = () => { cancelToken == null ? void 0 : cancelToken.unsubscribe(onCanceled); signal == null ? void 0 : signal.removeEventListener("abort", onCanceled); }; let task; task = uni.downloadFile(__spreadProps$3(__spreadValues$3({}, downloadConfig), { success: (res) => { var _a2, _b2, _c2, _d2, _e; let statusText; try { statusText = (_a2 = statuses(res == null ? void 0 : res.statusCode)) == null ? void 0 : _a2.toString(); } catch (_) { statusText = void 0; } const response = { // @ts-expect-error no types errMsg: (_d2 = (_c2 = (_b2 = res == null ? void 0 : res.errMsg) != null ? _b2 : res == null ? void 0 : res.errmsg) != null ? _c2 : res == null ? void 0 : res.msg) != null ? _d2 : res == null ? void 0 : res.message, // @ts-expect-error no types errno: res == null ? void 0 : res.errno, tempFilePath: res == null ? void 0 : res.tempFilePath, filePath: res == null ? void 0 : res.filePath, profile: res == null ? void 0 : res.profile, status: res == null ? void 0 : res.statusCode, statusText, // @ts-expect-error no types headers: (_e = res == null ? void 0 : res.header) != null ? _e : res == null ? void 0 : res.headers, config, // @ts-expect-error no types data: { tempFilePath: res == null ? void 0 : res.tempFilePath, filePath: res == null ? void 0 : res.filePath }, task }; settle( (val) => { resolve(val); done(); }, (err) => { reject(err); done(); }, response ); }, fail: (err) => { switch (err.errMsg) { case "request:fail abort": reject(new UnError(err.errMsg, UnError.ERR_CANCELED, config, task)); break; case "request:fail timeout": reject(new UnError(err.errMsg, UnError.ETIMEDOUT, config, task)); break; default: reject(new UnError(err.errMsg, UnError.ERR_NETWORK, config, task)); break; } }, complete: () => { if (onHeadersReceived) { task == null ? void 0 : task.offHeadersReceived(onHeadersReceived); } if (onProgressUpdate) { task == null ? void 0 : task.offProgressUpdate(onProgressUpdate); } } })); if (onHeadersReceived) { task.onHeadersReceived(onHeadersReceived); } if (onProgressUpdate) { task.onProgressUpdate(onProgressUpdate); } if (cancelToken || signal) { onCanceled = (cancel) => { if (!task) { return; } reject( // @ts-expect-error type not existed !cancel || cancel.type ? new UnCanceledError(void 0, config, task) : cancel ); task.abort(); task = void 0; }; cancelToken == null ? void 0 : cancelToken.subscribe(onCanceled); (signal == null ? void 0 : signal.aborted) ? onCanceled({}) : (_d = signal == null ? void 0 : signal.addEventListener) == null ? void 0 : _d.call(signal, "abort", onCanceled); } }); var __defProp$4 = Object.defineProperty; var __defProps$2 = Object.defineProperties; var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols; var __hasOwnProp$2 = Object.prototype.hasOwnProperty; var __propIsEnum$2 = Object.prototype.propertyIsEnumerable; var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$2 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$2.call(b, prop)) __defNormalProp$4(a, prop, b[prop]); if (__getOwnPropSymbols$2) for (var prop of __getOwnPropSymbols$2(b)) { if (__propIsEnum$2.call(b, prop)) __defNormalProp$4(a, prop, b[prop]); } return a; }; var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b)); const requestAdapter = (config) => new Promise((resolve, reject) => { var _a; const { onHeadersReceived, onChunkReceived, cancelToken, signal } = config; const requestConfig = buildRequestConfig(config); let onCanceled; const done = () => { var _a2; cancelToken == null ? void 0 : cancelToken.unsubscribe(onCanceled); (_a2 = signal == null ? void 0 : signal.removeEventListener) == null ? void 0 : _a2.call(signal, "abort", onCanceled); }; let task; task = uni.request(__spreadProps$2(__spreadValues$2({}, requestConfig), { success: (res) => { var _a2, _b, _c, _d, _e; let statusText; try { statusText = (_a2 = statuses(res == null ? void 0 : res.statusCode)) == null ? void 0 : _a2.toString(); } catch (_) { statusText = void 0; } const response = { // @ts-expect-error no types errMsg: (_d = (_c = (_b = res == null ? void 0 : res.errMsg) != null ? _b : res == null ? void 0 : res.errmsg) != null ? _c : res == null ? void 0 : res.msg) != null ? _d : res == null ? void 0 : res.message, // @ts-expect-error no types errno: res == null ? void 0 : res.errno, cookies: res == null ? void 0 : res.cookies, profile: res == null ? void 0 : res.profile, status: res == null ? void 0 : res.statusCode, statusText, // @ts-expect-error no types headers: (_e = res == null ? void 0 : res.header) != null ? _e : res == null ? void 0 : res.headers, config, // @ts-expect-error no types data: res == null ? void 0 : res.data, task }; settle( (val) => { resolve(val); done(); }, (err) => { reject(err); done(); }, response ); }, fail: (err) => { switch (err.errMsg) { case "request:fail abort": reject(new UnError(err.errMsg, UnError.ERR_CANCELED, config, task)); break; case "request:fail timeout": reject(new UnError(err.errMsg, UnError.ETIMEDOUT, config, task)); break; default: reject(new UnError(err.errMsg, UnError.ERR_NETWORK, config, task)); break; } }, complete: () => { if (onHeadersReceived) { task == null ? void 0 : task.offHeadersReceived(onHeadersReceived); } if (onChunkReceived) { task == null ? void 0 : task.offChunkReceived(onChunkReceived); } } })); if (onHeadersReceived) { task.onHeadersReceived(onHeadersReceived); } if (onChunkReceived) { task.onChunkReceived(onChunkReceived); } if (cancelToken || signal) { onCanceled = (cancel) => { if (!task) { return; } reject( // @ts-expect-error type not existed !cancel || cancel.type ? new UnCanceledError(void 0, config, task) : cancel ); task.abort(); task = void 0; }; cancelToken == null ? void 0 : cancelToken.subscribe(onCanceled); (signal == null ? void 0 : signal.aborted) ? onCanceled({}) : (_a = signal == null ? void 0 : signal.addEventListener) == null ? void 0 : _a.call(signal, "abort", onCanceled); } }); var __defProp$3 = Object.defineProperty; var __defProps$1 = Object.defineProperties; var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; var __hasOwnProp$1 = Object.prototype.hasOwnProperty; var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$1 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$1.call(b, prop)) __defNormalProp$3(a, prop, b[prop]); if (__getOwnPropSymbols$1) for (var prop of __getOwnPropSymbols$1(b)) { if (__propIsEnum$1.call(b, prop)) __defNormalProp$3(a, prop, b[prop]); } return a; }; var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)); const uploadAdapter = (config) => new Promise((resolve, reject) => { var _a, _b, _c, _d; const { onHeadersReceived, cancelToken, signal } = config; const onProgressUpdate = (_c = (_b = (_a = config == null ? void 0 : config.onUploadProgress) != null ? _a : config == null ? void 0 : config.onUploadProgressUpdate) != null ? _b : config == null ? void 0 : config.onProgress) != null ? _c : config == null ? void 0 : config.onProgressUpdate; const uploadConfig = buildUploadConfig(config); let onCanceled; const done = () => { cancelToken == null ? void 0 : cancelToken.unsubscribe(onCanceled); signal == null ? void 0 : signal.removeEventListener("abort", onCanceled); }; let task; task = uni.uploadFile(__spreadProps$1(__spreadValues$1({}, uploadConfig), { success: (res) => { var _a2, _b2, _c2, _d2, _e; let statusText; try { statusText = (_a2 = statuses(res == null ? void 0 : res.statusCode)) == null ? void 0 : _a2.toString(); } catch (_) { statusText = void 0; } const response = { // @ts-expect-error no types errMsg: (_d2 = (_c2 = (_b2 = res == null ? void 0 : res.errMsg) != null ? _b2 : res == null ? void 0 : res.errmsg) != null ? _c2 : res == null ? void 0 : res.msg) != null ? _d2 : res == null ? void 0 : res.message, // @ts-expect-error no types errno: res == null ? void 0 : res.errno, status: res == null ? void 0 : res.statusCode, statusText, // @ts-expect-error no types headers: (_e = res == null ? void 0 : res.header) != null ? _e : res == null ? void 0 : res.headers, config, // @ts-expect-error no types data: res == null ? void 0 : res.data, task }; settle( (val) => { resolve(val); done(); }, (err) => { reject(err); done(); }, response ); }, fail: (err) => { switch (err.errMsg) { case "request:fail abort": reject(new UnError(err.errMsg, UnError.ERR_CANCELED, config, task)); break; case "request:fail timeout": reject(new UnError(err.errMsg, UnError.ETIMEDOUT, config, task)); break; default: reject(new UnError(err.errMsg, UnError.ERR_NETWORK, config, task)); break; } }, complete: () => { if (onHeadersReceived) { task == null ? void 0 : task.offHeadersReceived(onHeadersReceived); } if (onProgressUpdate) { task == null ? void 0 : task.offProgressUpdate(onProgressUpdate); } } })); if (onHeadersReceived) { task.onHeadersReceived(onHeadersReceived); } if (onProgressUpdate) { task.onProgressUpdate(onProgressUpdate); } if (cancelToken || signal) { onCanceled = (cancel) => { if (!task) { return; } reject( // @ts-expect-error type not existed !cancel || cancel.type ? new UnCanceledError(void 0, config, task) : cancel ); task.abort(); task = void 0; }; cancelToken == null ? void 0 : cancelToken.subscribe(onCanceled); (signal == null ? void 0 : signal.aborted) ? onCanceled({}) : (_d = signal == null ? void 0 : signal.addEventListener) == null ? void 0 : _d.call(signal, "abort", onCanceled); } }); const adapters = { download: downloadAdapter, request: requestAdapter, upload: uploadAdapter }; const isUnCancel = (value) => (value == null ? void 0 : value.isUnCanceledError) === true; const throwIfCancellationRequested = (config) => { var _a, _b; if (config.cancelToken) { (_a = config.cancelToken) == null ? void 0 : _a.throwIfRequested(); } if ((_b = config.signal) == null ? void 0 : _b.aborted) { throw new UnCanceledError(); } }; const dispatchRequest = (config) => { throwIfCancellationRequested(config); let adapter = requestAdapter; if (typeof config.adapter === "string" && adapters[config.adapter]) { adapter = adapters[config.adapter]; } else if (typeof config.adapter === "function") { adapter = config.adapter; } return adapter(config).then( (response) => { throwIfCancellationRequested(config); return response; }, (error) => { if (!isUnCancel(error)) { throwIfCancellationRequested(config); } throw error; } ); }; const HttpStatusCode = { Continue: 100, 100: "Continue", SwitchingProtocols: 101, 101: "SwitchingProtocols", Processing: 102, 102: "Processing", EarlyHints: 103, 103: "EarlyHints", Ok: 200, 200: "Ok", Created: 201, 201: "Created", Accepted: 202, 202: "Accepted", NonAuthoritativeInformation: 203, 203: "NonAuthoritativeInformation", NoContent: 204, 204: "NoContent", ResetContent: 205, 205: "ResetContent", PartialContent: 206, 206: "PartialContent", MultiStatus: 207, 207: "MultiStatus", AlreadyReported: 208, 208: "AlreadyReported", ImUsed: 226, 226: "ImUsed", MultipleChoices: 300, 300: "MultipleChoices", MovedPermanently: 301, 301: "MovedPermanently", Found: 302, 302: "Found", SeeOther: 303, 303: "SeeOther", NotModified: 304, 304: "NotModified", UseProxy: 305, 305: "UseProxy", Unused: 306, 306: "Unused", TemporaryRedirect: 307, 307: "TemporaryRedirect", PermanentRedirect: 308, 308: "PermanentRedirect", BadRequest: 400, 400: "BadRequest", Unauthorized: 401, 401: "Unauthorized", PaymentRequired: 402, 402: "PaymentRequired", Forbidden: 403, 403: "Forbidden", NotFound: 404, 404: "NotFound", MethodNotAllowed: 405, 405: "MethodNotAllowed", NotAcceptable: 406, 406: "NotAcceptable", ProxyAuthenticationRequired: 407, 407: "ProxyAuthenticationRequired", RequestTimeout: 408, 408: "RequestTimeout", Conflict: 409, 409: "Conflict", Gone: 410, 410: "Gone", LengthRequired: 411, 411: "LengthRequired", PreconditionFailed: 412, 412: "PreconditionFailed", PayloadTooLarge: 413, 413: "PayloadTooLarge", UriTooLong: 414, 414: "UriTooLong", UnsupportedMediaType: 415, 415: "UnsupportedMediaType", RangeNotSatisfiable: 416, 416: "RangeNotSatisfiable", ExpectationFailed: 417, 417: "ExpectationFailed", ImATeapot: 418, 418: "ImATeapot", MisdirectedRequest: 421, 421: "MisdirectedRequest", UnprocessableEntity: 422, 422: "UnprocessableEntity", Locked: 423, 423: "Locked", FailedDependency: 424, 424: "FailedDependency", TooEarly: 425, 425: "TooEarly", UpgradeRequired: 426, 426: "UpgradeRequired", PreconditionRequired: 428, 428: "PreconditionRequired", TooManyRequests: 429, 429: "TooManyRequests", RequestHeaderFieldsTooLarge: 431, 431: "RequestHeaderFieldsTooLarge", UnavailableForLegalReasons: 451, 451: "UnavailableForLegalReasons", InternalServerError: 500, 500: "InternalServerError", NotImplemented: 501, 501: "NotImplemented", BadGateway: 502, 502: "BadGateway", ServiceUnavailable: 503, 503: "ServiceUnavailable", GatewayTimeout: 504, 504: "GatewayTimeout", HttpVersionNotSupported: 505, 505: "HttpVersionNotSupported", VariantAlsoNegotiates: 506, 506: "VariantAlsoNegotiates", InsufficientStorage: 507, 507: "InsufficientStorage", LoopDetected: 508, 508: "LoopDetected", NotExtended: 510, 510: "NotExtended", NetworkAuthenticationRequired: 511, 511: "NetworkAuthenticationRequired" }; const isUnError = (value) => (value == null ? void 0 : value.isUnError) === true; var __defProp$2 = Object.defineProperty; var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, key + "" , value); class UnInterceptorManager { constructor() { __publicField$2(this, "handlers", []); } use(fulfilled, rejected, options) { var _a; this.handlers.push({ fulfilled, rejected, synchronous: (_a = options == null ? void 0 : options.synchronous) != null ? _a : false, runWhen: options == null ? void 0 : options.runWhen }); return this.handlers.length - 1; } eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } } clear() { if (this.handlers) { this.handlers = []; } } each(fn) { for (const handler of this.handlers) { if (handler && fn) { fn(handler); } } } } var __defProp$1 = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp$1(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp$1(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value); class Un { constructor(instanceConfig) { __publicField$1(this, "defaults"); __publicField$1(this, "interceptors"); this.defaults = instanceConfig || {}; this.interceptors = { request: new UnInterceptorManager(), response: new UnInterceptorManager() }; } _request(configOrUrl, config) { const _config = typeof configOrUrl === "string" ? __spreadProps(__spreadValues({}, config), { url: configOrUrl }) : __spreadValues(__spreadValues({}, configOrUrl), config); const mergedConfig = mergeConfig(this.defaults, _config); const requestInterceptorChain = []; let synchronousRequestInterceptors = true; this.interceptors.request.each((interceptor) => { var _a; if (typeof interceptor.runWhen === "function" && interceptor.runWhen(mergedConfig) === false) { return; } synchronousRequestInterceptors = synchronousRequestInterceptors && ((_a = interceptor == null ? void 0 : interceptor.synchronous) != null ? _a : false); requestInterceptorChain.unshift( interceptor.fulfilled, interceptor.rejected ); }); const responseInterceptorChain = []; this.interceptors.response.each((interceptor) => { responseInterceptorChain.push( interceptor.fulfilled, interceptor.rejected ); }); let promise; let i = 0; let len = 0; if (!synchronousRequestInterceptors) { const chain = [dispatchRequest.bind(this), void 0]; chain.unshift(...requestInterceptorChain); chain.push(...responseInterceptorChain); len = chain.length; promise = Promise.resolve(mergedConfig); while (i < len) { promise = promise.then(chain[i++], chain[i++]); } return promise; } len = requestInterceptorChain.length; let newConfig = mergedConfig; i = 0; while (i < len) { const onFulfilled = requestInterceptorChain[i++]; const onRejected = requestInterceptorChain[i++]; try { newConfig = onFulfilled(newConfig); } catch (error) { onRejected.call(this, error); break; } } try { promise = dispatchRequest.call(this, newConfig); } catch (error) { return Promise.reject(error); } i = 0; len = responseInterceptorChain.length; while (i < len) { promise = promise.then( responseInterceptorChain[i++], responseInterceptorChain[i++] ); } return promise; } async request(configOrUrl, config) { try { return await this._request(configOrUrl, config); } catch (error) { if (error instanceof Error) { let dummy = {}; Error.captureStackTrace ? Error.captureStackTrace(dummy) : ( // biome-ignore lint/suspicious/noAssignInExpressions: follow axios implementation dummy = new Error() ); const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; if (!error.stack) { error.stack = stack; } else if (stack && !String(error.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { error.stack += ` ${stack}`; } } throw error; } } download(configOrUrl, config) { return this.request(configOrUrl, __spreadProps(__spreadValues({}, config), { adapter: "download" })); } upload(configOrUrl, config) { return this.request(configOrUrl, __spreadProps(__spreadValues({}, config), { adapter: "upload" })); } get(url, config) { return this.request(__spreadProps(__spreadValues({}, config), { method: "GET", url })); } delete(url, config) { return this.request(__spreadProps(__spreadValues({}, config), { method: "DELETE", url })); } head(url, config) { return this.request(__spreadProps(__spreadValues({}, config), { method: "HEAD", url })); } options(url, config) { return this.request(__spreadProps(__spreadValues({}, config), { method: "OPTIONS", url })); } trace(url, config) { return this.request(__spreadProps(__spreadValues({}, config), { method: "TRACE", url })); } connect(url, config) { return this.request(__spreadProps(__spreadValues({}, config), { method: "CONNECT", url })); } post(url, data, config) { return this.request(__spreadProps(__spreadValues({}, config), { method: "POST", url, data })); } put(url, data, config) { return this.request(__spreadProps(__spreadValues({}, config), { method: "PUT", url, data })); } patch(url, data, config) { return this.request(__spreadProps(__spreadValues({}, config), { method: "PATCH", url, data })); } getUri(config) { var _a, _b, _c; const mergedConfig = mergeConfig(this.defaults, config); const fullPath = buildFullPath( (_a = mergedConfig == null ? void 0 : mergedConfig.baseUrl) != null ? _a : "", (_b = mergedConfig == null ? void 0 : mergedConfig.url) != null ? _b : "", (_c = mergedConfig == null ? void 0 : mergedConfig.allowAbsoluteUrls) != null ? _c : true ); return buildUrl( fullPath, mergedConfig == null ? void 0 : mergedConfig.params, mergedConfig == null ? void 0 : mergedConfig.paramsSerializer ); } } var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); class UnCancelToken { constructor(executor) { __publicField(this, "promise"); __publicField(this, "reason"); __publicField(this, "listeners", []); if (typeof executor !== "function") { throw new TypeError("executor must be a function."); } let resolvePromise; this.promise = new Promise((resolve) => { resolvePromise = resolve; }); this.promise.then((cancel) => { for (const listener of this.listeners) { listener(cancel); } this.listeners = []; }); this.promise.then = (onfulfilled) => { let _resolve; const promise = new Promise((resolve) => { this.subscribe(resolve); _resolve = resolve; }).then(onfulfilled); promise.cancel = () => { this.unsubscribe(_resolve); }; return promise; }; executor((message, config, request) => { if (this.reason) { return; } this.reason = new UnCanceledError(message, config, request); resolvePromise(this.reason); }); } throwIfRequested() { if (this.reason) { throw this.reason; } } subscribe(listener) { if (this.reason) { listener(this.reason); return; } this.listeners.push(listener); } unsubscribe(listener) { const index = this.listeners.indexOf(listener); if (index !== -1) { this.listeners.splice(index, 1); } } toAbortSignal() { const controller = new AbortController(); const abort = (error) => { controller.abort(error); }; this.subscribe(abort); controller.signal.unsubscribe = () => this.unsubscribe(abort); return controller.signal; } static source() { let cancel; const token = new UnCancelToken((c) => { cancel = c; }); return { token, // @ts-expect-error Variable 'cancel' is used before being assigned.ts(2454) cancel }; } } const defaults = { adapter: "request", validateStatus: (status) => status >= 200 && status < 300 }; const createInstance = (defaultConfig) => { const context = new Un(defaultConfig); const instance = Un.prototype.request.bind(context); extend(instance, Un.prototype, context, { allOwnKeys: true }); extend(instance, context, null, { allOwnKeys: true }); instance.create = (instanceConfig) => createInstance(mergeConfig(defaultConfig, instanceConfig)); return instance; }; const un = createInstance(defaults); un.Un = Un; un.CanceledError = UnCanceledError; un.CancelToken = UnCancelToken; un.isCancel = isUnCancel; un.VERSION = version; un.UnError = UnError; un.isUnError = isUnError; un.all = (promises) => Promise.all(promises); un.mergeConfig = mergeConfig; un.HttpStatusCode = HttpStatusCode; export { HttpStatusCode, Un, UnCancelToken, UnCanceledError, UnError, UnInterceptorManager, adapters, buildDownloadConfig, buildFullPath, buildRequestConfig, buildUploadConfig, buildUrl, combineUrls, un as default, defaults, dispatchRequest, downloadAdapter, extend, forEach, isAbsoluteUrl, isUnCancel, isUnError, mergeConfig, requestAdapter, settle, un, uploadAdapter };