@seayoo-web/request 0.4.2 → 0.6.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 CHANGED
@@ -4,21 +4,19 @@
4
4
 
5
5
  市面上流行的网络请求工具有以下一些限制或不足:
6
6
 
7
- 1. 对 ts 支持度不够好,需要额外安装三方 types 声明
8
- 2. 流行的几个工具均不支持重试配置
7
+ 1. 体积过大
8
+ 2. 流行的几个 request 工具均不支持重试配置
9
9
  3. 对响应结果不进行更多检查(无类型守卫,无结构分析),无法完美对接 ts 代码
10
- 4. 支持多端的工具(如 axios)不支持 treeshaking
11
- 5. 支持的参数过于冗余,而相当多代码实际开发中使用不到
10
+ 4. 功能过于冗余,而相当多特性实际开发中使用不到
12
11
 
13
12
  ## 特性
14
13
 
15
- 1. 默认基于 fetch,在前端使用场景可大幅降低代码量
14
+ 1. 默认基于 fetch,请求和响应均 基于 json 或 text(不支持其他格式)
16
15
  2. 支持重试配置 maxRry / retryResolve / retryInterval
17
- 3. 支持响应结果处理策略 responseRule
16
+ 3. 支持响应结果处理策略 responseRule 和通用提示配置
18
17
  4. 支持类型守卫 typeGuard
19
18
  5. 支持多实例,多端(浏览器,nodejs,并可以扩展小程序)
20
- 6. 支持 treeshaking
21
- 7. get 请求函数支持并发缓存(缓存 500ms)
19
+ 7. get 请求函数支持并发缓存(默认缓存 500ms)
22
20
  8. 函数永不抛错,返回固定解析结构 { ok, data, status, headers, code, message }
23
21
  9. 提供 jsonp / jsonx 函数,支持带上传进度的 upload 函数
24
22
 
