diff --git a/.husky/pre-commit b/.husky/pre-commit index d2ae35e..f7ca6df 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,4 +1,6 @@ #!/bin/sh . "$(dirname "$0")/_/husky.sh" +yarn build +git add dist yarn lint-staged diff --git a/dist/@types/axios.d.ts b/dist/@types/axios.d.ts new file mode 100644 index 0000000..4e976ed --- /dev/null +++ b/dist/@types/axios.d.ts @@ -0,0 +1,22 @@ +import { AxiosAdapter, AxiosPlatform } from './core/adapter'; +import Axios, { + AxiosConstructor, + AxiosRequestConfig, + AxiosResponse, +} from './core/Axios'; +import { CancelTokenConstructor } from './core/cancel'; +export interface AxiosInstance extends Axios { + (config: AxiosRequestConfig): Promise>; + (url: string, config?: AxiosRequestConfig): Promise< + AxiosResponse + >; +} +export interface AxiosStatic extends AxiosInstance { + Axios: AxiosConstructor; + CancelToken: CancelTokenConstructor; + create(defaults?: AxiosRequestConfig): AxiosInstance; + createAdapter(platform: AxiosPlatform): AxiosAdapter; + isCancel(value: any): boolean; +} +declare const axios: AxiosStatic; +export default axios; diff --git a/dist/@types/core/Axios.d.ts b/dist/@types/core/Axios.d.ts new file mode 100644 index 0000000..2cffd46 --- /dev/null +++ b/dist/@types/core/Axios.d.ts @@ -0,0 +1,135 @@ +import { + AxiosAdapterRequestMethod, + AxiosAdapter, + AxiosAdapterTask, +} from './adapter'; +import { CancelToken } from './cancel'; +import InterceptorManager from './InterceptorManager'; +import { AxiosTransformer } from './transformData'; +export declare type AxiosRequestMethodAlias = + | 'options' + | 'get' + | 'head' + | 'post' + | 'put' + | 'delete' + | 'trace' + | 'connect'; +export declare type AxiosRequestMethod = + | AxiosAdapterRequestMethod + | AxiosRequestMethodAlias; +export declare type AxiosRequestHeaders = AnyObject; +export declare type AxiosRequestParams = AnyObject; +export declare type AxiosRequestData = AnyObject; +export declare type AxiosResponseHeaders = AnyObject; +export interface AxiosRequestFormData extends AxiosRequestData { + fileName: string; + filePath: string; + fileType?: 'image' | 'video' | 'audio'; + hideLoading?: boolean; +} +export interface AxiosProgressEvent { + progress: number; + totalBytesSent: number; + totalBytesExpectedToSend: number; +} +export interface AxiosProgressCallback { + (event: AxiosProgressEvent): void; +} +export interface AxiosRequestConfig { + adapter?: AxiosAdapter; + baseURL?: string; + cancelToken?: CancelToken; + data?: AxiosRequestData | AxiosRequestFormData | AxiosRequestFormData; + dataType?: 'json' | '其他'; + download?: boolean; + enableHttp2?: boolean; + enableQuic?: boolean; + enableCache?: boolean; + errorHandler?: (error: any) => Promise; + headers?: AxiosRequestHeaders; + method?: AxiosRequestMethod; + onUploadProgress?: AxiosProgressCallback; + onDownloadProgress?: AxiosProgressCallback; + params?: AxiosRequestParams; + paramsSerializer?: (params?: AxiosRequestParams) => string; + responseType?: 'text' | 'arraybuffer'; + sslVerify?: boolean; + transformRequest?: AxiosTransformer | AxiosTransformer[]; + transformResponse?: AxiosTransformer | AxiosTransformer[]; + timeout?: number; + upload?: boolean; + url?: string; + validateStatus?: (status: number) => boolean; +} +export interface AxiosResponse { + status: number; + statusText: string; + headers: AxiosResponseHeaders; + data: TData; + config?: AxiosRequestConfig; + request?: AxiosAdapterTask; + cookies?: string[]; + profile?: AnyObject; +} +export interface AxiosResponseError extends AnyObject { + status: number; + statusText: string; + headers: AxiosResponseHeaders; + config?: AxiosRequestConfig; + request?: AxiosAdapterTask; +} +export interface AxiosConstructor { + new (config: AxiosRequestConfig): Axios; +} +export default class Axios { + defaults: AxiosRequestConfig; + interceptors: { + request: InterceptorManager; + response: InterceptorManager>; + }; + constructor(defaults?: AxiosRequestConfig); + getUri(config: AxiosRequestConfig): string; + request( + config: AxiosRequestConfig, + ): Promise>; + options( + url: string, + config?: AxiosRequestConfig, + ): Promise>; + get( + url: string, + params?: AxiosRequestParams, + config?: AxiosRequestConfig, + ): Promise>; + head( + url: string, + params?: AxiosRequestParams, + config?: AxiosRequestConfig, + ): Promise>; + post( + url: string, + data?: AxiosRequestData | AxiosRequestFormData, + config?: AxiosRequestConfig, + ): Promise>; + put( + url: string, + data?: AxiosRequestData | AxiosRequestFormData, + config?: AxiosRequestConfig, + ): Promise>; + delete( + url: string, + params?: AxiosRequestParams, + config?: AxiosRequestConfig, + ): Promise>; + trace( + url: string, + config?: AxiosRequestConfig, + ): Promise>; + connect( + url: string, + config?: AxiosRequestConfig, + ): Promise>; + private _requestMethodWithoutParams; + private _requestMethodWithoutData; +} diff --git a/dist/@types/core/InterceptorManager.d.ts b/dist/@types/core/InterceptorManager.d.ts new file mode 100644 index 0000000..33d0dad --- /dev/null +++ b/dist/@types/core/InterceptorManager.d.ts @@ -0,0 +1,20 @@ +export interface InterceptorResolved { + (value: T): T | Promise; +} +export interface InterceptorRejected { + (error: any): any | Promise; +} +export interface Interceptor { + resolved: InterceptorResolved; + rejected?: InterceptorRejected; +} +export interface InterceptorExecutor { + (interceptor: Interceptor): void; +} +export default class InterceptorManager { + private id; + private interceptors; + use(resolved: InterceptorResolved, rejected?: InterceptorRejected): number; + eject(id: number): void; + forEach(executor: InterceptorExecutor, reverse?: 'reverse'): void; +} diff --git a/dist/@types/core/adapter.d.ts b/dist/@types/core/adapter.d.ts new file mode 100644 index 0000000..709b716 --- /dev/null +++ b/dist/@types/core/adapter.d.ts @@ -0,0 +1,70 @@ +import { + AxiosProgressCallback, + AxiosRequestConfig, + AxiosRequestData, + AxiosRequestHeaders, + AxiosResponse, + AxiosResponseError, +} from './Axios'; +export declare type AxiosAdapterRequestType = 'request' | 'download' | 'upload'; +export declare type AxiosAdapterRequestMethod = + | 'OPTIONS' + | 'GET' + | 'HEAD' + | 'POST' + | 'PUT' + | 'DELETE' + | 'TRACE' + | 'CONNECT'; +export interface AxiosAdapterRequestConfig extends AxiosRequestConfig { + type: AxiosAdapterRequestType; + method: AxiosAdapterRequestMethod; + url: string; + success(response: AxiosResponse): void; + fail(error: AxiosResponseError): void; +} +export interface AxiosAdapterBaseOptions extends AxiosAdapterRequestConfig { + header?: AxiosRequestHeaders; + success(response: any): void; + fail(error: any): void; +} +export interface AxiosAdapterUploadOptions extends AxiosAdapterBaseOptions { + filePath: string; + name: string; + fileName: string; + fileType: 'image' | 'video' | 'audio'; + hideLoading?: boolean; + formData?: AxiosRequestData; +} +export interface AxiosAdapterDownloadOptions extends AxiosAdapterBaseOptions { + filePath?: string; + fileName?: string; +} +export interface AxiosAdapterRequest { + (config: AxiosAdapterBaseOptions): AxiosAdapterTask | void; +} +export interface AxiosAdapterUpload { + (config: AxiosAdapterUploadOptions): AxiosAdapterTask | void; +} +export interface AxiosAdapterDownload { + (config: AxiosAdapterDownloadOptions): AxiosAdapterTask | void; +} +export interface AxiosPlatform { + request: AxiosAdapterRequest; + upload: AxiosAdapterUpload; + download: AxiosAdapterDownload; +} +export interface AxiosAdapterTask { + abort?(): void; + onProgressUpdate?(callback: AxiosProgressCallback): void; + offProgressUpdate?(callback: AxiosProgressCallback): void; +} +export interface AxiosAdapter { + (config: AxiosAdapterRequestConfig): AxiosAdapterTask | void; +} +export declare function isPlatform(value: any): value is AxiosPlatform; +export declare function revisePlatformApiNames( + platform: AnyObject, +): AxiosPlatform; +export declare function createAdapter(platform: AxiosPlatform): AxiosAdapter; +export declare function getAdapterDefault(): AxiosAdapter | undefined; diff --git a/dist/@types/core/cancel.d.ts b/dist/@types/core/cancel.d.ts new file mode 100644 index 0000000..973ea99 --- /dev/null +++ b/dist/@types/core/cancel.d.ts @@ -0,0 +1,28 @@ +export interface CancelAction { + (message?: string): void; +} +export interface CancelExecutor { + (cancel: CancelAction): void; +} +export interface CancelTokenSource { + token: CancelToken; + cancel: CancelAction; +} +export interface CancelTokenConstructor { + new (executor: CancelExecutor): CancelToken; + source(): CancelTokenSource; +} +export declare class Cancel { + message?: string; + constructor(message?: string); + toString(): string; +} +export declare function isCancel(value: any): value is Cancel; +export declare class CancelToken { + private reason?; + listener: Promise; + constructor(executor: CancelExecutor); + static source(): CancelTokenSource; + throwIfRequested(): void; +} +export declare function isCancelToken(value: any): value is CancelToken; diff --git a/dist/@types/core/createError.d.ts b/dist/@types/core/createError.d.ts new file mode 100644 index 0000000..2e3fb5a --- /dev/null +++ b/dist/@types/core/createError.d.ts @@ -0,0 +1,22 @@ +import { AxiosAdapterTask } from './adapter'; +import { AxiosRequestConfig, AxiosResponse, AxiosResponseError } from './Axios'; +export declare type AxiosErrorResponse = AxiosResponse | AxiosResponseError; +declare class AxiosError extends Error { + isAxiosError: boolean; + config: AxiosRequestConfig; + request?: AxiosAdapterTask; + response?: AxiosErrorResponse; + constructor( + message: string, + config: AxiosRequestConfig, + request?: AxiosAdapterTask, + response?: AxiosErrorResponse, + ); +} +export declare function createError( + message: string, + config: AxiosRequestConfig, + request?: AxiosAdapterTask, + response?: AxiosErrorResponse, +): AxiosError; +export {}; diff --git a/dist/@types/core/dispatchRequest.d.ts b/dist/@types/core/dispatchRequest.d.ts new file mode 100644 index 0000000..3c8eb25 --- /dev/null +++ b/dist/@types/core/dispatchRequest.d.ts @@ -0,0 +1,4 @@ +import { AxiosRequestConfig, AxiosResponse } from './Axios'; +export default function dispatchRequest( + config: AxiosRequestConfig, +): Promise; diff --git a/dist/@types/core/flattenHeaders.d.ts b/dist/@types/core/flattenHeaders.d.ts new file mode 100644 index 0000000..c1884eb --- /dev/null +++ b/dist/@types/core/flattenHeaders.d.ts @@ -0,0 +1,4 @@ +import { AxiosRequestConfig, AxiosRequestHeaders } from './Axios'; +export declare function flattenHeaders( + config: AxiosRequestConfig, +): AxiosRequestHeaders | undefined; diff --git a/dist/@types/core/generateType.d.ts b/dist/@types/core/generateType.d.ts new file mode 100644 index 0000000..cefad51 --- /dev/null +++ b/dist/@types/core/generateType.d.ts @@ -0,0 +1,5 @@ +import { AxiosAdapterRequestType } from './adapter'; +import { AxiosRequestConfig } from './Axios'; +export declare function generateType( + config: AxiosRequestConfig, +): AxiosAdapterRequestType; diff --git a/dist/@types/core/mergeConfig.d.ts b/dist/@types/core/mergeConfig.d.ts new file mode 100644 index 0000000..5c99aca --- /dev/null +++ b/dist/@types/core/mergeConfig.d.ts @@ -0,0 +1,5 @@ +import { AxiosRequestConfig } from './Axios'; +export declare function mergeConfig( + config1?: AxiosRequestConfig, + config2?: AxiosRequestConfig, +): AxiosRequestConfig; diff --git a/dist/@types/core/request.d.ts b/dist/@types/core/request.d.ts new file mode 100644 index 0000000..ed05944 --- /dev/null +++ b/dist/@types/core/request.d.ts @@ -0,0 +1,4 @@ +import { AxiosRequestConfig, AxiosResponse } from './Axios'; +export declare function request( + config: AxiosRequestConfig, +): Promise>; diff --git a/dist/@types/core/transformData.d.ts b/dist/@types/core/transformData.d.ts new file mode 100644 index 0000000..577b61b --- /dev/null +++ b/dist/@types/core/transformData.d.ts @@ -0,0 +1,16 @@ +import { + AxiosRequestData, + AxiosRequestFormData, + AxiosResponseHeaders, +} from './Axios'; +export interface AxiosTransformer { + ( + data?: AxiosRequestData | AxiosRequestFormData, + headers?: AxiosResponseHeaders, + ): AxiosRequestData | AxiosRequestFormData; +} +export declare function transformData( + data?: AxiosRequestData | AxiosRequestFormData, + headers?: AxiosResponseHeaders, + transforms?: AxiosTransformer | AxiosTransformer[], +): AxiosRequestData | AxiosRequestFormData | undefined; diff --git a/dist/@types/core/transformURL.d.ts b/dist/@types/core/transformURL.d.ts new file mode 100644 index 0000000..e2a817f --- /dev/null +++ b/dist/@types/core/transformURL.d.ts @@ -0,0 +1,2 @@ +import { AxiosRequestConfig } from './Axios'; +export declare function transformURL(config: AxiosRequestConfig): string; diff --git a/dist/@types/defaults.d.ts b/dist/@types/defaults.d.ts new file mode 100644 index 0000000..97c75e9 --- /dev/null +++ b/dist/@types/defaults.d.ts @@ -0,0 +1,3 @@ +import { AxiosRequestConfig } from './core/Axios'; +declare const defaults: AxiosRequestConfig; +export default defaults; diff --git a/dist/@types/helpers/is.d.ts b/dist/@types/helpers/is.d.ts new file mode 100644 index 0000000..566fbf5 --- /dev/null +++ b/dist/@types/helpers/is.d.ts @@ -0,0 +1,13 @@ +export declare function isArray(value: any): value is T[]; +export declare function isDate(date: any): date is Date; +export declare function isEmptyArray(value: any): value is []; +export declare function isEmptyObject(value: any): value is {}; +export declare function isFunction( + value: any, +): value is T; +export declare function isNull(value: any): value is null; +export declare function isPlainObject( + value: any, +): value is [T] extends never[] ? AnyObject : T; +export declare function isString(value: any): value is string; +export declare function isUndefined(value: any): value is undefined; diff --git a/dist/@types/helpers/url.d.ts b/dist/@types/helpers/url.d.ts new file mode 100644 index 0000000..62066c1 --- /dev/null +++ b/dist/@types/helpers/url.d.ts @@ -0,0 +1,17 @@ +export declare function buildURL( + url?: string, + params?: any, + paramsSerializer?: typeof paramsSerialization, +): string; +export declare function combineURL( + baseURL: string | undefined, + url: string, +): string; +export declare function dynamicInterpolation( + url: string, + sourceData?: any, +): string; +export declare function isAbsoluteURL(url: string): boolean; +export declare function isDynamicURL(url: string): boolean; +declare function paramsSerialization(params?: any): string; +export {}; diff --git a/dist/@types/helpers/utils.d.ts b/dist/@types/helpers/utils.d.ts new file mode 100644 index 0000000..25ffb1b --- /dev/null +++ b/dist/@types/helpers/utils.d.ts @@ -0,0 +1,19 @@ +export declare function deepMerge(...objs: T[]): T; +export declare function pick( + obj: T, + ...keys: K[] +): Pick; +export declare function omit( + obj: T, + ...keys: K[] +): Omit; +export declare function assert(condition: boolean, msg: string): void; +export declare function throwError(msg: string): void; +export declare function toLowerCase( + value: any, + defaultValue: T, +): T; +export declare function toUpperCase( + value: any, + defaultValue: T, +): T; diff --git a/dist/@types/index.d.ts b/dist/@types/index.d.ts new file mode 100644 index 0000000..0c991a9 --- /dev/null +++ b/dist/@types/index.d.ts @@ -0,0 +1,14 @@ +import axios from './axios'; +export { + AxiosRequestConfig, + AxiosRequestFormData, + AxiosResponse, + AxiosResponseError, +} from './core/Axios'; +export { + AxiosAdapterRequestConfig, + AxiosAdapter, + AxiosPlatform, +} from './core/adapter'; +export { AxiosInstance, AxiosStatic } from './axios'; +export default axios; diff --git a/dist/cjs/axios-miniprogram.js b/dist/cjs/axios-miniprogram.js new file mode 100644 index 0000000..4c80b0d --- /dev/null +++ b/dist/cjs/axios-miniprogram.js @@ -0,0 +1,48 @@ +/** + * @name axios-miniprogram + * @description 基于 Promise 的 HTTP 请求库,适用于各大小程序平台。 + * @version v2.0.0-rc-1 + * @date 2021-05-30 16:16:13 + * @author fluffff + * @github git+https://github.com/fluffff/axios-miniprogram.git + * @issues https://github.com/fluffff/axios-miniprogram/issues + */ +'use strict'; + +var extendStatics = function (d, b) {extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function (d, b) {d.__proto__ = b;} || function (d, b) {for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];};return extendStatics(d, b);};function __extends(d, b) {if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");extendStatics(d, b);function __() {this.constructor = d;}d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());}var __assign = function () {__assign = Object.assign || function __assign(t) {for (var s, i = 1, n = arguments.length; i < n; i++) {s = arguments[i];for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];}return t;};return __assign.apply(this, arguments);};function __rest(s, e) {var t = {};for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];}return t;}function __spreadArray(to, from) {for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) to[j] = from[i];return to;} + +var _toString = Object.prototype.toString;function isArray(value) {return Array.isArray(value);}function isDate(date) {return _toString.call(date) === '[object Date]';}function isEmptyArray(value) {return isArray(value) && value.length === 0;}function isFunction(value) {return typeof value === 'function';}function isNull(value) {return value === null;}function isPlainObject(value) {return _toString.call(value) === '[object Object]';}function isString(value) {return typeof value === 'string';}function isUndefined(value) {return typeof value === 'undefined';} + +function deepMerge() {var objs = [];for (var _i = 0; _i < arguments.length; _i++) {objs[_i] = arguments[_i];}var result = {};objs.forEach(function (obj) {return Object.keys(obj).forEach(function (key) {var val = obj[key];var resultVal = result[key];if (isPlainObject(resultVal) && isPlainObject(val)) {result[key] = deepMerge(resultVal, val);} else if (isPlainObject(val)) {result[key] = deepMerge(val);} else {result[key] = val;}});});return result;}function omit(obj) {var keys = [];for (var _i = 1; _i < arguments.length; _i++) {keys[_i - 1] = arguments[_i];}var _omit = Object.assign({}, obj);keys.forEach(function (key) {return delete _omit[key];});return _omit;}function assert(condition, msg) {if (!condition) {throwError(msg);}}function throwError(msg) {throw new Error("[axios-miniprogram]: " + msg);}function toLowerCase(value, defaultValue) {if (!isString(value)) {value = defaultValue;}return value.toLowerCase();}function toUpperCase(value, defaultValue) {if (!isString(value)) {value = defaultValue;}return value.toUpperCase();} + +function isPlatform(value) {return isPlainObject(value) && isFunction(value.request) && isFunction(value.upload) && isFunction(value.download);}function revisePlatformApiNames(platform) {var _a, _b, _c;return {request: (_a = platform.request) !== null && _a !== void 0 ? _a : platform.httpRequest,upload: (_b = platform.upload) !== null && _b !== void 0 ? _b : platform.uploadFile,download: (_c = platform.download) !== null && _c !== void 0 ? _c : platform.downloadFile};}function createAdapter(platform) {assert(isPlainObject(platform), 'platform 需要是一个 object');assert(isFunction(platform.request), 'platform.request 需要是一个 function');assert(isFunction(platform.upload), 'platform.upload 需要是一个 function');assert(isFunction(platform.download), 'platform.download 需要是一个 function');function transformResult(result) {if (!isUndefined(result.statusCode)) {result.status = result.statusCode;delete result.statusCode;}if (isUndefined(result.status)) {result.status = isUndefined(result.data) ? 400 : 200;}if (!isUndefined(result.header)) {result.headers = result.header;delete result.header;}if (isUndefined(result.headers)) {result.headers = {};}if (!isUndefined(result.errMsg)) {result.statusText = result.errMsg;delete result.errMsg;}if (isUndefined(result.statusText)) {result.statusText = result.status === 200 ? 'OK' : result.status === 400 ? 'Bad Adapter' : '';}}function transformOptions(config) {return __assign(__assign({}, config), {header: config.headers,success: function success(response) {transformResult(response);config.success(response);},fail: function fail(error) {transformResult(error);config.fail(error);}});}function injectDownloadData(response) {if (!isPlainObject(response.data)) {response.data = {};}if (!isUndefined(response.tempFilePath)) {response.data.tempFilePath = response.tempFilePath;delete response.tempFilePath;}if (!isUndefined(response.apFilePath)) {response.data.tempFilePath = response.apFilePath;delete response.apFilePath;}if (!isUndefined(response.filePath)) {response.data.filePath = response.filePath;delete response.filePath;}}function callRequest(request, baseOptions) {return request(baseOptions);}function callUpload(upload, baseOptions) {assert(isPlainObject(baseOptions.data), '上传文件时 data 需要是一个 object');assert(isString(baseOptions.data.fileName), '上传文件时 data.fileName 需要是一个 string');assert(isString(baseOptions.data.filePath), '上传文件时 data.filePath 需要是一个 string');var _a = baseOptions.data,fileName = _a.fileName,filePath = _a.filePath,fileType = _a.fileType,hideLoading = _a.hideLoading,formData = __rest(_a, ["fileName", "filePath", "fileType", "hideLoading"]);var options = __assign(__assign({}, baseOptions), {name: fileName,fileName: fileName,filePath: filePath,fileType: fileType !== null && fileType !== void 0 ? fileType : 'image',hideLoading: hideLoading,formData: formData});return upload(options);}function callDownload(download, baseOptions) {var _a, _b;var options = __assign(__assign({}, baseOptions), {filePath: (_a = baseOptions.params) === null || _a === void 0 ? void 0 : _a.filePath,fileName: (_b = baseOptions.params) === null || _b === void 0 ? void 0 : _b.fileName,success: function success(response) {injectDownloadData(response);baseOptions.success(response);}});return download(options);}return function adapterDefault(config) {var baseOptions = transformOptions(config);switch (config.type) {case 'request':return callRequest(platform.request, baseOptions);case 'upload':return callUpload(platform.upload, baseOptions);case 'download':return callDownload(platform.download, baseOptions);default:throwError("\u65E0\u6CD5\u8BC6\u522B\u7684\u8BF7\u6C42\u7C7B\u578B " + config.type);}};}function getAdapterDefault() {var tryGetPlatforms = [function () {return uni;}, function () {return wx;}, function () {return my;}, function () {return swan;}, function () {return tt;}, function () {return qq;}, function () {return qh;}, function () {return ks;}, function () {return dd;}];var platform;while (!isEmptyArray(tryGetPlatforms) && !isPlatform(platform)) {try {var tryGetPlatform = tryGetPlatforms.shift();if (isPlainObject(platform = tryGetPlatform())) {platform = revisePlatformApiNames(platform);}} catch (err) {}}if (!isPlatform(platform)) {return;}return createAdapter(platform);} + +function encode(str) {return encodeURIComponent(str).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']');}function buildURL(url, params, paramsSerializer) {if (url === void 0) {url = '';}if (paramsSerializer === void 0) {paramsSerializer = paramsSerialization;}if (!isPlainObject(params)) {return url;}return generateURL(url, paramsSerializer(params));}var combineREG = /(?= 200 && status < 300;},timeout: 10000,dataType: 'json',responseType: 'text',enableHttp2: false,enableQuic: false,enableCache: false,sslVerify: true}; + +function createInstance(defaults) {var instance = new Axios(defaults);function axios(url, config) {if (isString(url)) {config = Object.assign({}, config, {url: url});} else {config = url;}return instance.request(config);}Object.assign(axios, instance);Object.setPrototypeOf(axios, Object.getPrototypeOf(instance));return axios;}var axios = createInstance(defaults);axios.Axios = Axios;axios.CancelToken = CancelToken;axios.create = function create(defaults) {return createInstance(mergeConfig(axios.defaults, defaults));};axios.createAdapter = createAdapter;axios.isCancel = isCancel; + +module.exports = axios; diff --git a/dist/esm/axios-miniprogram.js b/dist/esm/axios-miniprogram.js new file mode 100644 index 0000000..4ced350 --- /dev/null +++ b/dist/esm/axios-miniprogram.js @@ -0,0 +1,46 @@ +/** + * @name axios-miniprogram + * @description 基于 Promise 的 HTTP 请求库,适用于各大小程序平台。 + * @version v2.0.0-rc-1 + * @date 2021-05-30 16:16:13 + * @author fluffff + * @github git+https://github.com/fluffff/axios-miniprogram.git + * @issues https://github.com/fluffff/axios-miniprogram/issues + */ +var extendStatics = function (d, b) {extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function (d, b) {d.__proto__ = b;} || function (d, b) {for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];};return extendStatics(d, b);};function __extends(d, b) {if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");extendStatics(d, b);function __() {this.constructor = d;}d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());}var __assign = function () {__assign = Object.assign || function __assign(t) {for (var s, i = 1, n = arguments.length; i < n; i++) {s = arguments[i];for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];}return t;};return __assign.apply(this, arguments);};function __rest(s, e) {var t = {};for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];}return t;}function __spreadArray(to, from) {for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) to[j] = from[i];return to;} + +var _toString = Object.prototype.toString;function isArray(value) {return Array.isArray(value);}function isDate(date) {return _toString.call(date) === '[object Date]';}function isEmptyArray(value) {return isArray(value) && value.length === 0;}function isFunction(value) {return typeof value === 'function';}function isNull(value) {return value === null;}function isPlainObject(value) {return _toString.call(value) === '[object Object]';}function isString(value) {return typeof value === 'string';}function isUndefined(value) {return typeof value === 'undefined';} + +function deepMerge() {var objs = [];for (var _i = 0; _i < arguments.length; _i++) {objs[_i] = arguments[_i];}var result = {};objs.forEach(function (obj) {return Object.keys(obj).forEach(function (key) {var val = obj[key];var resultVal = result[key];if (isPlainObject(resultVal) && isPlainObject(val)) {result[key] = deepMerge(resultVal, val);} else if (isPlainObject(val)) {result[key] = deepMerge(val);} else {result[key] = val;}});});return result;}function omit(obj) {var keys = [];for (var _i = 1; _i < arguments.length; _i++) {keys[_i - 1] = arguments[_i];}var _omit = Object.assign({}, obj);keys.forEach(function (key) {return delete _omit[key];});return _omit;}function assert(condition, msg) {if (!condition) {throwError(msg);}}function throwError(msg) {throw new Error("[axios-miniprogram]: " + msg);}function toLowerCase(value, defaultValue) {if (!isString(value)) {value = defaultValue;}return value.toLowerCase();}function toUpperCase(value, defaultValue) {if (!isString(value)) {value = defaultValue;}return value.toUpperCase();} + +function isPlatform(value) {return isPlainObject(value) && isFunction(value.request) && isFunction(value.upload) && isFunction(value.download);}function revisePlatformApiNames(platform) {var _a, _b, _c;return {request: (_a = platform.request) !== null && _a !== void 0 ? _a : platform.httpRequest,upload: (_b = platform.upload) !== null && _b !== void 0 ? _b : platform.uploadFile,download: (_c = platform.download) !== null && _c !== void 0 ? _c : platform.downloadFile};}function createAdapter(platform) {assert(isPlainObject(platform), 'platform 需要是一个 object');assert(isFunction(platform.request), 'platform.request 需要是一个 function');assert(isFunction(platform.upload), 'platform.upload 需要是一个 function');assert(isFunction(platform.download), 'platform.download 需要是一个 function');function transformResult(result) {if (!isUndefined(result.statusCode)) {result.status = result.statusCode;delete result.statusCode;}if (isUndefined(result.status)) {result.status = isUndefined(result.data) ? 400 : 200;}if (!isUndefined(result.header)) {result.headers = result.header;delete result.header;}if (isUndefined(result.headers)) {result.headers = {};}if (!isUndefined(result.errMsg)) {result.statusText = result.errMsg;delete result.errMsg;}if (isUndefined(result.statusText)) {result.statusText = result.status === 200 ? 'OK' : result.status === 400 ? 'Bad Adapter' : '';}}function transformOptions(config) {return __assign(__assign({}, config), {header: config.headers,success: function success(response) {transformResult(response);config.success(response);},fail: function fail(error) {transformResult(error);config.fail(error);}});}function injectDownloadData(response) {if (!isPlainObject(response.data)) {response.data = {};}if (!isUndefined(response.tempFilePath)) {response.data.tempFilePath = response.tempFilePath;delete response.tempFilePath;}if (!isUndefined(response.apFilePath)) {response.data.tempFilePath = response.apFilePath;delete response.apFilePath;}if (!isUndefined(response.filePath)) {response.data.filePath = response.filePath;delete response.filePath;}}function callRequest(request, baseOptions) {return request(baseOptions);}function callUpload(upload, baseOptions) {assert(isPlainObject(baseOptions.data), '上传文件时 data 需要是一个 object');assert(isString(baseOptions.data.fileName), '上传文件时 data.fileName 需要是一个 string');assert(isString(baseOptions.data.filePath), '上传文件时 data.filePath 需要是一个 string');var _a = baseOptions.data,fileName = _a.fileName,filePath = _a.filePath,fileType = _a.fileType,hideLoading = _a.hideLoading,formData = __rest(_a, ["fileName", "filePath", "fileType", "hideLoading"]);var options = __assign(__assign({}, baseOptions), {name: fileName,fileName: fileName,filePath: filePath,fileType: fileType !== null && fileType !== void 0 ? fileType : 'image',hideLoading: hideLoading,formData: formData});return upload(options);}function callDownload(download, baseOptions) {var _a, _b;var options = __assign(__assign({}, baseOptions), {filePath: (_a = baseOptions.params) === null || _a === void 0 ? void 0 : _a.filePath,fileName: (_b = baseOptions.params) === null || _b === void 0 ? void 0 : _b.fileName,success: function success(response) {injectDownloadData(response);baseOptions.success(response);}});return download(options);}return function adapterDefault(config) {var baseOptions = transformOptions(config);switch (config.type) {case 'request':return callRequest(platform.request, baseOptions);case 'upload':return callUpload(platform.upload, baseOptions);case 'download':return callDownload(platform.download, baseOptions);default:throwError("\u65E0\u6CD5\u8BC6\u522B\u7684\u8BF7\u6C42\u7C7B\u578B " + config.type);}};}function getAdapterDefault() {var tryGetPlatforms = [function () {return uni;}, function () {return wx;}, function () {return my;}, function () {return swan;}, function () {return tt;}, function () {return qq;}, function () {return qh;}, function () {return ks;}, function () {return dd;}];var platform;while (!isEmptyArray(tryGetPlatforms) && !isPlatform(platform)) {try {var tryGetPlatform = tryGetPlatforms.shift();if (isPlainObject(platform = tryGetPlatform())) {platform = revisePlatformApiNames(platform);}} catch (err) {}}if (!isPlatform(platform)) {return;}return createAdapter(platform);} + +function encode(str) {return encodeURIComponent(str).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']');}function buildURL(url, params, paramsSerializer) {if (url === void 0) {url = '';}if (paramsSerializer === void 0) {paramsSerializer = paramsSerialization;}if (!isPlainObject(params)) {return url;}return generateURL(url, paramsSerializer(params));}var combineREG = /(?= 200 && status < 300;},timeout: 10000,dataType: 'json',responseType: 'text',enableHttp2: false,enableQuic: false,enableCache: false,sslVerify: true}; + +function createInstance(defaults) {var instance = new Axios(defaults);function axios(url, config) {if (isString(url)) {config = Object.assign({}, config, {url: url});} else {config = url;}return instance.request(config);}Object.assign(axios, instance);Object.setPrototypeOf(axios, Object.getPrototypeOf(instance));return axios;}var axios = createInstance(defaults);axios.Axios = Axios;axios.CancelToken = CancelToken;axios.create = function create(defaults) {return createInstance(mergeConfig(axios.defaults, defaults));};axios.createAdapter = createAdapter;axios.isCancel = isCancel; + +export default axios; diff --git a/package.json b/package.json index fa11a9c..6765397 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "基于 Promise 的 HTTP 请求库,适用于各大小程序平台。", "main": "dist/cjs/axios-miniprogram.js", "module": "dist/esm/axios-miniprogram.js", - "types": "dist/@types/axios-miniprogram/index.d.ts", + "types": "dist/@types/index.d.ts", "files": [ "dist" ], @@ -47,6 +47,7 @@ "@types/jest": "^26.0.23", "@typescript-eslint/eslint-plugin": "^4.22.1", "@typescript-eslint/parser": "^4.22.1", + "dayjs": "^1.10.5", "eslint": "^7.26.0", "husky": "^6.0.0", "jest": "^26.6.3", @@ -63,8 +64,7 @@ "*.ts": [ "yarn lint", "yarn format", - "yarn test", - "yarn build" + "yarn test" ] } } diff --git a/rollup.config.js b/rollup.config.js index d94598c..00f3c2f 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -4,6 +4,7 @@ import { nodeResolve } from '@rollup/plugin-node-resolve'; import { babel } from '@rollup/plugin-babel'; import typescript from 'rollup-plugin-typescript2'; import commonjs from '@rollup/plugin-commonjs'; +import dayjs from 'dayjs'; import { DEFAULT_EXTENSIONS } from '@babel/core'; import filterEmptyLines from './scripts/@rollup/plugin-filter-empty-lines'; @@ -11,7 +12,6 @@ import pkg from './package.json'; const entryFilePath = path.resolve(__dirname, 'src/index.ts'); const distPath = path.resolve(__dirname, 'dist'); -const pkgName = pkg.name; const extensions = [].concat(DEFAULT_EXTENSIONS, '.ts'); const plugins = [ @@ -32,8 +32,18 @@ const plugins = [ filterEmptyLines(), ]; +const banner = `/** + * @name ${pkg.name} + * @description ${pkg.description} + * @version ${pkg.version} + * @date ${dayjs().format('YYYY-MM-DD HH:mm:ss')} + * @author ${pkg.author} + * @github ${pkg.repository.url} + * @issues ${pkg.bugs.url} + */`; + function resolveOutputFilePath(format) { - return path.resolve(distPath, format, `${pkgName}.js`); + return path.resolve(distPath, format, `${pkg.name}.js`); } function generateConfig(format) { @@ -42,9 +52,10 @@ function generateConfig(format) { output: { file: resolveOutputFilePath(format), format, - name: pkgName, + name: pkg.name, exports: 'default', indent: false, + banner, }, plugins, }; diff --git a/tsconfig.json b/tsconfig.json index 50e2eca..cf2f2e9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,7 +7,7 @@ "sourceMap": true, "strict": true, "declaration": true, - "declarationDir": "dist/@types/axios-miniprogram", + "declarationDir": "dist/@types", }, "include": ["src/**/*", "global.d.ts"], "exclude": ["node_modules"] diff --git a/yarn.lock b/yarn.lock index a6bf9c5..8f0f53e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2402,6 +2402,11 @@ date-fns@^1.27.2: resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-1.30.1.tgz#2e71bf0b119153dbb4cc4e88d9ea5acfb50dc05c" integrity sha512-hBSVCvSmWC+QypYObzwGOd9wqdDpOt+0wl0KbU+R+uuZBS1jN8VsD1ss3irQDknRj5NvxiTF6oj/nDRnN/UQNw== +dayjs@^1.10.5: + version "1.10.5" + resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.10.5.tgz#5600df4548fc2453b3f163ebb2abbe965ccfb986" + integrity sha512-BUFis41ikLz+65iH6LHQCDm4YPMj5r1YFLdupPIyM4SGcXMmtiLQ7U37i+hGS8urIuqe7I/ou3IS1jVc4nbN4g== + debug@^2.2.0, debug@^2.3.3: version "2.6.9" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"