@seayoo-web/request 3.2.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/dist/index.cjs +2 -2
- package/dist/index.js +71 -71
- package/dist/node.cjs +1 -1
- package/dist/node.js +13 -13
- package/dist/request.fetch-BqSnA_jT.cjs +1 -0
- package/dist/{request.fetch-D8zNsNGx.js → request.fetch-CLcd8XUK.js} +16 -16
- package/dist/retry-BltIjZ1L.cjs +3 -0
- package/dist/retry-D8V8lDdS.js +1159 -0
- package/dist/wx.cjs +1 -1
- package/dist/wx.js +2 -2
- package/package.json +2 -2
- package/types/inc/cache.d.ts +3 -2
- package/types/inc/type.d.ts +15 -1
- package/dist/request.fetch-Clr0F0uQ.cjs +0 -1
- package/dist/retry-CsPcCrZK.cjs +0 -3
- package/dist/retry-DQlh3z7q.js +0 -1106
package/dist/wx.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./retry-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./retry-BltIjZ1L.cjs"),l=async function(e,o,u){return t.handleResponse(await t.retryRequest(p,e,o,u),e,o,u)},p=async function(e,o,u){const s=await t.convertOptions(e,o,u),a=s.method==="PATCH"?"POST":s.method,c=t._e(s.url,s.params);return t.jt.wx?new Promise(d=>{wx.request({url:c,data:s.body,header:s.headers,method:a,dataType:"string",responseType:"text",fail(){d({url:c,method:a,status:-1,statusText:t.RequestInternalError.Unknown,body:""})},success(n){d({url:c,method:a,status:n.statusCode,statusText:n.statusCode+"",headers:{...n.header},body:s.method==="HEAD"||n.statusCode===204?"":f(n.data)})}})}):{url:c,method:a,status:-1,statusText:t.RequestInternalError.NotSupport,body:""}};function f(e){return typeof e=="string"?e:e instanceof ArrayBuffer&&t.jt.TextDecoder?new TextDecoder().decode(e):JSON.stringify(e)}function i(e){return new t.NetRequestHandler(l,e)}const r=i(),R=r.setConfig,y=r.head,g=r.get,q=r.post,h=r.del,x=r.put;exports.RequestInternalError=t.RequestInternalError;exports.getResponseRulesDescription=t.getResponseRulesDescription;exports.NetRequest=i;exports.del=h;exports.get=g;exports.head=y;exports.post=q;exports.put=x;exports.setGlobalConfig=R;
|
package/dist/wx.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { h as p, r as f, c as l,
|
|
2
|
-
import {
|
|
1
|
+
import { h as p, r as f, c as l, _ as h, j as i, a as d, N as x } from "./retry-D8V8lDdS.js";
|
|
2
|
+
import { g as H } from "./retry-D8V8lDdS.js";
|
|
3
3
|
const y = async function(t, n, r) {
|
|
4
4
|
return p(await f(g, t, n, r), t, n, r);
|
|
5
5
|
}, g = async function(t, n, r) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seayoo-web/request",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.0",
|
|
4
4
|
"description": "request tools for seayoo web",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"source": "./src/index.ts",
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"happy-dom": "^12.10.3",
|
|
61
61
|
"msw": "^2.7.0",
|
|
62
62
|
"vitest": "^3.0.5",
|
|
63
|
-
"@seayoo-web/utils": "^3.
|
|
63
|
+
"@seayoo-web/utils": "^3.6.2"
|
|
64
64
|
},
|
|
65
65
|
"scripts": {
|
|
66
66
|
"prebuild": "pnpm --F utils build",
|
package/types/inc/cache.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import { RequestCacheResolve } from "./type";
|
|
1
2
|
/** 为 get 请求并发而设计的缓冲工具 */
|
|
2
3
|
export declare class Cache<T = unknown> {
|
|
3
4
|
private ttl;
|
|
4
5
|
private cache;
|
|
5
6
|
constructor(ttl?: number);
|
|
6
|
-
getKey(url: string, param?: Record<string, unknown
|
|
7
|
+
getKey(method: string, url: string, param?: Record<string, unknown>, resolve?: RequestCacheResolve): string;
|
|
7
8
|
updateTTL(ttl: number): void;
|
|
8
9
|
get(key: string): Promise<T> | null;
|
|
9
|
-
set(key: string, action: Promise<T
|
|
10
|
+
set(key: string, action: Promise<T>, ttl?: number): void;
|
|
10
11
|
}
|
package/types/inc/type.d.ts
CHANGED
|
@@ -62,6 +62,8 @@ export interface IRetryRequestOptions {
|
|
|
62
62
|
method: string;
|
|
63
63
|
}) => number);
|
|
64
64
|
}
|
|
65
|
+
/** 计算请求缓冲key的函数 */
|
|
66
|
+
export type RequestCacheResolve = () => string | false;
|
|
65
67
|
export interface IOtherRequestOptions {
|
|
66
68
|
/**
|
|
67
69
|
* 如果设置为 false 则关闭通用提示
|
|
@@ -79,6 +81,16 @@ export interface IOtherRequestOptions {
|
|
|
79
81
|
});
|
|
80
82
|
/** 自定义 ajax response 解析策略 */
|
|
81
83
|
responseRule?: IResponseRule;
|
|
84
|
+
/**
|
|
85
|
+
* 用于设置请求的缓冲时长,单位 ms,建议不小于 100,默认 500。设置为 0 则不缓冲
|
|
86
|
+
*/
|
|
87
|
+
cacheTTL?: number;
|
|
88
|
+
/**
|
|
89
|
+
* 设置请求缓冲用的 key,返回非空字符串后将对请求进行缓存,时长为 cacheTTL
|
|
90
|
+
*
|
|
91
|
+
* get 请求默认按照参数为 key 进行缓冲,返回 false 或空字符串则不缓冲
|
|
92
|
+
*/
|
|
93
|
+
cacheResolve?: RequestCacheResolve;
|
|
82
94
|
}
|
|
83
95
|
/** 对外工具接口的请求配置 */
|
|
84
96
|
export type IRequestOptions = IBaseRequestOptions & IRetryRequestOptions & IOtherRequestOptions;
|
|
@@ -90,7 +102,9 @@ export type IRequestGlobalConfig = {
|
|
|
90
102
|
* 设置全局 url 基础路径,必须要以 / 开头 或者完整的 api 地址,比如 /api 或 https://api.server.com/path
|
|
91
103
|
*/
|
|
92
104
|
baseURL?: string;
|
|
93
|
-
/**
|
|
105
|
+
/**
|
|
106
|
+
* 用于设置请求的缓冲时长,单位 ms,建议不小于 100,默认 500。设置为 0 则不缓冲
|
|
107
|
+
*/
|
|
94
108
|
cacheTTL?: number;
|
|
95
109
|
/** 接口响应错误时的默认提示消息 */
|
|
96
110
|
defaultTypeGuardMessage?: string;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const s=require("./retry-CsPcCrZK.cjs"),E=async function(n,a,i){return s.handleResponse(await s.retryRequest(w,n,a,i),n,a,i)},w=async function(n,a,i){const t=await s.convertOptions(n,a,i),u=new URL(t.url),c=t.params;c instanceof Object&&Object.keys(c).forEach(e=>u.searchParams.set(e,c[e]));const r=s.jt.AbortController?new AbortController:null;function d(){r&&!r.signal.aborted&&r.abort()}t.abort&&t.abort.addEventListener("abort",d);let l=!1;const h=t.timeout>0?setTimeout(function(){l=!0,d()},t.timeout):null,f=t.method==="HEAD";return await fetch(u,{method:t.method,headers:Object.keys(t.headers).length>0?new Headers(t.headers):void 0,body:t.body,credentials:t.credentials,signal:r==null?void 0:r.signal,redirect:"follow"}).then(async e=>{const o={url:u.toString(),method:t.method,status:e.status,statusText:e.statusText,headers:s.fromEntries([...e.headers.entries()])},b=f||e.status===204?"":await e.text().catch(m=>m);return b instanceof Error?{...o,body:"",statusText:s.RequestInternalError.Unknown,rawError:b}:{...o,body:b}}).catch(e=>{const o=r==null?void 0:r.signal.aborted;return{url:u.toString(),method:t.method,status:o&&!l?0:-1,statusText:l?s.RequestInternalError.Timeout:o?s.RequestInternalError.Aborted:s.RequestInternalError.NetworkError,body:"",rawError:e}}).finally(()=>{h!==null&&clearTimeout(h),t.abort&&t.abort.removeEventListener("abort",d)})};exports.fetchRequest=E;
|
package/dist/retry-CsPcCrZK.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
"use strict";var ot=Object.defineProperty;var at=(e,t,s)=>t in e?ot(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var v=(e,t,s)=>at(e,typeof t!="symbol"?t+"":t,s);var lt=Object.defineProperty,ut=(e,t,s)=>t in e?lt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,o=(e,t,s)=>ut(e,typeof t!="symbol"?t+"":t,s);const u=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),j={wx:"wx"in u&&N(u.wx)&&"getSystemInfo"in u.wx&&m(u.wx.getSystemInfo),fetch:"fetch"in u&&m(u.fetch),window:"window"in u&&N(u.window),requestAnimationFrame:"requestAnimationFrame"in u&&m(u.requestAnimationFrame),localStorage:"localStorage"in u&&N(u.localStorage)&&"getItem"in u.localStorage&&m(u.localStorage.getItem),sessionStorage:"sessionStorage"in u&&N(u.sessionStorage)&&"getItem"in u.sessionStorage&&m(u.sessionStorage.getItem),File:"File"in u&&m(u.File),Blob:"Blob"in u&&m(u.Blob),Proxy:"Proxy"in u&&m(u.Proxy),Request:"Request"in u&&m(u.Request),FormData:"FormData"in u&&m(u.FormData),TextDecoder:"TextDecoder"in u&&m(u.TextDecoder),ResizeObserver:"ResizeObserver"in u&&m(u.ResizeObserver),AbortController:"AbortController"in u&&m(u.AbortController),URLSearchParams:"URLSearchParams"in u&&m(u.URLSearchParams)};function m(e){return typeof e=="function"}function N(e){return typeof e=="object"&&e!==null}function ht(e){return new Promise(t=>setTimeout(t,Math.max(0,e)))}function Q(){}function Y(e,t){const s={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console)},r=`[${e}]`;return["log","error","warn"].forEach(n=>{const i=console[n];s[n]=(...a)=>{i.apply(console,[r,...a])}}),s}function ct(e){const t=e||"CustomError";return class extends Error{constructor(s){super(s),Object.defineProperty(this,"name",{value:t,enumerable:!1,configurable:!0}),"setPrototypeOf"in Object&&Object.setPrototypeOf(this,new.target.prototype),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,this.constructor)}}}const ft=/^(?:https?:)?\/\/.+$/i,dt=/^https?:\/\/.+$/i,mt=/^\{[\d\D]*\}$/,_t=/^\[[\d\D]*\]$/;function gt(e){return typeof e=="string"}function F(e,t=!1){return t?ft.test(e):dt.test(e)}function pt(e){return e==null}function tt(e,...t){return e!==null&&typeof e=="object"&&!(e instanceof Map)&&!(e instanceof Set)&&!(e instanceof WeakMap)&&!(e instanceof WeakSet)&&!Array.isArray(e)&&t.every(s=>s in e)}function k(e,...t){if(!e||typeof e!="object")return!1;const s=Object.getPrototypeOf(e);return s!==Object.prototype&&s!==null?!1:t.every(r=>r in e)}function I(e,t){return Array.isArray(e)&&e.every(s=>t(s))}function A(e){if(typeof e!="number"||Number.isNaN(e)||!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))return!1;if(e===0)return!0;const t=Math.abs(e);return t>=Number.EPSILON&&t<=Number.MAX_SAFE_INTEGER}function et(e){return mt.test(e)||_t.test(e)}function bt(e,t=20){const s=Math.max(t,10),r=[...e];return r.length<=s?e:r.slice(0,s-3).join("")+"..."}function U(e,t){try{const s=JSON.parse(e);return t?t(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);Y("LoadUtils");async function yt(e){return await new Promise(function(t){const s=document.getElementsByTagName("head")[0],r=document.createElement("script");r.setAttribute("type","text/javascript"),r.setAttribute("charset","utf-8"),r.onload=function(){s.removeChild(r),t(!0)},r.onerror=function(){s.removeChild(r),t(!1)},r.setAttribute("src",e),s.appendChild(r)})}function J(e){return Object.getOwnPropertyNames(e).forEach(function(t){delete e[t]}),e}const g=Y("Validator");function x(e){return e?`"${bt(e).replace(/"/g,'\\"')}"`:"empty string"}function T(e){return typeof e=="object"&&e&&"constructor"in e&&typeof e.constructor=="function"?e.constructor.name||"ClassInstance":Object.prototype.toString.call(e).replace(/(?:.+ |]$)/g,"")}function S(e){return typeof e=="bigint"}function l(e){return new Error(`${e?`${e}()`:"method"} is not allowed after locked`)}class q{constructor(){o(this,"_ps",{}),o(this,"_allow",[]),o(this,"_reject",[]),o(this,"_locked",!1),o(this,"_opt",!1),o(this,"_null",!1)}pattern(t,s){if(this._locked)throw l("pattern");return this._ps[`#${t||"custom"}`]=s,this}url(t=!1){if(this._locked)throw l("url");return this._ps.url=t?/^(?:https?:)?\/\/.+$/i:/^https?:\/\/.+$/i,this}dataUri(){if(this._locked)throw l("dataUri");return this._ps.dataUri=/^data:[a-z]+\/[a-z]+;base64,[\w+/=]+$/,this}enum(...t){if(this._locked)throw l("enum");const s=t[0];return I(t,gt)?(this._allow=t,J(this._ps)):k(s)&&(this._allow=Object.values(s).map(r=>`${r}`),J(this._ps)),this}disallow(...t){return this._reject.push(...t),this}optional(){if(this._locked)throw l("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw l("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const t=new q;return t._ps={...this._ps},t._allow=[...this._allow],t._reject=[...this._reject],t._locked=!1,t}validate(t,s=g.warn){if(t===void 0)return this._opt||(s("should be a string, but got undefined"),!1);if(t===null)return this._null||(s("should be a string, but got null"),!1);if(typeof t!="string")return s(`should be a string, but got ${typeof t}`),!1;if(this._allow.length>0)return this._allow.includes(t)||(s(`${x(t)} is not allowed, just support ${this._allow.map(x).join(", ")}`),!1);if(this._reject.length>0&&this._reject.some(n=>typeof n=="string"?n===t:n.test(t)))return s(`${x(t)} is not allowed`),!1;const r=Object.keys(this._ps);return r.length>0&&!r.some(n=>{const i=this._ps[n];return i instanceof RegExp?i.test(t):i(t)})?(s(`${x(t)} is not match pattern ${r.join(" | ")}`),!1):!0}}class C{constructor(){o(this,"_int",!1),o(this,"_min",-1/0),o(this,"_max",1/0),o(this,"_allow",[]),o(this,"_reject",[]),o(this,"_infinite",!1),o(this,"_unsafe",!1),o(this,"_nan",!1),o(this,"_locked",!1),o(this,"_opt",!1),o(this,"_null",!1)}int(){if(this._locked)throw l("int");return this._int=!0,this}min(t){if(this._locked)throw l("min");return Number.isNaN(t)||(this._min=t),this}max(t){if(this._locked)throw l("max");return Number.isNaN(t)||(this._max=t),this}allowNaN(){if(this._locked)throw l("allowNaN");return this._nan=!0,this}allowInfinity(){if(this._locked)throw l("allowInfinity");return this._infinite=!0,this._unsafe=!0,this}unsafe(){if(this._locked)throw l("unsafe");return this._unsafe=!0,this}enum(...t){if(this._locked)throw l("enum");const s=t[0];return I(t,A)?(this._allow=t,this._reject=[]):k(s)&&(this._allow=Object.values(s).map(r=>A(r)?r:null).filter(r=>r!==null),this._reject=[]),this}disallow(...t){if(this._locked)throw l("disallow");return this._reject.push(...t),this}optional(){if(this._locked)throw l("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw l("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const t=new C;return t._int=this._int,t._min=this._min,t._max=this._max,t._allow=[...this._allow],t._reject=[...this._reject],t._infinite=this._infinite,t._unsafe=this._unsafe,t._nan=this._nan,t._locked=!1,t}validate(t,s=g.warn){return t===void 0?this._opt||(s("should be a number, but got undefined"),!1):t===null?this._null||(s("should be a number, but got null"),!1):typeof t!="number"?(s(`should be a number, but got ${typeof t}`),!1):Number.isNaN(t)?this._nan||(s("should be a number, but got NaN"),!1):!Number.isFinite(t)&&!this._infinite?(s("should be a number, but got Infinity"),!1):this._allow.length>0?this._allow.includes(t)||(s(`${t} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(t)?(s(`${t} is not allowed`),!1):this._int&&Math.ceil(t)!==t?(s(`${t} is not an integer`),!1):!A(t)&&!this._unsafe?(s(`${t} is not a safe number`),!1):t>=this._min&&t<=this._max||(s(`${t} is not in range [${this._min}, ${this._max}]`),!1)}}class D{constructor(){o(this,"_min",null),o(this,"_max",null),o(this,"_allow",[]),o(this,"_reject",[]),o(this,"_locked",!1),o(this,"_opt",!1),o(this,"_null",!1)}min(t){if(this._locked)throw l("min");return this._min=t,this}max(t){if(this._locked)throw l("max");return this._max=t,this}enum(...t){if(this._locked)throw l("enum");const s=t[0];return I(t,S)?(this._allow=t,this._reject=[]):k(s)&&(this._allow=Object.values(s).map(r=>S(r)?r:null).filter(r=>r!==null),this._reject=[]),this}disallow(...t){if(this._locked)throw l("disallow");return this._reject.push(...t),this}optional(){if(this._locked)throw l("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw l("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const t=new D;return t._min=this._min,t._max=this._max,t._allow=[...this._allow],t._reject=[...this._reject],t._locked=!1,t}validate(t,s=g.warn){return t===void 0?this._opt||(s("should be a bigint, but got undefined"),!1):t===null?this._null||(s("should be a bigint, but got null"),!1):S(t)?this._allow.length>0?this._allow.includes(t)||(s(`${t} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(t)?(s(`${t} is not allowed`),!1):(this._min!==null?t>=this._min:!0)&&(this._max!==null?t<=this._max:!0)||(s(`${t} is not in range [${this._min===null?-1/0:this._min}, ${this._max===null?1/0:this._max}]`),!1):(s(`should be a bigint, but got ${typeof t}`),!1)}}class L{constructor(){o(this,"_locked",!1),o(this,"_opt",!1),o(this,"_null",!1)}optional(){if(this._locked)throw l("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw l("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new L}validate(t,s=g.warn){return t===void 0?this._opt||(s("should be a boolean, but got undefined"),!1):t===null?this._null||(s("should be a boolean, but got null"),!1):typeof t!="boolean"?(s(`should be a boolean, but got ${typeof t}`),!1):!0}}class R{constructor(t){o(this,"_shape"),o(this,"_plain",!1),o(this,"_locked",!1),o(this,"_opt",!1),o(this,"_null",!1),this._shape=t}plain(){if(this._locked)throw l("plain");return this._plain=!0,this}optional(){if(this._locked)throw l("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw l("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}get shape(){return{...this._shape}}clone(){const t=new R(this._shape);return t._plain=this._plain,t._locked=!1,t}match(t,s){return t in this._shape?this._shape[t].validate(s,Q):!1}validate(t,s=g.warn){return t===void 0?this._opt||(s("should be a object, but got undefined"),!1):t===null?this._null||(s("should be a object, but got null"),!1):tt(t)?this._plain&&!k(t)?(s(`should be a plain object, but got ${T(t)}`),!1):Object.keys(this._shape).every(r=>this._shape[r].validate(t[r],(...n)=>{s(`[.${String(r)}]`,...n)})):(s(`should be a object, but got ${T(t)}`),!1)}}class B{constructor(t){o(this,"_val"),o(this,"_locked",!1),o(this,"_opt",!1),o(this,"_null",!1),this._val=t}optional(){if(this._locked)throw l("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw l("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new B(this._val)}validate(t,s=g.warn){return t===void 0?this._opt||(s("should be a record, but got undefined"),!1):t===null?this._null||(s("should be a record, but got null"),!1):k(t)?Object.keys(t).every(r=>this._val.validate(t[r],(...n)=>{s(`[:${r}]`,...n)})):(s(`should be a record, but got ${T(t)}`),!1)}}class H{constructor(t){o(this,"_val"),o(this,"_min",0),o(this,"_max",1/0),o(this,"_locked",!1),o(this,"_opt",!1),o(this,"_null",!1),this._val=t}min(t){if(this._locked)throw l("min");return this._min=t,this}max(t){if(this._locked)throw l("max");return this._max=t,this}optional(){if(this._locked)throw l("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw l("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const t=new H(this._val);return t._min=this._min,t._max=this._max,t._locked=!1,t}validate(t,s=g.warn){return t===void 0?this._opt||(s("should be a array, but got undefined"),!1):t===null?this._null||(s("should be a array, but got null"),!1):Array.isArray(t)?t.length<this._min||t.length>this._max?(this._min===this._max?s(`should be a array with length ${this._min}`):s(`should be a array with length between ${this._min} and ${this._max}`),!1):t.every((r,n)=>this._val.validate(r,(...i)=>{s(`[${n}]`,...i)})):(s(`should be a array, but got ${typeof t}`),!1)}}class z{constructor(...t){o(this,"_vs"),o(this,"_locked",!1),o(this,"_opt",!1),o(this,"_null",!1),this._vs=t}optional(){if(this._locked)throw l("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw l("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new z(...this._vs)}validate(t,s=g.warn){return t===void 0?this._opt||(s("should be a tuple, but got undefined"),!1):t===null?this._null||(s("should be a tuple, but got null"),!1):Array.isArray(t)?t.length!==this._vs.length?(s(`should be a tuple with length ${this._vs.length}, but got ${t.length}`),!1):this._vs.every((r,n)=>r.validate(t[n],(...i)=>{s(`[idx:${n}]`,...i)})):(s(`should be a tuple, but got ${typeof t}`),!1)}}class G{constructor(...t){o(this,"_vs"),o(this,"_key",""),o(this,"_locked",!1),o(this,"_opt",!1),o(this,"_null",!1),this._vs=t}optional(){if(this._locked)throw l("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw l("maybeNull");return this._null=!0,this}key(t){if(this._locked)throw l("key");return this._vs.every(s=>s instanceof R)?this._key=t:g.warn("union type key can only be used when all validators are ObjectValidator"),this}satisfies(){return this}lock(){return this._locked=!0,this}get validators(){return[...this._vs]}clone(){const t=new G(...this._vs);return t._key=this._key,t._locked=!1,t}validate(t,s=g.warn){if(t===void 0)return this._opt||(s("should be a union, but got undefined"),!1);if(t===null)return this._null||(s("should be a union, but got null"),!1);if(this._key&&tt(t)&&t){const n=t[this._key];if(n===void 0)return s(`key field "${this._key}" is not found`,t),!1;const i=this._vs.find(a=>a instanceof R&&a.match(this._key,n));return i?i.validate(t,s):(s(`key field "${this._key}" value is match union definition`,n),!1)}const r=this._vs.some(n=>n.validate(t,Q));return r||s("value is not match union definition",t),r}}class O{constructor(t,s){o(this,"_name",""),o(this,"_guard"),o(this,"_locked",!1),o(this,"_opt",!1),o(this,"_null",!1),this._name=t,this._guard=s}optional(){if(this._locked)throw l("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw l("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new O(this._name,this._guard)}validate(t,s=g.warn){const r=this._name||"custom type";return t===void 0?this._opt||(s(`should be ${r}, but got undefined`),!1):t===null?this._null||(s(`should be ${r}, but got null`),!1):this._guard(t)||(s(`custom validation${this._name?`(${this._name})`:""} failed`),!1)}}function wt(e,t){if(typeof e=="string"){if(!t)throw new Error("custom type guard must be defined");return new O(e,t)}return new O("",e)}const kt={shape(e){return e},define(e){return e},guard(e){return function(t){return e.validate(t)}},object(e){return new R(e)},record(e){return new B(e)},array(e){return new H(e)},tuple(...e){return new z(...e)},union(...e){return new G(...e)},string(){return new q},bool(){return new L},number(){return new C},bigint(){return new D},custom:wt,unknown(){return{validate(e){return!0}}},never(){return{validate(e){return!1}}}},vt=e=>k(e)&&Object.keys(e).length===0;kt.custom("EmptyObject",vt);function $t(e,t="数据未能正确识别"){return typeof e=="function"?{guard:e,message:t}:{guard:e.guard,message:e.message||t}}function jt(e,t=""){return!t||F(e,!0)?V(e):(V(t)+"/"+e).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function V(e){return F(e,!0)?e.startsWith("http")?e:("location"in globalThis?location.protocol:"https:")+e:("location"in globalThis?location.origin:"http://127.0.0.1")+"/"+e.replace(/^\/+/,"")}function Rt(e,t){const s={};return(e.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(r){const n=r.split("="),i=n[0],a=decodeURIComponent(n[1]||"");s[i]!==void 0?s[i]+=","+a:s[i]=a}),t!==!0?s[t]||"":s}function Et(e,t){if(t){if(t===!0)return e.replace(/\?[^#]*/,"")}else return e;const s=e.split("#"),r=s[0].split("?"),n=r[0],i=r.length>1?r[1]:"",a=s.length>1?"#"+s[1]:"",h=typeof t=="string"?[t]:Array.isArray(t)?t:[];return!h.length||!i?s[0]+a:(h.map(c=>c.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(n+"?"+i.replace(new RegExp("(?:^|&)(?:"+h.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+a)}function Nt(e,t,s=!1){const r=typeof t=="string"?t:Object.keys(t).map(a=>`${a}=${encodeURIComponent(t[a])}`).join("&");if(!r)return e;const n=e.split("#");s&&(n[0]=Et(n[0],(r.match(/([^=&#?]+)=[^&#]+/g)||[]).map(a=>a.replace(/=.+$/,""))));const i=n[0].indexOf("?")+1?"&":"?";return(n[0]+i+r+(n.length>1?"#"+n[1]:"")).replace(/\?&/,"?")}function xt(e){const t=e.match(/(?:\?|&)([^=]+)(?:&|$)/g);return t?t.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class Ot{constructor(t=500){v(this,"ttl");v(this,"cache");this.cache={},this.ttl=Math.max(t,0)}getKey(t,s){const r=t.replace(/#.+/,""),n=r.replace(/\?.+/g,""),i=Object.assign(Rt(r,!0),s),a=xt(r),h=Object.keys(i).sort().map(c=>`${c}#${i[c]}`);return`${n}_${h.join(",")}_${a.join(",")}`}updateTTL(t){this.ttl=Math.max(t,0)}get(t){if(this.ttl===0)return null;const s=this.cache[t];return s?s.ttl<Date.now()?(delete this.cache[t],null):s.res:null}set(t,s){this.ttl!==0&&(this.cache[t]={ttl:Date.now()+this.ttl,res:s})}}class st{constructor(t){v(this,"config",{baseURL:"/",maxRetry:0,retryInterval:100,retryResolve:"network",timeout:1e4,cacheTTL:500,credentials:"same-origin",defaultTypeGuardMessage:"响应数据未能正确识别",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}});t&&this.set(t)}set(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!F(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)}get(t){return this.config[t]}getFullUrl(t){return jt(t,this.config.baseURL)}showMessage(t,s,r,n){this.config.messageHandler&&s&&this.config.messageHandler(t,s,r,n)}}const K={UnexpectResponse:"UnexpectResponse",Aborted:"Aborted",Unknown:"Unknown",NetworkError:"NetworkError",Timeout:"Timeout",NotSupport:"NotSupport",URLFormatError:"URLFormatError"};function Ft(e,t,s,r){if(t.ok&&!pt(t.data)&&r){const n=$t(r,s.get("defaultTypeGuardMessage"));return n.guard(t.data)||(t.code=K.UnexpectResponse,s.showMessage(!0,`${e} ${n.message}`,t.code,t.status),console.error(t.code,e,t.data),t.data=null,t.message=n.message),t}return t}class At{constructor(t,s){v(this,"agent");v(this,"config");v(this,"cache");this.config=new st(s),this.agent=t,this.cache=new Ot(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.request=this.request.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}async request(t,s){try{return await this.agent(t,this.config,s)}catch(r){return console.error("RequestError",r),{ok:!1,status:-9,code:K.Unknown,message:r instanceof Error?`${r.message}
|
|
2
|
-
${r.stack||""}`:String(r),headers:{},data:null}}}async guard(t,s,r){return Ft(t,s,this.config,r)}setConfig(t){this.config.set(t),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(t){return this.config.get(t)}async head(t,s){const r=Object.assign({},s||null);return r.method="HEAD",this.guard(t,await this.request(t,r),null)}async get(t,s,r){const n=Object.assign({},r||null);n.method="GET";const i=this.cache.getKey(t,n.params),a=this.cache.get(i);if(a)return this.guard(t,await a,s||null);const h=this.request(t,n);return this.cache.set(i,h),this.guard(t,await h,s||null)}async post(t,s,r,n){const i=Object.assign({},n||null);return i.method="POST",i.body=s||{},this.guard(t,await this.request(t,i),r||null)}async del(t,s,r){const n=Object.assign({},r||null);return n.method="DELETE",this.guard(t,await this.request(t,n),s||null)}async put(t,s,r,n){const i=Object.assign({},n||null);return i.method="PUT",i.body=s||{},this.guard(t,await this.request(t,i),r||null)}async patch(t,s,r,n){const i=Object.assign({},n||null);return i.method="PATCH",i.body=s||{},this.guard(t,await this.request(t,i),r||null)}}async function St(e,t,s){var y;const r=Object.assign({method:"GET"},s),n=j.FormData?r.body instanceof FormData:!1,i=n&&r.method!=="POST"&&r.method!=="PUT"?"POST":r.method,a=i==="GET"||i==="HEAD"||i==="DELETE";a&&r.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete r.body);const h=Object.assign(n||a?{}:{"Content-Type":j.Blob&&r.body instanceof Blob?r.body.type||"application/octet-stream":"application/json;charset=utf-8"},r.headers),c=r.params||{},_={};Object.keys(c).forEach($=>{c[$]!==void 0&&(_[$]=Ut(c[$]))});const f=t.getFullUrl(e),d=Tt(r.body),p=r.timeout||t.get("timeout"),b=await async function(){const $=t.get("requestTransformer");if($)return await $({headers:h,params:_,method:i,url:f,body:d})}(),w=typeof b=="string"&&b?b:f;return(y=t.get("logHandler"))==null||y({type:"ready",url:w,method:i,headers:h,timeout:p,body:d}),{url:w,method:i,body:d,params:_,headers:h,timeout:p,abort:r.abort,credentials:r.credentials||t.get("credentials")}}function Ut(e){return typeof e=="string"?e:Array.isArray(e)?e.join(","):e+""}function Tt(e){if(e)return typeof e=="string"||j.URLSearchParams&&e instanceof URLSearchParams||e instanceof ArrayBuffer||j.Blob&&e instanceof Blob||j.FormData&&e instanceof FormData?e:JSON.stringify(e)}const rt="data",E="message";function Mt(e,t,s,r,n){const i=n||r;return W(e)?Bt(i.ok||r.ok,e,t,s):It(i.failed||r.failed,t,s)}const Pt=function(e){const t=[],s=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),s.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(s.messageField||E)+" 作为错误消息");break}const r=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),r.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(r.dataField||rt)+" 作为响应数据,读取 "+(r.messageField||E)+" 作为提示消息"),r.statusField&&t.push(" 当 "+r.statusField+" 为 "+(r.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),r.ignoreMessage&&t.push(" 并忽略以下消息:"+r.ignoreMessage);break}return t.join(`
|
|
3
|
-
`)};function It(e,t,s){const r=e||{resolve:"json",messageField:E},n={ok:!1,code:t,message:s,data:null};switch(r.resolve){case"body":n.message=Z(s)||s;break;case"json":const{code:i,message:a}=qt(s,r.converter,r.statusField,r.messageField);n.code=i||t,n.message=Z(s)||a;break}return n}function qt(e,t,s,r=E){if(!et(e))return{message:""};const n=P(U(e),t);return!n||!k(n)?{message:e}:{code:s?M(n,s):"",message:M(n,r)||e}}function M(e,t){const s=Array.isArray(t)?t:[t];for(const r of s)if(r in e)return Ct(e[r]);return""}function Ct(e){return e?typeof e=="string"?e:JSON.stringify(e):""}const Dt=/<title>([^<]+)<\/title>/i,Lt=/<message>([^<]+)<\/message>/i;function Z(e){const t=e.match(Dt);if(t)return t[1];const s=e.match(Lt);return s?s[1]:""}function Bt(e,t,s,r){const n=e||{resolve:"body"},i={ok:!0,code:s,message:"",data:null};if(t===204||!r)return i;if(n.resolve==="body")return i.data=et(r)?P(U(r),e.converter):r,i;const a=P(U(r),e.converter);if(!a||!k(a))return i.ok=!1,i.code="ResponseFormatError",i.message="响应内容无法格式化为 Object",i;const h=n.statusField,c=n.statusOKValue||"",_=n.dataField||rt,f=n.messageField||E,d=n.ignoreMessage||"";if(h&&!(h in a))return i.ok=!1,i.code="ResponseFieldMissing",i.message="响应内容找不到状态字段 "+h,i;const p=h?a[h]+"":"";return i.ok=h?p===c:!0,i.code=p||s,i.data=_===!0?a:_ in a?a[_]:null,i.message=M(a,f),d&&i.message&&(Array.isArray(d)&&d.includes(i.message)||typeof d=="string"&&i.message===d)&&(i.message=""),i}function W(e){return e>=200&&e<400}function P(e,t){return t?typeof t=="function"?t(e):(console.warn('工具不再支持 "camelize", "snakify" 参数,请自行提供函数来转化 body 内容'),e):e}const Ht=ct("APIError");function zt(e){const t={};for(const n in e.headers)(n.startsWith("x-")||n.includes("trace")||n.includes("server")||/\b(?:id|uuid)\b/.test(n))&&(t[n]=e.headers[n]);const s=e.url.replace(/^(?:https?:)?\/*/i,"").replace(/\?.+/,""),r=e.status<0?"unknown":e.status;return{sentryError:new Ht(`${s} | ${r}${e.code?` | ${e.code}`:""}`),sentryTags:{...t,status:r,method:e.method,code:e.code||"unknown",message:e.message||"empty"},sentryExtra:{url:e.url,responseBody:e.body||"empty",responseHeaders:e.headers,rawError:e.error}}}function nt(e){return e.reduce((t,[s,r])=>(s&&(t[s]=r||""),t),{})}function Gt(e,t,s,r){var b;const n=e.status,i=e.method,a=nt(Object.entries(e.headers||{}).map(([w,y])=>[w.toLowerCase(),y])),{ok:h,code:c,data:_,message:f}=Mt(n,e.statusText,e.body,s.get("responseRule"),r==null?void 0:r.responseRule);if(!W(n)){const w=zt({url:e.url,method:e.method,status:n,code:c,message:f,body:e.body,headers:a,error:e.rawError});(s.get("errorHandler")||Kt)({url:t,method:i,status:n,code:c,message:f,headers:a,rawError:e.rawError,responseBody:e.body,...w})}if(n<0)return X({ok:!1,status:n,code:e.statusText,headers:{},message:"",data:null},`${i} ${t} ${e.statusText}`,i,t,s,r);const d={ok:h,data:_,code:c,message:f,status:n,headers:a};(b=s.get("responseHandler"))==null||b({...d},i,t);const p=h?f:f||e.statusText;return X(d,p,i,t,s,r)}function X(e,t,s,r,n,i){const a=n.get("message"),h=a===!1||(i==null?void 0:i.message)===!1?!1:(i==null?void 0:i.message)||a;if(h!==!1){const c=typeof h=="function"?h(e,s,r,t):t;c instanceof Error?n.showMessage(!0,c.message,e.code,e.status):c&&typeof c=="object"&&"message"in c?n.showMessage(!1,c.message,e.code,e.status):n.showMessage(!e.ok,c,e.code,e.status)}return e}function Kt(e){const t={};for(const s in e)s.startsWith("sentry")||(t[s]=e[s]);console.error("RequestError",t)}async function it(e,t,s,r,n){const i=n||0,a=Math.max(0,Math.min(10,(r==null?void 0:r.maxRetry)??s.get("maxRetry")??0)),h=(r==null?void 0:r.retryResolve)??s.get("retryResolve"),c=s.get("logHandler");c==null||c({type:"prepare",url:t,method:(r==null?void 0:r.method)||"GET",retry:i,maxRetry:a,message:i===0?"start":`retry ${i}/${a} start`,headers:r==null?void 0:r.headers,options:r});const _=Date.now(),f=await e(t,s,r),d=f.status,p=Date.now()-_,b=`[cost ${p}][${d}] ${d<0?f.body:""}`;c==null||c({type:"finished",url:t,method:f.method,retry:i,maxRetry:a,message:i===0?`finish ${b}`:`retry ${i}/${a} finish ${b}`,response:f,headers:f.headers,cost:p});const w=W(d);if(!a||i>=a||h==="network"&&d>0||h==="status"&&w||Array.isArray(h)&&!h.includes(d)||typeof h=="function"&&h(f,i)!==!0)return f;const y=(r==null?void 0:r.retryInterval)??s.get("retryInterval")??100;return await ht(Math.max(100,y==="2EB"?Math.pow(2,i)*100:typeof y=="function"?y(i+1,{url:t,status:d,method:f.method})||0:y)),await it(e,t,s,r,i+1)}exports.At=F;exports.NetRequestHandler=At;exports.RequestGlobalConfig=st;exports.RequestInternalError=K;exports.ce=yt;exports.convertOptions=St;exports.fromEntries=nt;exports.ge=Nt;exports.getResponseRulesDescription=Pt;exports.handleResponse=Gt;exports.jt=j;exports.retryRequest=it;
|