@@ -46,10 +44,15 @@ export async function getUserList(): Promise<IUser[]> {
46
44
  ## 配置响应规则
47
45
 
48
46
  ```js
47
+ // 浏览器环境
49
48
  const { setGlobalConfig } from "@seayoo-web/request"
49
+ // nodejs 环境
50
+ const { setGlobalConfig } from "@seayoo-web/request/node"
51
+
50
52
  // 以下是默认的全局配置(更多介绍请参考下方全局配置)
51
53
  setGlobalConfig({
52
54
  // api 基础路径,默认根目录,通常可以设置为 /api
55
+ // nodejs 环境下此配置无效
53
56
  baseURL: "",
54
57
  // 响应解析规则
55
58
  responseRule: {
@@ -57,46 +60,27 @@ setGlobalConfig({
57
60
  ok: { resolve: "body" },
58
61
  // status 失败时解析策略:将响应体解析为 json 并读取 message 字段作为错误消息
59
62
  failed: { resolve: "json", messageField: "message" }
60
- }
63
+ },
64
+ // 更多全局配置参考下方介绍
61
65
  })
62
66
  ```
63
67
 
64
68
  ## 全局函数和自创建实例
65
69
 
66
70
  ```js
67
- // 以下为全局导出的工具函数
68
- const { get, post, put, patch, del } from "@seayoo-web/request"
69
-
70
- // 自定义创建实例
71
- const { NetRequest } from "@seayoo-web/request"
72
- const { get, post, put, patch, del, setConfig } = new NetRequest()
73
- ```
74
-
75
- ## 更换 RequestAgent
71
+ // 以下为浏览器环境全局默认导出的工具函数
72
+ const { get, post, put, patch, del, head } from "@seayoo-web/request"
76
73
 
77
- 内置提供三个 RequestAgent: fetchRequest, xhRequest, nodeRequest,更换方法如下:
74
+ // 以下是 nodejs 环境全局默认导出的工具函数
75
+ const { get, post, put, patch, del, head } from "@seayoo-web/request/node"
78
76
 
79
- ```js
80
- // 设置为 nodejs 环境使用的 nodeRequest
81
- const { setGlobalAgent, nodeRequest } from "@seayoo-web/request"
82
- setGlobalAgent(nodeRequest)
83
-
84
- // 如果要兼容 IE11,则可以更换使用 xhr
85
- const { setGlobalAgent, xhRequest } from "@seayoo-web/request"
86
- setGlobalAgent(xhRequest)
87
-
88
- // 可以增加环境自动判断
89
- const { setGlobalAgent, xmlHttpRequest } from "@seayoo-web/request"
90
- if(!("Fetch" in window)) {
91
- setGlobalAgent(xhRequest)
92
- }
77
+ // 浏览器环境自定义创建实例
78
+ const { NetRequest } from "@seayoo-web/request"
79
+ const { get, post, put, patch, del, setConfig } = NetRequest()
93
80
 
94
- // 自定义实例更换 RequestAgent
95
- const { NetRequest, nodeRequest, fetchRequest } from "@seayoo-web/request"
96
- // 可以 new 时传递
97
- const { get, post, setAgent } = new NetRequest({}, nodeRequest)
98
- // 也可以随时修改
99
- setAgent(fetchRequest)
81
+ // nodejs环境自定义创建实例
82
+ const { NetRequest } from "@seayoo-web/request/node"
83
+ const { get, post, put, patch, del, setConfig } = NetRequest()
100
84
  ```
101
85
 
102
86
  ## 全局配置参数
@@ -110,7 +94,7 @@ setGlobalConfig({ baseURL: "/api" })
110
94
  // 自定义实例全局配置是独立的
111
95
  const { NetRequest } from "@seayoo-web/request"
112
96
  // 可以 new 时传递
113
- const { get, post, setConfig } = new NetRequest({ baseURL: "/api" })
97
+ const { get, post, setConfig } = NetRequest({ baseURL: "/api" })
114
98
  // 也可以随时修改
115
99
  setConfig({ timeout: 5000 })
116
100
  ```
@@ -124,13 +108,17 @@ setConfig({ timeout: 5000 })
124
108
  1. 请求时传入的 url 为完整 url,即以 http:// 或 https:// 开头
125
109
  2. 请求时传入的 url 以 / 开头
126
110
 
111
+ 此条配置仅针对浏览器生效;
112
+
127
113
  ### credentials
128
114
 
129
115
  类型:"omit" | "same-origin" | "include"
130
116
 
131
117
  说明:是否携带用户认证信息(cookie, basic http auth 等),默认 "same-orgin",当需要跨域发送 cookie 时可以设置为 include;当需要明确忽略 cookie(比如认证信息已经放入自定义 header 头)时,可以设置为 omit;
132
118
 
133
- 其中 xhRequest 时,omit 无效;此条配置仅针对浏览器生效;
119
+ 其中如果浏览器不支持 fetch omit 无效;
120
+
121
+ 此条配置仅针对浏览器生效;
134
122
 
135
123
  ### timeout
136
124
 
@@ -138,6 +126,12 @@ setConfig({ timeout: 5000 })
138
126
 
139
127
  说明:请求超时设置,单位 ms,默认 5000
140
128
 
129
+ ### cacheTTL
130
+
131
+ 类型: number
132
+
133
+ 说明:用于控制 get 请求的缓冲时效,单位 ms,默认 500
134
+
141
135
  ### message
142
136
 
143
137
  类型:false | ((result: IResponseResult, method: string, url: string, defaultMessage: string) => string | false)
@@ -216,7 +210,7 @@ setConfig({ timeout: 5000 })
216
210
 
217
211
  类型:null | ((status: number, method: string, url: string) => void)
218
212
 
219
- 说明:全局错误处理函数,仅仅在 status 错误时(<=200 或 > 400)时触发
213
+ 说明:全局错误处理函数,仅仅在 http status 错误时触发
220
214
 
221
215
  ### messageHandler
222
216
 
@@ -286,20 +280,57 @@ setConfig({ timeout: 5000 })
286
280
 
287
281
  所有请求均返回同样的结构(包括网络错误或状态码错误时)其结构字段如下
288
282
 
289
- - **ok** : boolean 表示当前请求是否成功,包括检测 http status 以及 responseRule
290
- - **status**: number 表示响应的 http 状态码,网络错误或其他异常情况返回负数(具体数值无含义)
291
- - **code** : string 表示当前请求的状态信息,可能是 http statusText,也可能是 responseRule 中定义的错误码,如果是网络错误则返回 "NetworkError",如果 RequestAgent 用的是 xhRequest,也可能是 "Failed" 或 "Aborted",如果用的是 nodeRequest,也可能返回 "Unknown"
292
- - **message**: string 响应结果的提示消息,不受 IRequestOptions.message 影响
293
- - **headers**: Record<string, string | undefined> 响应的头信息,全部字段名均被转成小写
294
- - **data**: 响应的数据内容,可能不存在(undefined),也可能是 null,这取决于响应状态以及类型守卫(见下说明)的检查结果,如果 ok 为 false,则 data 为 undefined,如果类型守卫检查失败,则返回 null
283
+ ### ok
284
+
285
+ 类型:boolean
286
+
287
+ 说明:表示当前请求是否成功,包括检测 http status 以及 responseRule
288
+
289
+ ### status
290
+
291
+ 类型:number
292
+
293
+ 说明:表示响应的 http 状态码,网络错误或其他异常情况返回负数(具体数值无含义)
294
+
295
+ ### code
296
+
297
+ 类型:string
298
+
299
+ 说明:表示当前请求的状态信息,其可能值有
300
+
301
+ - http statusText 当请求完成且无自定义错误码时
302
+ - responseRule 中自定义的错误码
303
+ - "NetworkError","Failed","Aborted" 或 "Unknown" 网络错误或取消等异常情况
304
+
305
+ ### message
306
+
307
+ 类型:string
308
+
309
+ 说明:响应结果的提示消息,不受 IRequestOptions.message 影响
310
+
311
+ ### headers
312
+
313
+ 类型:Record<string, string | undefined>
314
+
315
+ 说明:响应的头信息,全部字段名均被转成小写
316
+
317
+ ### data
318
+
319
+ 类型:unknown | T | null
320
+
321
+ 说明:响应的数据内容,其可能值为:
322
+
323
+ - unknown:如果不提供类型守卫,则返回 unknown
324
+ - null:网络请求错误、类型守卫检查失败、服务器没有返回正确格式的 json 数据,则返回 null
325
+ - T:如果成功返回并通过类型守卫检查,则返回类型守卫对应的类型
295
326
 
296
327
  ## 类型守卫
297
328
 
298
329
  类型守卫是一个返回 boolean 的特殊函数,用于检查某个 unknown 的数据是否为指定类型的数据,对于 ts 来说,这是确保远程数据类型安全的必要措施。其定义如下
299
330
 
300
331
  ```js
301
- export type TypeGuardFn<T> = (value: unknown) => value is T;
302
- export type TypeGuard<T> = {
332
+ type TypeGuardFn<T> = (value: unknown) => value is T;
333
+ type TypeGuard<T> = {
303
334
  guard: TypeGuardFn<T>;
304
335
  message: string; /* 当检查失败时的错误提示信息 */
305
336
  };
@@ -337,11 +368,11 @@ type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>
337
368
 
338
369
  工具还提供了三个特殊函数以应对不同的场景需求,且限于浏览器环境使用:
339
370
 
340
- ### upload(url: string, files: {key: string, blob: Blob}[], options?)
371
+ ### upload(url: string, files: Record<string, Blob>, options?)
341
372
 
342
- 因为 fetch 不支持上传进度信息,故使用 xhRequest 函数包装,支持带有上传进度信息的 upload 函数,以满足特定场景下的大文件上传需求;
373
+ 因为 fetch 不支持上传进度信息,故使用 xhr 函数包装,支持带有上传进度信息的 upload 函数,以满足特定场景下的大文件上传需求;
343
374
 
344
- 其可选 options 不支持重试,其 body 类型限制为 Record<string, string | number | boolean>,并且随着 formData 发送;同时新增进度信息配置:
375
+ 其可选 options 不支持重试,其 body 类型限制为 Record<string, unknown>,并且随着 formData 发送;同时新增进度信息配置:
345
376
 
346
377
  **onUploadProgress?: (progress: { total: number; loaded: number }) => void**
347
378
 
@@ -2,7 +2,7 @@
2
2
  export declare class Cache<T = unknown> {
3
3
  private ttl;
4
4
  private cache;
5
- constructor(cacheMs?: number);
5
+ constructor(ttl?: number);
6
6
  getKey(url: string, param?: Record<string, unknown>): string;
7
7
  updateTTL(ttl: number): void;
8
8
  get(key: string): Promise<T> | null;
@@ -4,7 +4,7 @@ export declare class RequestGlobalConfig {
4
4
  private config;
5
5
  constructor(config?: IGlobalConfig);
6
6
  set(config: Partial<IGlobalConfig>): void;
7
- get<T extends keyof IGlobalConfig>(key: T): SomeRequired<IGlobalConfig, "credentials" | "timeout" | "baseURL" | "maxRetry" | "retryResolve" | "retryInterval" | "responseRule">[T];
7
+ get<T extends keyof IGlobalConfig>(key: T): SomeRequired<IGlobalConfig, "credentials" | "timeout" | "maxRetry" | "retryResolve" | "retryInterval" | "responseRule" | "baseURL" | "cacheTTL">[T];
8
8
  /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
9
9
  getFullUrl(url: string): string;
10
10
  /** 提示消息 */
@@ -0,0 +1,62 @@
1
+ import type { TypeGuard, TypeGuardFn } from "@seayoo-web/utils";
2
+ import type { IRequestOptions, IGlobalConfig, NetRequestAgent, ResponseWithType, ResponseWithoutType } from "./type";
3
+ type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>;
4
+ type RequestBody = NonNullable<IRequestOptions["body"]>;
5
+ /** 工具函数主类 */
6
+ export declare class NetRequestHandler {
7
+ private agent;
8
+ private config;
9
+ private cache;
10
+ constructor(agent: NetRequestAgent, config?: IGlobalConfig);
11
+ /**
12
+ * 执行网络请求
13
+ */
14
+ private exec;
15
+ /**
16
+ * 检查响应的数据类型
17
+ */
18
+ private guard;
19
+ /**
20
+ * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / logHandler / responseRule
21
+ */
22
+ setConfig(config: IGlobalConfig): void;
23
+ /**
24
+ * 读取默认的请求配置
25
+ */
26
+ getConfig<T extends keyof IGlobalConfig>(key: T): import("@seayoo-web/utils").SomeRequired<IGlobalConfig, "credentials" | "timeout" | "maxRetry" | "retryResolve" | "retryInterval" | "responseRule" | "baseURL" | "cacheTTL">[T];
27
+ /**
28
+ * 发送一个 HEAD 请求,并且不处理响应 body
29
+ */
30
+ head(url: string, options?: IRequestOptions): ResponseWithType<null>;
31
+ /**
32
+ * 发送一个 GET 请求,请求自带 500ms 缓冲控制以应对并发场景
33
+ */
34
+ get(url: string): ResponseWithoutType;
35
+ get(url: string, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
36
+ get<T>(url: string, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
37
+ /**
38
+ * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
39
+ */
40
+ post(url: string, data: RequestBody): ResponseWithoutType;
41
+ post(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
42
+ post<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
43
+ /**
44
+ * 发送一个 DELETE 请求,可选 typeGuard 用于检查数据类型
45
+ */
46
+ del(url: string): ResponseWithoutType;
47
+ del(url: string, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
48
+ del<T>(url: string, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
49
+ /**
50
+ * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
51
+ */
52
+ put(url: string, data: RequestBody): ResponseWithoutType;
53
+ put(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
54
+ put<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
55
+ /**
56
+ * 发送一个 PATCH 请求,可选 typeGuard 用于检查数据类型
57
+ */
58
+ patch(url: string, data: RequestBody): ResponseWithoutType;
59
+ patch(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
60
+ patch<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
61
+ }
62
+ export {};
@@ -12,20 +12,11 @@ export declare const fetchRequest: NetRequestAgent;
12
12
  * 该方法必定 resolve,限制在浏览器环境中使用
13
13
  */
14
14
  export declare const xhRequest: NetRequestAgent;
15
- /**
16
- * 基于 nodejs 的 http/https 包的网络请求包装函数,url 必须是一个完整 url
17
- *
18
- * 该方法必定 resolve,限制在 nodejs 环境中使用
19
- */
20
- export declare const nodeRequest: NetRequestAgent;
21
15
  /**
22
16
  * 上传文件,支持进度信息和多文件上传,不抛错,限制在浏览器中使用,不支持重试
23
17
  */
24
- export declare function xhrUpload(url: string, files: {
25
- key: string;
26
- blob: Blob;
27
- }[], options?: Omit<IRequestOptions, keyof XHRequestOptions | keyof IRetryRequestOptions> & Omit<XHRequestOptions, "body"> & {
28
- body?: Record<string, string | number | boolean>;
18
+ export declare function xhrUpload(url: string, files: Record<string, Blob>, options?: Omit<IRequestOptions, keyof XHRequestOptions | keyof IRetryRequestOptions> & Omit<XHRequestOptions, "body"> & {
19
+ body?: Record<string, unknown>;
29
20
  },
30
21
  /** 全局配置中独有的配置,以受全局配置控制 */
31
22
  config?: Omit<IGlobalConfig, keyof IRequestOptions>): Promise<IResponseResult>;
@@ -0,0 +1,7 @@
1
+ import type { NetRequestAgent } from "./type";
2
+ /**
3
+ * 基于 nodejs 的 http/https 包的网络请求包装函数,url 必须是一个完整 url
4
+ *
5
+ * 该方法必定 resolve,限制在 nodejs 环境中使用
6
+ */
7
+ export declare const nodeRequest: NetRequestAgent;
@@ -40,10 +40,10 @@ export type IRequestOptions = IBaseRequestOptions & IRetryRequestOptions & IOthe
40
40
  export type IGlobalConfig = {
41
41
  /**
42
42
  * 设置全局 url 基础路径,必须要以 / 开头 或者完整的 api 地址,比如 /api 或 https://api.server.com/path
43
- *
44
- * nodejs 环境下无效
45
43
  */
46
44
  baseURL?: string;
45
+ /** 用于 get 请求的缓存时长,单位 ms,建议不小于 100 */
46
+ cacheTTL?: number;
47
47
  /** 全局 header 处理函数,通常用于追加全局认证 header 信息 */
48
48
  headerHandler?: null | ((header: Record<string, string>, method: string, url: string) => void);
49
49
  /** 全局错误处理函数,仅仅在 statusCode 错误时触发 */
@@ -122,13 +122,9 @@ export interface IResponseResult<T = unknown> {
122
122
  /** 响应的 headers 信息 */
123
123
  headers: Record<string, string | undefined>;
124
124
  /**
125
- * 成功时返回的数据
126
- *
127
- * 当 ok 为 false 时为 undefined
128
- *
129
- * 当 ok 为 true 时,如果服务器没有响应 body(比如 status 202/204)则为 null,如果类型守卫检查失败,也是 null
125
+ * 成功时返回的数据,如果网络错误/服务器没有响应内容(比如 http status 202/204)/类型守卫检查失败则是 null
130
126
  */
131
- data?: T;
127
+ data: T;
132
128
  }
133
129
  export type ResponseWithType<T> = Promise<IResponseResult<T | null>>;
134
130
  export type ResponseWithoutType = Promise<IResponseResult>;
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- var e=require("@seayoo-web/utils"),t=require("node:http"),r=require("node:https");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=/*#__PURE__*/n(t),o=/*#__PURE__*/n(r),a=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,100)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,100)},t.get=function(e){var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){this.cache[e]={ttl:Date.now()+this.ttl,res:t}},e}(),i=/*#__PURE__*/function(){function t(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var r=t.prototype;return r.set=function(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!e.isFullURL(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)},r.get=function(e){return this.config[e]},r.getFullUrl=function(t){return t.startsWith("/")?e.getFullURL(t):e.getFullURL(t,this.config.baseURL)},r.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},t}();function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u.apply(this,arguments)}function c(e,t,r){var n=Object.assign({method:"GET"},r),s=n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"Content-Type":"application/json;charset=utf-8"},n.headers),i=t.get("headerHandler");i&&i(a,o,e);var u=n.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:o,body:l(n.body),params:c,headers:a,timeout:n.timeout||t.get("timeout"),credentials:n.credentials||t.get("credentials")}}function l(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var d=function(e,t,r){try{var n=c(e,t,r),s=new URL(t.getFullUrl(e)),o=n.params;o instanceof Object&&Object.keys(o).forEach(function(e){return s.searchParams.set(e,o[e])});var a=new AbortController,i=n.timeout>0?setTimeout(function(){return a.abort()},n.timeout):null,u=new Request(s,{method:n.method,headers:new Headers(n.headers),body:n.body,credentials:n.credentials,signal:n.timeout>0?a.signal:null,redirect:"follow"});return Promise.resolve(fetch(u).then(function(e){try{var t=function(e){return{url:u,method:i,status:a,statusText:o,headers:r,body:e}},r=Object.fromEntries(e.headers.entries()),o=e.statusText,a=e.status,i=n.method,u=s.toString();return Promise.resolve("HEAD"===n.method?t(""):Promise.resolve(e.text()).then(t))}catch(e){return Promise.reject(e)}}).catch(function(e){return{url:s.toString(),method:n.method,status:-1,statusText:"NetworkError",body:String(e)}}).finally(function(){null!==i&&clearTimeout(i)}))}catch(e){return Promise.reject(e)}},h=function t(r,n,s,o,a){try{var i,u,c=a||0,l=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:s.get("maxRetry")),d=null!=(u=null==o?void 0:o.retryResolve)?u:s.get("retryResolve"),h=s.get("logHandler")||e.noop;h({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:c,maxRetry:l,message:0===c?"start":"retry "+c+"/"+l+" start",options:o});var f=Date.now();return Promise.resolve(r(n,s,o)).then(function(a){var i,u=a.status,m=Date.now()-f,g="[cost "+m+"]["+u+"] "+(u<0?a.body:"");if(h({type:"finished",url:n,method:a.method,retry:c,maxRetry:l,message:0===c?"finish "+g:"retry "+c+"/"+l+" finish "+g,response:a,cost:m}),!l||"network"===d&&u>0||"status"===d&&u>=200&&u<400||c>=l)return a;var v=null!=(i=null==o?void 0:o.retryInterval)?i:s.get("retryInterval");return Promise.resolve(e.sleep(Math.max(100,"function"==typeof v?v(c+1):v))).then(function(){return Promise.resolve(t(r,n,s,o,c+1))})})}catch(e){return Promise.reject(e)}},f="message",m="data";function g(t,r){if(void 0===r&&(r=f),!e.isJsonLike(t))return"";var n,s=e.parseJSON(t);return s&&e.isStringRecord(s)&&r in s?(n=s[r])?"string"==typeof n?n:JSON.stringify(n):"":t}function v(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function p(t,r,n,s){if(t.status<0)return y({ok:!1,status:t.status,code:t.statusText,headers:{},message:""},t.method+" "+r+" "+t.statusText,t.method,r,n,s);var o;(t.status<200||t.status>=400)&&(null==(o=n.get("errorHandler"))||o(t.status,t.method,r));var a,i,c,l,d,h=u({},(a=t.status,i=t.statusText,c=t.body,l=n.get("responseRule"),d=(null==s?void 0:s.responseRule)||l,a>=200&&a<400?function(t,r,n,s){var o=t||{resolve:"body"},a={ok:!0,code:n,message:"",data:null};if(202===r||204===r||!s)return a;if("body"===o.resolve)return a.data=e.isJsonLike(s)?e.parseJSON(s):s,a;var i=e.parseJSON(s);if(!i||!e.isStringRecord(i))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;var u=o.statusField||"code",c=o.statusOKValue||"0",l=o.dataField||m,d=o.messageField||f,h=o.ignoreMessage||"";if(!(u in i))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+u,a;var g=i[u]+"";return a.ok=g===c,a.code=g,a.message=d in i?i[d]+"":"",a.data=l in i?i[l]:null,h&&a.message&&(Array.isArray(h)&&h.includes(a.message)||"string"==typeof h&&a.message===h)&&(a.message=""),a}(d.ok||l.ok,a,i,c):function(e,t,r){var n=e||{resolve:"json",messageField:f},s={ok:!1,code:t,message:r};switch(n.resolve){case"auto":s.message=v(r)||g(r,n.messageField)||r;break;case"body":s.message=v(r)||r;break;case"json":s.message=g(r,n.messageField)}return s}(d.failed||l.failed,i,c)),{status:t.status,headers:Object.fromEntries(Object.entries(t.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return h.ok||delete h.data,y(h,h.ok?h.message:t.method+" "+r+" ["+h.code+"] "+(h.message||t.statusText),t.method,r,n,s)}function y(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}var b=function(t,r,n){try{var a=c(t,r,n);if(!e.isFullURL(t))return Promise.resolve({url:t,method:a.method,status:-2,statusText:"URLFormatError",headers:{},body:""});var i=/^https:\/\//i.test(t)?o.default:s.default,u=new URL(t),l=a.params;l instanceof Object&&Object.keys(l).forEach(function(e){return u.searchParams.set(e,l[e])});var d="HEAD"===a.method;return Promise.resolve(new Promise(function(e){var r=i.request(u,{headers:a.headers,method:a.method,timeout:a.timeout>0?a.timeout:void 0},function(r){var n=[];d||r.on("data",function(e){return n.push(e)}),r.on("end",function(){var s=Object.fromEntries(Object.entries(r.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));e({url:t,method:a.method,status:r.statusCode||-3,statusText:r.statusMessage||"Unknown",headers:s,body:d?"":Buffer.concat(n).toString("utf-8")})})});r.on("error",function(r){e({url:t,method:a.method,status:-1,statusText:r.name||"Unknown",body:r.message})}),a.body&&r.write(a.body),r.end()}))}catch(e){return Promise.reject(e)}},j=function(t,r,n){try{var s=u({},c(t,r,n),{onUploadProgress:null==n?void 0:n.onUploadProgress}),o=s.method,a=s.onUploadProgress||function(){return 0},i=e.addParamsToString(r.getFullUrl(t),s.params);return Promise.resolve(new Promise(function(e){var r=1,n=0,u=new XMLHttpRequest;u.upload.addEventListener("progress",function(e){r=e.total,a({total:e.total,loaded:e.loaded})}),u.addEventListener("load",function(){n&&clearTimeout(n),a({loaded:r,total:r}),e({url:i,method:o,status:u.status,statusText:u.statusText,headers:P(u),body:"HEAD"===o?"":u.responseText})}),u.addEventListener("error",function(){n&&clearTimeout(n),e({url:i,method:o,status:-2,statusText:"Failed",body:"Request "+o+" "+t+" Failed"})}),u.addEventListener("abort",function(){n&&clearTimeout(n),e({url:i,method:o,status:-3,statusText:"Aborted",body:"Request "+o+" "+t+" Aborted"})}),Object.entries(s.headers).forEach(function(e){u.setRequestHeader(e[0],e[1])}),"include"===s.credentials&&(u.withCredentials=!0),u.open(o,i,!0),s.body&&u.send(s.body),s.timeout>0&&(n=setTimeout(function(){u.abort()},s.timeout))}))}catch(e){return Promise.reject(e)}};function P(e){var t={};if(!e)return t;var r=e.getAllResponseHeaders();return r&&"null"!==r&&r.replace(/\r/g,"").split("\n").forEach(function(e){var r=e.trim();if(r){var n=r.split(":"),s=n[0].trim();s&&(t[s]=(n[1]||"").trim())}}),t}var x=function(e,t,r){try{return Promise.resolve(h(d,e,t,r)).then(function(n){return p(n,e,t,r)})}catch(e){return Promise.reject(e)}},w=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new i(e),this.agent=t||x,this.cache=new a(500),this.setAgent=this.setAgent.bind(this),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.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)}var r=t.prototype;return r.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},r.guard=function(t,r,n){try{return Promise.resolve(function(t,r,n,s){if(r.ok&&!e.isEmpty(r.data)&&null!==s){var o=e.getTypeGuard(s,"响应数据未能正确识别");if(o.guard(r.data))return r;console.error("response type check faild",t,r.data),n.showMessage(!0,t+" "+o.message)}return r.data=null,r}(t,r,this.config,n))}catch(e){return Promise.reject(e)}},r.setAgent=function(e){this.agent=e},r.setConfig=function(e){this.config.set(e)},r.getConfig=function(e){return this.config.get(e)},r.head=function(e,t){try{var r=this,n=Object.assign({},t||null);n.method="HEAD";var s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},r.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},r.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},r.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t}(),R=new w,O=R.setAgent,T=R.setConfig,k=R.head,E=R.get,L=R.post,F=R.del,U=R.put,H=R.patch;exports.NetRequest=w,exports.del=F,exports.fetchRequest=x,exports.get=E,exports.getResponseRulesDescription=function(e){var t=[],r=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),r.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(r.messageField||f)+" 作为错误消息");break;case"auto":t.push(" 尝试解析为json,并读取 "+(r.messageField||f)+" 作为错误消息,如果失败则将响应内容作为错误消息")}var n=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":t.push(" 将响应解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(n.dataField||m)+" 作为响应数据,读取 "+(n.messageField||f)+" 作为提示消息"),n.statusField&&n.statusOKValue&&t.push(" 当 "+n.statusField+" 为 "+n.statusOKValue+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&t.push(" 并忽略以下消息:"+n.ignoreMessage)}return t.join("\n")},exports.head=k,exports.jsonp=function(t,r,n){void 0===n&&(n={});try{var s=window;"callback"in n||(n.callback="jsonxData"+Math.random().toString(16).slice(2));var o=n.callback+"";if(!t)return Promise.resolve(null);var a=e.addParamsToString(t,n,!0);return Promise.resolve(new Promise(function(n){s[o]=function(e){if(o in window&&delete s[o],r(e))return e;console.warn("response type check faild",t,e),n(null)},e.loadJS(a).catch(function(){n(null),delete s[o]})}))}catch(e){return Promise.reject(e)}},exports.jsonx=function(t,r,n){void 0===n&&(n={});try{var s=window;return"var"in n||(n.var="jsonxData"+Math.random().toString(16).slice(2)),Promise.resolve(t?e.loadJS(e.addParamsToString(t,n,!0)).then(function(){var e=s[n.var+""];return r(e)?e:(console.warn("response type check faild",t,e),null)}).catch(function(){return null}):null)}catch(e){return Promise.reject(e)}},exports.nodeRequest=function(e,t,r){try{return Promise.resolve(h(b,e,t,r)).then(function(n){return p(n,e,t,r)})}catch(e){return Promise.reject(e)}},exports.patch=H,exports.post=L,exports.put=U,exports.setGlobalAgent=O,exports.setGlobalConfig=T,exports.upload=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){try{var s=new FormData,o=null==r?void 0:r.body;o instanceof Object&&Object.entries(o).forEach(function(e){s.append(e[0],String(e[1]))}),t&&t.length>0&&t.forEach(function(e){s.append(e.key,e.blob)});var a=new i(n);return Promise.resolve(j(e,a,u({},r,{method:"POST",body:s}))).then(function(t){return p(t,e,a,r)})}catch(e){return Promise.reject(e)}}(e,t,r,{baseURL:R.getConfig("baseURL"),logHandler:R.getConfig("logHandler"),errorHandler:R.getConfig("errorHandler"),headerHandler:R.getConfig("headerHandler"),messageHandler:R.getConfig("messageHandler")}))}catch(e){return Promise.reject(e)}},exports.xhRequest=function(e,t,r){try{return Promise.resolve(h(j,e,t,r)).then(function(n){return p(n,e,t,r)})}catch(e){return Promise.reject(e)}};
1
+ var e=require("@seayoo-web/utils");function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},t.apply(this,arguments)}function r(e,t,r){var s=Object.assign({method:"GET"},r),o=s.body instanceof FormData,a=o?"POST":s.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=t.get("headerHandler");u&&u(i,a,e);var c=s.params||{},l={};return Object.keys(c).forEach(function(e){var t;void 0!==c[e]&&(l[e]="string"==typeof(t=c[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:a,body:n(s.body),params:l,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}}function n(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var s=function(e,t,n){try{var s=r(e,t,n),o=new URL(t.getFullUrl(e)),a=s.params;a instanceof Object&&Object.keys(a).forEach(function(e){return o.searchParams.set(e,a[e])});var i=new AbortController,u=s.timeout>0?setTimeout(function(){return i.abort()},s.timeout):null,c=new Request(o,{method:s.method,headers:new Headers(s.headers),body:s.body,credentials:s.credentials,signal:s.timeout>0?i.signal:null,redirect:"follow"});return Promise.resolve(fetch(c).then(function(e){try{var t=function(e){return{url:u,method:i,status:a,statusText:n,headers:r,body:e}},r=Object.fromEntries(e.headers.entries()),n=e.statusText,a=e.status,i=s.method,u=o.toString();return Promise.resolve("HEAD"===s.method?t(""):Promise.resolve(e.text()).then(t))}catch(e){return Promise.reject(e)}}).catch(function(e){return{url:o.toString(),method:s.method,status:-1,statusText:"NetworkError",body:String(e)}}).finally(function(){null!==u&&clearTimeout(u)}))}catch(e){return Promise.reject(e)}},o=function t(r,n,s,o,a){try{var i,u,c=a||0,l=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:s.get("maxRetry")),d=null!=(u=null==o?void 0:o.retryResolve)?u:s.get("retryResolve"),h=s.get("logHandler")||e.noop;h({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:c,maxRetry:l,message:0===c?"start":"retry "+c+"/"+l+" start",options:o});var f=Date.now();return Promise.resolve(r(n,s,o)).then(function(a){var i,u=a.status,g=Date.now()-f,m="[cost "+g+"]["+u+"] "+(u<0?a.body:"");if(h({type:"finished",url:n,method:a.method,retry:c,maxRetry:l,message:0===c?"finish "+m:"retry "+c+"/"+l+" finish "+m,response:a,cost:g}),!l||"network"===d&&u>0||"status"===d&&u>=200&&u<400||c>=l)return a;var v=null!=(i=null==o?void 0:o.retryInterval)?i:s.get("retryInterval");return Promise.resolve(e.sleep(Math.max(100,"function"==typeof v?v(c+1):v))).then(function(){return Promise.resolve(t(r,n,s,o,c+1))})})}catch(e){return Promise.reject(e)}},a="message",i="data";function u(t,r){if(void 0===r&&(r=a),!e.isJsonLike(t))return"";var n,s=e.parseJSON(t);return s&&e.isStringRecord(s)&&r in s?(n=s[r])?"string"==typeof n?n:JSON.stringify(n):"":t}function c(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function l(r,n,s,o){if(r.status<0)return d({ok:!1,status:r.status,code:r.statusText,headers:{},message:"",data:null},r.method+" "+n+" "+r.statusText,r.method,n,s,o);var l;(r.status<200||r.status>=400)&&(null==(l=s.get("errorHandler"))||l(r.status,r.method,n));var h,f,g,m,v,p=t({},(h=r.status,f=r.statusText,g=r.body,m=s.get("responseRule"),v=(null==o?void 0:o.responseRule)||m,h>=200&&h<400?function(t,r,n,s){var o=t||{resolve:"body"},u={ok:!0,code:n,message:"",data:null};if(202===r||204===r||!s)return u;if("body"===o.resolve)return u.data=e.isJsonLike(s)?e.parseJSON(s):s,u;var c=e.parseJSON(s);if(!c||!e.isStringRecord(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=o.statusField||"code",d=o.statusOKValue||"0",h=o.dataField||i,f=o.messageField||a,g=o.ignoreMessage||"";if(!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var m=c[l]+"";return u.ok=m===d,u.code=m,u.message=f in c?c[f]+"":"",u.data=h in c?c[h]:null,g&&u.message&&(Array.isArray(g)&&g.includes(u.message)||"string"==typeof g&&u.message===g)&&(u.message=""),u}(v.ok||m.ok,h,f,g):function(e,t,r){var n=e||{resolve:"json",messageField:a},s={ok:!1,code:t,message:r,data:null};switch(n.resolve){case"auto":s.message=c(r)||u(r,n.messageField)||r;break;case"body":s.message=c(r)||r;break;case"json":s.message=u(r,n.messageField)}return s}(v.failed||m.failed,f,g)),{status:r.status,headers:Object.fromEntries(Object.entries(r.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return d(p,p.ok?p.message:r.method+" "+n+" ["+p.code+"] "+(p.message||r.statusText),r.method,n,s,o)}function d(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}var h=/*#__PURE__*/function(){function t(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var r=t.prototype;return r.set=function(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!e.isFullURL(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)},r.get=function(e){return this.config[e]},r.getFullUrl=function(t){return t.startsWith("/")?e.getFullURL(t):e.getFullURL(t,this.config.baseURL)},r.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},t}(),f=function(n,s,o){try{var a=t({},r(n,s,o),{onUploadProgress:null==o?void 0:o.onUploadProgress}),i=a.method,u=a.onUploadProgress||function(){return 0},c=e.addParamsToString(s.getFullUrl(n),a.params);return Promise.resolve(new Promise(function(e){var t=1,r=0,s=new XMLHttpRequest;s.upload.addEventListener("progress",function(e){t=e.total,u({total:e.total,loaded:e.loaded})}),s.addEventListener("load",function(){r&&clearTimeout(r),u({loaded:t,total:t}),e({url:c,method:i,status:s.status,statusText:s.statusText,headers:g(s),body:"HEAD"===i?"":s.responseText})}),s.addEventListener("error",function(){r&&clearTimeout(r),e({url:c,method:i,status:-2,statusText:"Failed",body:"Request "+i+" "+n+" Failed"})}),s.addEventListener("abort",function(){r&&clearTimeout(r),e({url:c,method:i,status:-3,statusText:"Aborted",body:"Request "+i+" "+n+" Aborted"})}),Object.entries(a.headers).forEach(function(e){s.setRequestHeader(e[0],e[1])}),"include"===a.credentials&&(s.withCredentials=!0),s.open(i,c,!0),a.body&&s.send(a.body),a.timeout>0&&(r=setTimeout(function(){s.abort()},a.timeout))}))}catch(e){return Promise.reject(e)}};function g(e){var t={};if(!e)return t;var r=e.getAllResponseHeaders();return r&&"null"!==r&&r.replace(/\r/g,"").split("\n").forEach(function(e){var r=e.trim();if(r){var n=r.split(":"),s=n[0].trim();s&&(t[s]=(n[1]||"").trim())}}),t}var m=function(e,t,r){try{return Promise.resolve(o(s,e,t,r)).then(function(n){return l(n,e,t,r)})}catch(e){return Promise.reject(e)}},v=function(e,t,r){try{return Promise.resolve(o(f,e,t,r)).then(function(n){return l(n,e,t,r)})}catch(e){return Promise.reject(e)}},p=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),y=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new h(t),this.agent=e,this.cache=new p(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.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)}var r=t.prototype;return r.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},r.guard=function(t,r,n){try{return Promise.resolve(function(t,r,n,s){if(r.ok&&!e.isEmpty(r.data)&&null!==s){var o=e.getTypeGuard(s,"响应数据未能正确识别");if(o.guard(r.data))return r;console.error("response type check faild",t,r.data),n.showMessage(!0,t+" "+o.message)}return r.data=null,r}(t,r,this.config,n))}catch(e){return Promise.reject(e)}},r.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},r.getConfig=function(e){return this.config.get(e)},r.head=function(e,t){try{var r=this,n=Object.assign({},t||null);n.method="HEAD";var s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},r.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},r.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},r.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t}();function b(e){return"fetch"in window?new y(m,e):new y(v,e)}var j=b(),P=j.setConfig,w=j.head,T=j.get,x=j.post,R=j.del,O=j.put,k=j.patch;exports.NetRequest=b,exports.del=R,exports.get=T,exports.getResponseRulesDescription=function(e){var t=[],r=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),r.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(r.messageField||a)+" 作为错误消息");break;case"auto":t.push(" 尝试解析为json,并读取 "+(r.messageField||a)+" 作为错误消息,如果失败则将响应内容作为错误消息")}var n=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":t.push(" 将响应解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(n.dataField||i)+" 作为响应数据,读取 "+(n.messageField||a)+" 作为提示消息"),n.statusField&&n.statusOKValue&&t.push(" 当 "+n.statusField+" 为 "+n.statusOKValue+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&t.push(" 并忽略以下消息:"+n.ignoreMessage)}return t.join("\n")},exports.head=w,exports.jsonp=function(t,r,n){void 0===n&&(n={});try{var s=window;"callback"in n||(n.callback="jsonxData"+Math.random().toString(16).slice(2));var o=n.callback+"";if(!t)return Promise.resolve(null);var a=e.addParamsToString(t,n,!0);return Promise.resolve(new Promise(function(n){s[o]=function(e){if(o in window&&delete s[o],r(e))return e;console.warn("response type check faild",t,e),n(null)},e.loadJS(a).catch(function(){n(null),delete s[o]})}))}catch(e){return Promise.reject(e)}},exports.jsonx=function(t,r,n){void 0===n&&(n={});try{var s=window;return"var"in n||(n.var="jsonxData"+Math.random().toString(16).slice(2)),Promise.resolve(t?e.loadJS(e.addParamsToString(t,n,!0)).then(function(){var e=s[n.var+""];return r(e)?e:(console.warn("response type check faild",t,e),null)}).catch(function(){return null}):null)}catch(e){return Promise.reject(e)}},exports.patch=k,exports.post=x,exports.put=O,exports.setGlobalConfig=P,exports.upload=function(e,r,n){try{return Promise.resolve(function(e,r,n,s){try{var o=new FormData,a=null==n?void 0:n.body,i=t({},r);for(var u in a instanceof Object&&Object.entries(a).forEach(function(e){var t=e[0],r=e[1];r instanceof Blob?i[t]=r:Array.isArray(r)?r.forEach(function(e,r){o.append(t+"["+r+"]",String(e))}):o.append(t,String(r))}),i)o.append(u,i[u]);var c=new h(s);return Promise.resolve(f(e,c,t({},n,{method:"POST",body:o}))).then(function(t){return l(t,e,c,n)})}catch(e){return Promise.reject(e)}}(e,r,n,{baseURL:j.getConfig("baseURL"),logHandler:j.getConfig("logHandler"),errorHandler:j.getConfig("errorHandler"),headerHandler:j.getConfig("headerHandler"),messageHandler:j.getConfig("messageHandler")}))}catch(e){return Promise.reject(e)}};
package/dist/index.d.ts CHANGED
@@ -1,78 +1,17 @@
1
- import { xhrUpload } from "./inc/request";
2
- import type { TypeGuard, TypeGuardFn } from "@seayoo-web/utils";
3
- import type { IRequestOptions, IGlobalConfig, NetRequestAgent, ResponseWithType, ResponseWithoutType } from "./inc/type";
4
- type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>;
5
- type RequestBody = NonNullable<IRequestOptions["body"]>;
6
- export { fetchRequest, xhRequest, nodeRequest } from "./inc/request";
1
+ import { xhrUpload } from "./inc/request.browser";
2
+ import { NetRequestHandler } from "./inc/main";
3
+ import type { IGlobalConfig } from "./inc/type";
4
+ export { jsonp, jsonx } from "./inc/jsonp";
7
5
  export { getResponseRulesDescription } from "./inc/rule";
8
6
  export type { IGlobalConfig } from "./inc/type";
9
- /** 导出简易的资源加载工具 */
10
- export { jsonp, jsonx } from "./inc/jsonp";
11
- /** 工具函数主类 */
12
- export declare class NetRequest {
13
- private agent;
14
- private config;
15
- private cache;
16
- constructor(config?: IGlobalConfig, agent?: NetRequestAgent);
17
- /**
18
- * 执行网络请求
19
- */
20
- private exec;
21
- /**
22
- * 检查响应的数据类型
23
- */
24
- private guard;
25
- /**
26
- * 更换网络请求 Agent,可选模块有 fetchRequest, xhRequest, nodeRequest
27
- */
28
- setAgent(agent: NetRequestAgent): void;
29
- /**
30
- * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / logHandler / responseRule
31
- */
32
- setConfig(config: IGlobalConfig): void;
33
- /**
34
- * 读取默认的请求配置
35
- */
36
- getConfig<T extends keyof IGlobalConfig>(key: T): import("@seayoo-web/utils").SomeRequired<IGlobalConfig, "credentials" | "timeout" | "baseURL" | "maxRetry" | "retryResolve" | "retryInterval" | "responseRule">[T];
37
- /**
38
- * 发送一个 HEAD 请求,并且不处理响应 body
39
- */
40
- head(url: string, options?: IRequestOptions): ResponseWithType<null>;
41
- /**
42
- * 发送一个 GET 请求,请求自带 500ms 缓冲控制以应对并发场景
43
- */
44
- get(url: string): ResponseWithoutType;
45
- get(url: string, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
46
- get<T>(url: string, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
47
- /**
48
- * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
49
- */
50
- post(url: string, data: RequestBody): ResponseWithoutType;
51
- post(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
52
- post<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
53
- /**
54
- * 发送一个 DELETE 请求,可选 typeGuard 用于检查数据类型
55
- */
56
- del(url: string): ResponseWithoutType;
57
- del(url: string, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
58
- del<T>(url: string, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
59
- /**
60
- * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
61
- */
62
- put(url: string, data: RequestBody): ResponseWithoutType;
63
- put(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
64
- put<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
65
- /**
66
- * 发送一个 PATCH 请求,可选 typeGuard 用于检查数据类型
67
- */
68
- patch(url: string, data: RequestBody): ResponseWithoutType;
69
- patch(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
70
- patch<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
71
- }
72
7
  /**
73
- * 设置全局默认的 Request Agent
8
+ * 基于 xhr 模块的上传工具,支持上传进度
9
+ */
10
+ export declare const upload: (url: string, files: Parameters<typeof xhrUpload>[1], options?: Parameters<typeof xhrUpload>[2]) => ReturnType<typeof xhrUpload>;
11
+ /**
12
+ * 创建新的实例空间,配置和缓存跟全局默认实例是隔离的
74
13
  */
75
- export declare const setGlobalAgent: (agent: NetRequestAgent) => void;
14
+ export declare function NetRequest(config?: IGlobalConfig): NetRequestHandler;
76
15
  /**
77
16
  * 设置全局默认的 Request Config
78
17
  */
@@ -80,48 +19,44 @@ export declare const setGlobalConfig: (config: IGlobalConfig) => void;
80
19
  /**
81
20
  * 发送一个 HEAD 请求
82
21
  */
83
- export declare const head: (url: string, options?: IRequestOptions) => ResponseWithType<null>;
22
+ export declare const head: (url: string, options?: import("./inc/type").IRequestOptions | undefined) => import("./inc/type").ResponseWithType<null>;
84
23
  /**
85
24
  * 发送一个 GET 请求,请求自带 500ms 缓冲控制以应对并发场景,可选 typeGuard 用于检查数据类型
86
25
  */
87
26
  export declare const get: {
88
- (url: string): ResponseWithoutType;
89
- (url: string, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
90
- <T>(url: string, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
27
+ (url: string): import("./inc/type").ResponseWithoutType;
28
+ (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
29
+ <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
91
30
  };
92
31
  /**
93
32
  * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
94
33
  */
95
34
  export declare const post: {
96
- (url: string, data: RequestBody): ResponseWithoutType;
97
- (url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
98
- <T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
35
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
36
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
37
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
99
38
  };
100
39
  /**
101
40
  * 发送一个 DELETE 请求,可选 typeGuard 用于检查数据类型
102
41
  */
103
42
  export declare const del: {
104
- (url: string): ResponseWithoutType;
105
- (url: string, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
106
- <T>(url: string, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
43
+ (url: string): import("./inc/type").ResponseWithoutType;
44
+ (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
45
+ <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
107
46
  };
108
47
  /**
109
48
  * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
110
49
  */
111
50
  export declare const put: {
112
- (url: string, data: RequestBody): ResponseWithoutType;
113
- (url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
114
- <T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
51
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
52
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
53
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
115
54
  };
116
55
  /**
117
56
  * 发送一个 PATCH 请求,可选 typeGuard 用于检查数据类型
118
57
  */
119
58
  export declare const patch: {
120
- (url: string, data: RequestBody): ResponseWithoutType;
121
- (url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
122
- <T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
59
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
60
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
61
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
123
62
  };
124
- /**
125
- * 基于 xhReqeust 模块的上传工具,支持上传进度,非必要不推荐使用
126
- */
127
- export declare const upload: (url: string, files: Parameters<typeof xhrUpload>[1], options: Parameters<typeof xhrUpload>[2]) => ReturnType<typeof xhrUpload>;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{isEmpty as e,getTypeGuard as t,isFullURL as r,getFullURL as n,noop as s,sleep as o,isJsonLike as a,parseJSON as i,isStringRecord as u,addParamsToString as c,loadJS as l}from"@seayoo-web/utils";import d from"node:http";import h from"node:https";var f=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,100)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,100)},t.get=function(e){var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){this.cache[e]={ttl:Date.now()+this.ttl,res:t}},e}(),m=/*#__PURE__*/function(){function e(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var t=e.prototype;return t.set=function(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!r(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)},t.get=function(e){return this.config[e]},t.getFullUrl=function(e){return e.startsWith("/")?n(e):n(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}();function g(){return g=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},g.apply(this,arguments)}function v(e,t,r){var n=Object.assign({method:"GET"},r),s=n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"Content-Type":"application/json;charset=utf-8"},n.headers),i=t.get("headerHandler");i&&i(a,o,e);var u=n.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:o,body:y(n.body),params:c,headers:a,timeout:n.timeout||t.get("timeout"),credentials:n.credentials||t.get("credentials")}}function y(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var b=function(e,t,r){try{var n=v(e,t,r),s=new URL(t.getFullUrl(e)),o=n.params;o instanceof Object&&Object.keys(o).forEach(function(e){return s.searchParams.set(e,o[e])});var a=new AbortController,i=n.timeout>0?setTimeout(function(){return a.abort()},n.timeout):null,u=new Request(s,{method:n.method,headers:new Headers(n.headers),body:n.body,credentials:n.credentials,signal:n.timeout>0?a.signal:null,redirect:"follow"});return Promise.resolve(fetch(u).then(function(e){try{var t=function(e){return{url:u,method:i,status:a,statusText:o,headers:r,body:e}},r=Object.fromEntries(e.headers.entries()),o=e.statusText,a=e.status,i=n.method,u=s.toString();return Promise.resolve("HEAD"===n.method?t(""):Promise.resolve(e.text()).then(t))}catch(e){return Promise.reject(e)}}).catch(function(e){return{url:s.toString(),method:n.method,status:-1,statusText:"NetworkError",body:String(e)}}).finally(function(){null!==i&&clearTimeout(i)}))}catch(e){return Promise.reject(e)}},p=function e(t,r,n,a,i){try{var u,c,l=i||0,d=Math.min(10,null!=(u=null==a?void 0:a.maxRetry)?u:n.get("maxRetry")),h=null!=(c=null==a?void 0:a.retryResolve)?c:n.get("retryResolve"),f=n.get("logHandler")||s;f({type:"prepear",url:r,method:(null==a?void 0:a.method)||"GET",retry:l,maxRetry:d,message:0===l?"start":"retry "+l+"/"+d+" start",options:a});var m=Date.now();return Promise.resolve(t(r,n,a)).then(function(s){var i,u=s.status,c=Date.now()-m,g="[cost "+c+"]["+u+"] "+(u<0?s.body:"");if(f({type:"finished",url:r,method:s.method,retry:l,maxRetry:d,message:0===l?"finish "+g:"retry "+l+"/"+d+" finish "+g,response:s,cost:c}),!d||"network"===h&&u>0||"status"===h&&u>=200&&u<400||l>=d)return s;var v=null!=(i=null==a?void 0:a.retryInterval)?i:n.get("retryInterval");return Promise.resolve(o(Math.max(100,"function"==typeof v?v(l+1):v))).then(function(){return Promise.resolve(e(t,r,n,a,l+1))})})}catch(e){return Promise.reject(e)}},j="message",P="data",w=function(e){var t=[],r=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),r.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(r.messageField||j)+" 作为错误消息");break;case"auto":t.push(" 尝试解析为json,并读取 "+(r.messageField||j)+" 作为错误消息,如果失败则将响应内容作为错误消息")}var n=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":t.push(" 将响应解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(n.dataField||P)+" 作为响应数据,读取 "+(n.messageField||j)+" 作为提示消息"),n.statusField&&n.statusOKValue&&t.push(" 当 "+n.statusField+" 为 "+n.statusOKValue+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&t.push(" 并忽略以下消息:"+n.ignoreMessage)}return t.join("\n")};function O(e,t){if(void 0===t&&(t=j),!a(e))return"";var r,n=i(e);return n&&u(n)&&t in n?(r=n[t])?"string"==typeof r?r:JSON.stringify(r):"":e}function k(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function T(e,t,r,n){if(e.status<0)return x({ok:!1,status:e.status,code:e.statusText,headers:{},message:""},e.method+" "+t+" "+e.statusText,e.method,t,r,n);var s;(e.status<200||e.status>=400)&&(null==(s=r.get("errorHandler"))||s(e.status,e.method,t));var o,c,l,d,h,f=g({},(o=e.status,c=e.statusText,l=e.body,d=r.get("responseRule"),h=(null==n?void 0:n.responseRule)||d,o>=200&&o<400?function(e,t,r,n){var s=e||{resolve:"body"},o={ok:!0,code:r,message:"",data:null};if(202===t||204===t||!n)return o;if("body"===s.resolve)return o.data=a(n)?i(n):n,o;var c=i(n);if(!c||!u(c))return o.ok=!1,o.code="ResponseFormatError",o.message="响应内容无法格式化为 Object",o;var l=s.statusField||"code",d=s.statusOKValue||"0",h=s.dataField||P,f=s.messageField||j,m=s.ignoreMessage||"";if(!(l in c))return o.ok=!1,o.code="ResponseFieldMissing",o.message="响应内容找不到状态字段 "+l,o;var g=c[l]+"";return o.ok=g===d,o.code=g,o.message=f in c?c[f]+"":"",o.data=h in c?c[h]:null,m&&o.message&&(Array.isArray(m)&&m.includes(o.message)||"string"==typeof m&&o.message===m)&&(o.message=""),o}(h.ok||d.ok,o,c,l):function(e,t,r){var n=e||{resolve:"json",messageField:j},s={ok:!1,code:t,message:r};switch(n.resolve){case"auto":s.message=k(r)||O(r,n.messageField)||r;break;case"body":s.message=k(r)||r;break;case"json":s.message=O(r,n.messageField)}return s}(h.failed||d.failed,c,l)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return f.ok||delete f.data,x(f,f.ok?f.message:e.method+" "+t+" ["+f.code+"] "+(f.message||e.statusText),e.method,t,r,n)}function x(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}var E=function(e,t,n){try{var s=v(e,t,n);if(!r(e))return Promise.resolve({url:e,method:s.method,status:-2,statusText:"URLFormatError",headers:{},body:""});var o=/^https:\/\//i.test(e)?h:d,a=new URL(e),i=s.params;i instanceof Object&&Object.keys(i).forEach(function(e){return a.searchParams.set(e,i[e])});var u="HEAD"===s.method;return Promise.resolve(new Promise(function(t){var r=o.request(a,{headers:s.headers,method:s.method,timeout:s.timeout>0?s.timeout:void 0},function(r){var n=[];u||r.on("data",function(e){return n.push(e)}),r.on("end",function(){var o=Object.fromEntries(Object.entries(r.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));t({url:e,method:s.method,status:r.statusCode||-3,statusText:r.statusMessage||"Unknown",headers:o,body:u?"":Buffer.concat(n).toString("utf-8")})})});r.on("error",function(r){t({url:e,method:s.method,status:-1,statusText:r.name||"Unknown",body:r.message})}),s.body&&r.write(s.body),r.end()}))}catch(e){return Promise.reject(e)}},R=function(e,t,r){try{var n=g({},v(e,t,r),{onUploadProgress:null==r?void 0:r.onUploadProgress}),s=n.method,o=n.onUploadProgress||function(){return 0},a=c(t.getFullUrl(e),n.params);return Promise.resolve(new Promise(function(t){var r=1,i=0,u=new XMLHttpRequest;u.upload.addEventListener("progress",function(e){r=e.total,o({total:e.total,loaded:e.loaded})}),u.addEventListener("load",function(){i&&clearTimeout(i),o({loaded:r,total:r}),t({url:a,method:s,status:u.status,statusText:u.statusText,headers:F(u),body:"HEAD"===s?"":u.responseText})}),u.addEventListener("error",function(){i&&clearTimeout(i),t({url:a,method:s,status:-2,statusText:"Failed",body:"Request "+s+" "+e+" Failed"})}),u.addEventListener("abort",function(){i&&clearTimeout(i),t({url:a,method:s,status:-3,statusText:"Aborted",body:"Request "+s+" "+e+" Aborted"})}),Object.entries(n.headers).forEach(function(e){u.setRequestHeader(e[0],e[1])}),"include"===n.credentials&&(u.withCredentials=!0),u.open(s,a,!0),n.body&&u.send(n.body),n.timeout>0&&(i=setTimeout(function(){u.abort()},n.timeout))}))}catch(e){return Promise.reject(e)}};function F(e){var t={};if(!e)return t;var r=e.getAllResponseHeaders();return r&&"null"!==r&&r.replace(/\r/g,"").split("\n").forEach(function(e){var r=e.trim();if(r){var n=r.split(":"),s=n[0].trim();s&&(t[s]=(n[1]||"").trim())}}),t}var H=function(e,t,r){try{return Promise.resolve(p(b,e,t,r)).then(function(n){return T(n,e,t,r)})}catch(e){return Promise.reject(e)}},L=function(e,t,r){try{return Promise.resolve(p(R,e,t,r)).then(function(n){return T(n,e,t,r)})}catch(e){return Promise.reject(e)}},U=function(e,t,r){try{return Promise.resolve(p(E,e,t,r)).then(function(n){return T(n,e,t,r)})}catch(e){return Promise.reject(e)}},A=function(e,t,r){void 0===r&&(r={});try{var n=window;return"var"in r||(r.var="jsonxData"+Math.random().toString(16).slice(2)),Promise.resolve(e?l(c(e,r,!0)).then(function(){var s=n[r.var+""];return t(s)?s:(console.warn("response type check faild",e,s),null)}).catch(function(){return null}):null)}catch(e){return Promise.reject(e)}},C=function(e,t,r){void 0===r&&(r={});try{var n=window;"callback"in r||(r.callback="jsonxData"+Math.random().toString(16).slice(2));var s=r.callback+"";if(!e)return Promise.resolve(null);var o=c(e,r,!0);return Promise.resolve(new Promise(function(r){n[s]=function(o){if(s in window&&delete n[s],t(o))return o;console.warn("response type check faild",e,o),r(null)},l(o).catch(function(){r(null),delete n[s]})}))}catch(e){return Promise.reject(e)}},D=/*#__PURE__*/function(){function r(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new m(e),this.agent=t||H,this.cache=new f(500),this.setAgent=this.setAgent.bind(this),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.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)}var n=r.prototype;return n.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},n.guard=function(r,n,s){try{return Promise.resolve(function(r,n,s,o){if(n.ok&&!e(n.data)&&null!==o){var a=t(o,"响应数据未能正确识别");if(a.guard(n.data))return n;console.error("response type check faild",r,n.data),s.showMessage(!0,r+" "+a.message)}return n.data=null,n}(r,n,this.config,s))}catch(e){return Promise.reject(e)}},n.setAgent=function(e){this.agent=e},n.setConfig=function(e){this.config.set(e)},n.getConfig=function(e){return this.config.get(e)},n.head=function(e,t){try{var r=this,n=Object.assign({},t||null);n.method="HEAD";var s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},n.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},n.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},n.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},n.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},n.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},r}(),M=new D,S=M.setAgent,q=M.setConfig,K=M.head,B=M.get,G=M.post,I=M.del,N=M.put,V=M.patch,J=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){try{var s=new FormData,o=null==r?void 0:r.body;o instanceof Object&&Object.entries(o).forEach(function(e){s.append(e[0],String(e[1]))}),t&&t.length>0&&t.forEach(function(e){s.append(e.key,e.blob)});var a=new m(n);return Promise.resolve(R(e,a,g({},r,{method:"POST",body:s}))).then(function(t){return T(t,e,a,r)})}catch(e){return Promise.reject(e)}}(e,t,r,{baseURL:M.getConfig("baseURL"),logHandler:M.getConfig("logHandler"),errorHandler:M.getConfig("errorHandler"),headerHandler:M.getConfig("headerHandler"),messageHandler:M.getConfig("messageHandler")}))}catch(e){return Promise.reject(e)}};export{D as NetRequest,I as del,H as fetchRequest,B as get,w as getResponseRulesDescription,K as head,C as jsonp,A as jsonx,U as nodeRequest,V as patch,G as post,N as put,S as setGlobalAgent,q as setGlobalConfig,J as upload,L as xhRequest};
1
+ import{noop as e,sleep as t,isJsonLike as r,parseJSON as n,isStringRecord as s,isFullURL as o,getFullURL as a,addParamsToString as i,isEmpty as u,getTypeGuard as c,loadJS as l}from"@seayoo-web/utils";function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},d.apply(this,arguments)}function h(e,t,r){var n=Object.assign({method:"GET"},r),s=n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"Content-Type":"application/json;charset=utf-8"},n.headers),i=t.get("headerHandler");i&&i(a,o,e);var u=n.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:o,body:f(n.body),params:c,headers:a,timeout:n.timeout||t.get("timeout"),credentials:n.credentials||t.get("credentials")}}function f(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var m=function(e,t,r){try{var n=h(e,t,r),s=new URL(t.getFullUrl(e)),o=n.params;o instanceof Object&&Object.keys(o).forEach(function(e){return s.searchParams.set(e,o[e])});var a=new AbortController,i=n.timeout>0?setTimeout(function(){return a.abort()},n.timeout):null,u=new Request(s,{method:n.method,headers:new Headers(n.headers),body:n.body,credentials:n.credentials,signal:n.timeout>0?a.signal:null,redirect:"follow"});return Promise.resolve(fetch(u).then(function(e){try{var t=function(e){return{url:u,method:i,status:a,statusText:o,headers:r,body:e}},r=Object.fromEntries(e.headers.entries()),o=e.statusText,a=e.status,i=n.method,u=s.toString();return Promise.resolve("HEAD"===n.method?t(""):Promise.resolve(e.text()).then(t))}catch(e){return Promise.reject(e)}}).catch(function(e){return{url:s.toString(),method:n.method,status:-1,statusText:"NetworkError",body:String(e)}}).finally(function(){null!==i&&clearTimeout(i)}))}catch(e){return Promise.reject(e)}},g=function r(n,s,o,a,i){try{var u,c,l=i||0,d=Math.min(10,null!=(u=null==a?void 0:a.maxRetry)?u:o.get("maxRetry")),h=null!=(c=null==a?void 0:a.retryResolve)?c:o.get("retryResolve"),f=o.get("logHandler")||e;f({type:"prepear",url:s,method:(null==a?void 0:a.method)||"GET",retry:l,maxRetry:d,message:0===l?"start":"retry "+l+"/"+d+" start",options:a});var m=Date.now();return Promise.resolve(n(s,o,a)).then(function(e){var i,u=e.status,c=Date.now()-m,g="[cost "+c+"]["+u+"] "+(u<0?e.body:"");if(f({type:"finished",url:s,method:e.method,retry:l,maxRetry:d,message:0===l?"finish "+g:"retry "+l+"/"+d+" finish "+g,response:e,cost:c}),!d||"network"===h&&u>0||"status"===h&&u>=200&&u<400||l>=d)return e;var v=null!=(i=null==a?void 0:a.retryInterval)?i:o.get("retryInterval");return Promise.resolve(t(Math.max(100,"function"==typeof v?v(l+1):v))).then(function(){return Promise.resolve(r(n,s,o,a,l+1))})})}catch(e){return Promise.reject(e)}},v="message",y="data",p=function(e){var t=[],r=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),r.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(r.messageField||v)+" 作为错误消息");break;case"auto":t.push(" 尝试解析为json,并读取 "+(r.messageField||v)+" 作为错误消息,如果失败则将响应内容作为错误消息")}var n=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":t.push(" 将响应解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(n.dataField||y)+" 作为响应数据,读取 "+(n.messageField||v)+" 作为提示消息"),n.statusField&&n.statusOKValue&&t.push(" 当 "+n.statusField+" 为 "+n.statusOKValue+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&t.push(" 并忽略以下消息:"+n.ignoreMessage)}return t.join("\n")};function b(e,t){if(void 0===t&&(t=v),!r(e))return"";var o,a=n(e);return a&&s(a)&&t in a?(o=a[t])?"string"==typeof o?o:JSON.stringify(o):"":e}function j(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function P(e,t,o,a){if(e.status<0)return w({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,o,a);var i;(e.status<200||e.status>=400)&&(null==(i=o.get("errorHandler"))||i(e.status,e.method,t));var u,c,l,h,f,m=d({},(u=e.status,c=e.statusText,l=e.body,h=o.get("responseRule"),f=(null==a?void 0:a.responseRule)||h,u>=200&&u<400?function(e,t,o,a){var i=e||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===t||204===t||!a)return u;if("body"===i.resolve)return u.data=r(a)?n(a):a,u;var c=n(a);if(!c||!s(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField||"code",d=i.statusOKValue||"0",h=i.dataField||y,f=i.messageField||v,m=i.ignoreMessage||"";if(!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var g=c[l]+"";return u.ok=g===d,u.code=g,u.message=f in c?c[f]+"":"",u.data=h in c?c[h]:null,m&&u.message&&(Array.isArray(m)&&m.includes(u.message)||"string"==typeof m&&u.message===m)&&(u.message=""),u}(f.ok||h.ok,u,c,l):function(e,t,r){var n=e||{resolve:"json",messageField:v},s={ok:!1,code:t,message:r,data:null};switch(n.resolve){case"auto":s.message=j(r)||b(r,n.messageField)||r;break;case"body":s.message=j(r)||r;break;case"json":s.message=b(r,n.messageField)}return s}(f.failed||h.failed,c,l)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return w(m,m.ok?m.message:e.method+" "+t+" ["+m.code+"] "+(m.message||e.statusText),e.method,t,o,a)}function w(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}var T=/*#__PURE__*/function(){function e(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var t=e.prototype;return t.set=function(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!o(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)},t.get=function(e){return this.config[e]},t.getFullUrl=function(e){return e.startsWith("/")?a(e):a(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),O=function(e,t,r){try{var n=d({},h(e,t,r),{onUploadProgress:null==r?void 0:r.onUploadProgress}),s=n.method,o=n.onUploadProgress||function(){return 0},a=i(t.getFullUrl(e),n.params);return Promise.resolve(new Promise(function(t){var r=1,i=0,u=new XMLHttpRequest;u.upload.addEventListener("progress",function(e){r=e.total,o({total:e.total,loaded:e.loaded})}),u.addEventListener("load",function(){i&&clearTimeout(i),o({loaded:r,total:r}),t({url:a,method:s,status:u.status,statusText:u.statusText,headers:x(u),body:"HEAD"===s?"":u.responseText})}),u.addEventListener("error",function(){i&&clearTimeout(i),t({url:a,method:s,status:-2,statusText:"Failed",body:"Request "+s+" "+e+" Failed"})}),u.addEventListener("abort",function(){i&&clearTimeout(i),t({url:a,method:s,status:-3,statusText:"Aborted",body:"Request "+s+" "+e+" Aborted"})}),Object.entries(n.headers).forEach(function(e){u.setRequestHeader(e[0],e[1])}),"include"===n.credentials&&(u.withCredentials=!0),u.open(s,a,!0),n.body&&u.send(n.body),n.timeout>0&&(i=setTimeout(function(){u.abort()},n.timeout))}))}catch(e){return Promise.reject(e)}};function x(e){var t={};if(!e)return t;var r=e.getAllResponseHeaders();return r&&"null"!==r&&r.replace(/\r/g,"").split("\n").forEach(function(e){var r=e.trim();if(r){var n=r.split(":"),s=n[0].trim();s&&(t[s]=(n[1]||"").trim())}}),t}var k=function(e,t,r){try{return Promise.resolve(g(m,e,t,r)).then(function(n){return P(n,e,t,r)})}catch(e){return Promise.reject(e)}},E=function(e,t,r){try{return Promise.resolve(g(O,e,t,r)).then(function(n){return P(n,e,t,r)})}catch(e){return Promise.reject(e)}},R=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),L=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new T(t),this.agent=e,this.cache=new R(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.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)}var t=e.prototype;return t.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},t.guard=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){if(t.ok&&!u(t.data)&&null!==n){var s=c(n,"响应数据未能正确识别");if(s.guard(t.data))return t;console.error("response type check faild",e,t.data),r.showMessage(!0,e+" "+s.message)}return t.data=null,t}(e,t,this.config,r))}catch(e){return Promise.reject(e)}},t.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},t.getConfig=function(e){return this.config.get(e)},t.head=function(e,t){try{var r=this,n=Object.assign({},t||null);n.method="HEAD";var s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}(),F=function(e,t,r){void 0===r&&(r={});try{var n=window;return"var"in r||(r.var="jsonxData"+Math.random().toString(16).slice(2)),Promise.resolve(e?l(i(e,r,!0)).then(function(){var s=n[r.var+""];return t(s)?s:(console.warn("response type check faild",e,s),null)}).catch(function(){return null}):null)}catch(e){return Promise.reject(e)}},H=function(e,t,r){void 0===r&&(r={});try{var n=window;"callback"in r||(r.callback="jsonxData"+Math.random().toString(16).slice(2));var s=r.callback+"";if(!e)return Promise.resolve(null);var o=i(e,r,!0);return Promise.resolve(new Promise(function(r){n[s]=function(o){if(s in window&&delete n[s],t(o))return o;console.warn("response type check faild",e,o),r(null)},l(o).catch(function(){r(null),delete n[s]})}))}catch(e){return Promise.reject(e)}},U=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){try{var s=new FormData,o=null==r?void 0:r.body,a=d({},t);for(var i in o instanceof Object&&Object.entries(o).forEach(function(e){var t=e[0],r=e[1];r instanceof Blob?a[t]=r:Array.isArray(r)?r.forEach(function(e,r){s.append(t+"["+r+"]",String(e))}):s.append(t,String(r))}),a)s.append(i,a[i]);var u=new T(n);return Promise.resolve(O(e,u,d({},r,{method:"POST",body:s}))).then(function(t){return P(t,e,u,r)})}catch(e){return Promise.reject(e)}}(e,t,r,{baseURL:A.getConfig("baseURL"),logHandler:A.getConfig("logHandler"),errorHandler:A.getConfig("errorHandler"),headerHandler:A.getConfig("headerHandler"),messageHandler:A.getConfig("messageHandler")}))}catch(e){return Promise.reject(e)}};function C(e){return"fetch"in window?new L(k,e):new L(E,e)}var A=C(),D=A.setConfig,M=A.head,S=A.get,q=A.post,K=A.del,B=A.put,G=A.patch;export{C as NetRequest,K as del,S as get,p as getResponseRulesDescription,M as head,H as jsonp,F as jsonx,G as patch,q as post,B as put,D as setGlobalConfig,U as upload};
package/dist/node.cjs ADDED
@@ -0,0 +1 @@
1
+ var e=require("@seayoo-web/utils"),t=require("node:http"),r=require("node:https");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=/*#__PURE__*/s(t),o=/*#__PURE__*/s(r),a=function t(r,s,n,o,a){try{var i,u,c=a||0,l=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:n.get("maxRetry")),h=null!=(u=null==o?void 0:o.retryResolve)?u:n.get("retryResolve"),d=n.get("logHandler")||e.noop;d({type:"prepear",url:s,method:(null==o?void 0:o.method)||"GET",retry:c,maxRetry:l,message:0===c?"start":"retry "+c+"/"+l+" start",options:o});var f=Date.now();return Promise.resolve(r(s,n,o)).then(function(a){var i,u=a.status,g=Date.now()-f,m="[cost "+g+"]["+u+"] "+(u<0?a.body:"");if(d({type:"finished",url:s,method:a.method,retry:c,maxRetry:l,message:0===c?"finish "+m:"retry "+c+"/"+l+" finish "+m,response:a,cost:g}),!l||"network"===h&&u>0||"status"===h&&u>=200&&u<400||c>=l)return a;var v=null!=(i=null==o?void 0:o.retryInterval)?i:n.get("retryInterval");return Promise.resolve(e.sleep(Math.max(100,"function"==typeof v?v(c+1):v))).then(function(){return Promise.resolve(t(r,s,n,o,c+1))})})}catch(e){return Promise.reject(e)}};function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},i.apply(this,arguments)}var u="message";function c(t,r){if(void 0===r&&(r=u),!e.isJsonLike(t))return"";var s,n=e.parseJSON(t);return n&&e.isStringRecord(n)&&r in n?(s=n[r])?"string"==typeof s?s:JSON.stringify(s):"":t}function l(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function h(e,t,r,s,n,o){return!1!==(null==o?void 0:o.message)&&n.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,s,t):t),e}function d(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var f=function(t,r,s){try{var a=function(e,t,r){var s=Object.assign({method:"GET"},r),n=s.body instanceof FormData,o=n?"POST":s.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var a=Object.assign(n?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),i=t.get("headerHandler");i&&i(a,o,e);var u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:o,body:d(s.body),params:c,headers:a,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}}(t,r,s);if(!e.isFullURL(t))return Promise.resolve({url:t,method:a.method,status:-2,statusText:"URLFormatError",headers:{},body:""});var i=/^https:\/\//i.test(t)?o.default:n.default,u=new URL(t),c=a.params;c instanceof Object&&Object.keys(c).forEach(function(e){return u.searchParams.set(e,c[e])});var l="HEAD"===a.method;return Promise.resolve(new Promise(function(e){var r=i.request(u,{headers:a.headers,method:a.method,timeout:a.timeout>0?a.timeout:void 0},function(r){var s=[];l||r.on("data",function(e){return s.push(e)}),r.on("end",function(){var n=Object.fromEntries(Object.entries(r.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));e({url:t,method:a.method,status:r.statusCode||-3,statusText:r.statusMessage||"Unknown",headers:n,body:l?"":Buffer.concat(s).toString("utf-8")})})});r.on("error",function(r){e({url:t,method:a.method,status:-1,statusText:r.name||"Unknown",body:r.message})}),a.body&&r.write(a.body),r.end()}))}catch(e){return Promise.reject(e)}},g=function(t,r,s){try{return Promise.resolve(a(f,t,r,s)).then(function(n){return function(t,r,s,n){if(t.status<0)return h({ok:!1,status:t.status,code:t.statusText,headers:{},message:"",data:null},t.method+" "+r+" "+t.statusText,t.method,r,s,n);var o;(t.status<200||t.status>=400)&&(null==(o=s.get("errorHandler"))||o(t.status,t.method,r));var a,d,f,g,m,v=i({},(a=t.status,d=t.statusText,f=t.body,g=s.get("responseRule"),m=(null==n?void 0:n.responseRule)||g,a>=200&&a<400?function(t,r,s,n){var o=t||{resolve:"body"},a={ok:!0,code:s,message:"",data:null};if(202===r||204===r||!n)return a;if("body"===o.resolve)return a.data=e.isJsonLike(n)?e.parseJSON(n):n,a;var i=e.parseJSON(n);if(!i||!e.isStringRecord(i))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;var c=o.statusField||"code",l=o.statusOKValue||"0",h=o.dataField||"data",d=o.messageField||u,f=o.ignoreMessage||"";if(!(c in i))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+c,a;var g=i[c]+"";return a.ok=g===l,a.code=g,a.message=d in i?i[d]+"":"",a.data=h in i?i[h]:null,f&&a.message&&(Array.isArray(f)&&f.includes(a.message)||"string"==typeof f&&a.message===f)&&(a.message=""),a}(m.ok||g.ok,a,d,f):function(e,t,r){var s=e||{resolve:"json",messageField:u},n={ok:!1,code:t,message:r,data:null};switch(s.resolve){case"auto":n.message=l(r)||c(r,s.messageField)||r;break;case"body":n.message=l(r)||r;break;case"json":n.message=c(r,s.messageField)}return n}(m.failed||g.failed,d,f)),{status:t.status,headers:Object.fromEntries(Object.entries(t.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return h(v,v.ok?v.message:t.method+" "+r+" ["+v.code+"] "+(v.message||t.statusText),t.method,r,s,n)}(n,t,r,s)})}catch(e){return Promise.reject(e)}},m=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),v=/*#__PURE__*/function(){function t(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var r=t.prototype;return r.set=function(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!e.isFullURL(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)},r.get=function(e){return this.config[e]},r.getFullUrl=function(t){return t.startsWith("/")?e.getFullURL(t):e.getFullURL(t,this.config.baseURL)},r.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},t}(),y=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new v(t),this.agent=e,this.cache=new m(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.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)}var r=t.prototype;return r.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},r.guard=function(t,r,s){try{return Promise.resolve(function(t,r,s,n){if(r.ok&&!e.isEmpty(r.data)&&null!==n){var o=e.getTypeGuard(n,"响应数据未能正确识别");if(o.guard(r.data))return r;console.error("response type check faild",t,r.data),s.showMessage(!0,t+" "+o.message)}return r.data=null,r}(t,r,this.config,s))}catch(e){return Promise.reject(e)}},r.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},r.getConfig=function(e){return this.config.get(e)},r.head=function(e,t){try{var r=this,s=Object.assign({},t||null);s.method="HEAD";var n=r.guard;return Promise.resolve(r.exec(e,s)).then(function(t){return n.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},r.get=function(e,t,r){try{var s,n=function(r){if(s)return r;var n=o.exec(e,a);o.cache.set(i,n);var u=o.guard;return Promise.resolve(n).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(n){var a=r.call(o,e,n,t||null);return s=1,a})}}();return Promise.resolve(c&&c.then?c.then(n):n(c))}catch(e){return Promise.reject(e)}},r.post=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="POST",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.del=function(e,t,r){try{var s=this,n=Object.assign({},r||null);n.method="DELETE";var o=s.guard;return Promise.resolve(s.exec(e,n)).then(function(r){return o.call(s,e,r,t||null)})}catch(e){return Promise.reject(e)}},r.put=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PUT",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.patch=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PATCH",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t}();function p(e){return new y(g,e)}var b=p(),j=b.setConfig,P=b.head,x=b.get,O=b.post,R=b.del,T=b.put,w=b.patch;exports.NetRequest=p,exports.del=R,exports.get=x,exports.head=P,exports.patch=w,exports.post=O,exports.put=T,exports.setGlobalConfig=j;
package/dist/node.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { NetRequestHandler } from "./inc/main";
2
+ import type { IGlobalConfig } from "./inc/type";
3
+ export type { IGlobalConfig } from "./inc/type";
4
+ /**
5
+ * 创建新的实例空间,配置和缓存跟全局默认实例是隔离的
6
+ */
7
+ export declare function NetRequest(config?: IGlobalConfig): NetRequestHandler;
8
+ /**
9
+ * 设置全局默认的 Request Config
10
+ */
11
+ export declare const setGlobalConfig: (config: IGlobalConfig) => void;
12
+ /**
13
+ * 发送一个 HEAD 请求
14
+ */
15
+ export declare const head: (url: string, options?: import("./inc/type").IRequestOptions | undefined) => import("./inc/type").ResponseWithType<null>;
16
+ /**
17
+ * 发送一个 GET 请求,请求自带 500ms 缓冲控制以应对并发场景,可选 typeGuard 用于检查数据类型
18
+ */
19
+ export declare const get: {
20
+ (url: string): import("./inc/type").ResponseWithoutType;
21
+ (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
22
+ <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
23
+ };
24
+ /**
25
+ * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
26
+ */
27
+ export declare const post: {
28
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
29
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
30
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
31
+ };
32
+ /**
33
+ * 发送一个 DELETE 请求,可选 typeGuard 用于检查数据类型
34
+ */
35
+ export declare const del: {
36
+ (url: string): import("./inc/type").ResponseWithoutType;
37
+ (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
38
+ <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
39
+ };
40
+ /**
41
+ * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
42
+ */
43
+ export declare const put: {
44
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
45
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
46
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
47
+ };
48
+ /**
49
+ * 发送一个 PATCH 请求,可选 typeGuard 用于检查数据类型
50
+ */
51
+ export declare const patch: {
52
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
53
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
54
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
55
+ };
package/dist/node.mjs ADDED
@@ -0,0 +1 @@
1
+ import{noop as e,sleep as t,isJsonLike as r,parseJSON as n,isStringRecord as s,isFullURL as o,isEmpty as a,getTypeGuard as i,getFullURL as u}from"@seayoo-web/utils";import c from"node:http";import l from"node:https";var h=function r(n,s,o,a,i){try{var u,c,l=i||0,h=Math.min(10,null!=(u=null==a?void 0:a.maxRetry)?u:o.get("maxRetry")),d=null!=(c=null==a?void 0:a.retryResolve)?c:o.get("retryResolve"),f=o.get("logHandler")||e;f({type:"prepear",url:s,method:(null==a?void 0:a.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:a});var m=Date.now();return Promise.resolve(n(s,o,a)).then(function(e){var i,u=e.status,c=Date.now()-m,g="[cost "+c+"]["+u+"] "+(u<0?e.body:"");if(f({type:"finished",url:s,method:e.method,retry:l,maxRetry:h,message:0===l?"finish "+g:"retry "+l+"/"+h+" finish "+g,response:e,cost:c}),!h||"network"===d&&u>0||"status"===d&&u>=200&&u<400||l>=h)return e;var v=null!=(i=null==a?void 0:a.retryInterval)?i:o.get("retryInterval");return Promise.resolve(t(Math.max(100,"function"==typeof v?v(l+1):v))).then(function(){return Promise.resolve(r(n,s,o,a,l+1))})})}catch(e){return Promise.reject(e)}};function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},d.apply(this,arguments)}var f="message";function m(e,t){if(void 0===t&&(t=f),!r(e))return"";var o,a=n(e);return a&&s(a)&&t in a?(o=a[t])?"string"==typeof o?o:JSON.stringify(o):"":e}function g(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function v(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}function y(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var p=function(e,t,r){try{var n=function(e,t,r){var n=Object.assign({method:"GET"},r),s=n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"Content-Type":"application/json;charset=utf-8"},n.headers),i=t.get("headerHandler");i&&i(a,o,e);var u=n.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:o,body:y(n.body),params:c,headers:a,timeout:n.timeout||t.get("timeout"),credentials:n.credentials||t.get("credentials")}}(e,t,r);if(!o(e))return Promise.resolve({url:e,method:n.method,status:-2,statusText:"URLFormatError",headers:{},body:""});var s=/^https:\/\//i.test(e)?l:c,a=new URL(e),i=n.params;i instanceof Object&&Object.keys(i).forEach(function(e){return a.searchParams.set(e,i[e])});var u="HEAD"===n.method;return Promise.resolve(new Promise(function(t){var r=s.request(a,{headers:n.headers,method:n.method,timeout:n.timeout>0?n.timeout:void 0},function(r){var s=[];u||r.on("data",function(e){return s.push(e)}),r.on("end",function(){var o=Object.fromEntries(Object.entries(r.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));t({url:e,method:n.method,status:r.statusCode||-3,statusText:r.statusMessage||"Unknown",headers:o,body:u?"":Buffer.concat(s).toString("utf-8")})})});r.on("error",function(r){t({url:e,method:n.method,status:-1,statusText:r.name||"Unknown",body:r.message})}),n.body&&r.write(n.body),r.end()}))}catch(e){return Promise.reject(e)}},b=function(e,t,o){try{return Promise.resolve(h(p,e,t,o)).then(function(a){return function(e,t,o,a){if(e.status<0)return v({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,o,a);var i;(e.status<200||e.status>=400)&&(null==(i=o.get("errorHandler"))||i(e.status,e.method,t));var u,c,l,h,y,p=d({},(u=e.status,c=e.statusText,l=e.body,h=o.get("responseRule"),y=(null==a?void 0:a.responseRule)||h,u>=200&&u<400?function(e,t,o,a){var i=e||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===t||204===t||!a)return u;if("body"===i.resolve)return u.data=r(a)?n(a):a,u;var c=n(a);if(!c||!s(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField||"code",h=i.statusOKValue||"0",d=i.dataField||"data",m=i.messageField||f,g=i.ignoreMessage||"";if(!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var v=c[l]+"";return u.ok=v===h,u.code=v,u.message=m in c?c[m]+"":"",u.data=d in c?c[d]:null,g&&u.message&&(Array.isArray(g)&&g.includes(u.message)||"string"==typeof g&&u.message===g)&&(u.message=""),u}(y.ok||h.ok,u,c,l):function(e,t,r){var n=e||{resolve:"json",messageField:f},s={ok:!1,code:t,message:r,data:null};switch(n.resolve){case"auto":s.message=g(r)||m(r,n.messageField)||r;break;case"body":s.message=g(r)||r;break;case"json":s.message=m(r,n.messageField)}return s}(y.failed||h.failed,c,l)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return v(p,p.ok?p.message:e.method+" "+t+" ["+p.code+"] "+(p.message||e.statusText),e.method,t,o,a)}(a,e,t,o)})}catch(e){return Promise.reject(e)}},j=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),P=/*#__PURE__*/function(){function e(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var t=e.prototype;return t.set=function(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!o(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)},t.get=function(e){return this.config[e]},t.getFullUrl=function(e){return e.startsWith("/")?u(e):u(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),T=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new P(t),this.agent=e,this.cache=new j(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.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)}var t=e.prototype;return t.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},t.guard=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){if(t.ok&&!a(t.data)&&null!==n){var s=i(n,"响应数据未能正确识别");if(s.guard(t.data))return t;console.error("response type check faild",e,t.data),r.showMessage(!0,e+" "+s.message)}return t.data=null,t}(e,t,this.config,r))}catch(e){return Promise.reject(e)}},t.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},t.getConfig=function(e){return this.config.get(e)},t.head=function(e,t){try{var r=this,n=Object.assign({},t||null);n.method="HEAD";var s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function w(e){return new T(b,e)}var O=w(),x=O.setConfig,R=O.head,k=O.get,E=O.post,L=O.del,U=O.put,F=O.patch;export{w as NetRequest,L as del,k as get,R as head,F as patch,E as post,U as put,x as setGlobalConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "0.4.2",
3
+ "version": "0.6.0",
4
4
  "description": "requst tools for seayoo web",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",
@@ -8,16 +8,22 @@
8
8
  "source": "src/index.ts",
9
9
  "types": "dist/index.d.ts",
10
10
  "exports": {
11
- "types": "./dist/index.d.ts",
12
- "default": "./dist/index.mjs",
13
- "require": "./dist/index.cjs"
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.mjs",
14
+ "require": "./dist/index.cjs"
15
+ },
16
+ "./node": {
17
+ "types": "./dist/node.d.ts",
18
+ "default": "./dist/node.mjs",
19
+ "require": "./dist/node.cjs"
20
+ }
14
21
  },
15
22
  "publishConfig": {
16
23
  "access": "public"
17
24
  },
18
25
  "scripts": {
19
- "build": "rimraf ./dist & microbundle --sourcemap false --format cjs,es",
20
- "build2": "rimraf ./dist & microbundle --visualize --format cjs,es",
26
+ "build": "rimraf ./dist & microbundle src/*.ts --sourcemap false --format cjs,es",
21
27
  "dev": "microbundle watch",
22
28
  "clear": "rimraf dist && rimraf node_modules",
23
29
  "lint": "eslint ./src/**/*.{ts,js}",
@@ -49,6 +55,6 @@
49
55
  "typescript": "^5.2.2"
50
56
  },
51
57
  "dependencies": {
52
- "@seayoo-web/utils": "^1.3.3"
58
+ "@seayoo-web/utils": "^1.3.4"
53
59
  }
54
60
  }