@seayoo-web/request 1.6.7 → 1.7.1

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.
@@ -0,0 +1,497 @@
1
+ var q = Object.defineProperty;
2
+ var I = (t, e, s) => e in t ? q(t, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : t[e] = s;
3
+ var f = (t, e, s) => (I(t, typeof e != "symbol" ? e + "" : e, s), s);
4
+ const m = typeof globalThis < "u" ? globalThis : typeof global < "u" ? global : typeof window < "u" ? window : {}, O = {
5
+ fetch: "fetch" in m,
6
+ window: "window" in m,
7
+ FormData: "FormData" in m,
8
+ Blob: "Blob" in m,
9
+ wx: "wx" in m,
10
+ TextDecoder: "TextDecoder" in m,
11
+ AbortController: "AbortController" in m
12
+ };
13
+ function K(t) {
14
+ return t.reduce(
15
+ (e, [s, n]) => (s && (e[s] = n || ""), e),
16
+ {}
17
+ );
18
+ }
19
+ function N(t) {
20
+ return new Promise((e) => setTimeout(e, Math.max(0, t)));
21
+ }
22
+ function J() {
23
+ }
24
+ function j(t) {
25
+ return t ? t[0].toLowerCase() + t.slice(1) : "";
26
+ }
27
+ const B = /_\w*/, P = /-\w*/;
28
+ function U(t) {
29
+ const e = B.test(t) ? t.replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (s, n) => n.toUpperCase()) : P.test(t) ? t.replace(/(?:^-*|-*$)/g, "").replace(/-+(\w)/g, (s, n) => n.toUpperCase()) : t;
30
+ return j(e);
31
+ }
32
+ function M(t) {
33
+ return B.test(t) ? j(t).replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (e, s) => "_" + s.toLowerCase()) : P.test(t) ? j(t.replace(/(?:^-*|-*$)/g, "")).replace(/-+(\w)/g, (e, s) => "_" + s.toLowerCase()) : j(t).replace(/[A-Z]/g, (e) => `_${e.toLowerCase()}`);
34
+ }
35
+ const G = /^(?:https?:)?\/\/.+$/i, V = /^https?:\/\/.+$/i, W = /^\{[\d\D]*\}$/, Z = /^\[[\d\D]*\]$/;
36
+ function A(t, e = !1) {
37
+ return e ? G.test(t) : V.test(t);
38
+ }
39
+ function z(t) {
40
+ return t == null;
41
+ }
42
+ function v(t, ...e) {
43
+ if (!t || typeof t != "object")
44
+ return !1;
45
+ const s = Object.getPrototypeOf(t);
46
+ return s !== Object.prototype && s !== null ? !1 : e.every((n) => n in t);
47
+ }
48
+ function S(t) {
49
+ return W.test(t) || Z.test(t);
50
+ }
51
+ function F(t, e) {
52
+ try {
53
+ const s = JSON.parse(t);
54
+ return e ? e(s) ? s : null : s;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+ "" + Math.random().toString(32).slice(2);
60
+ function $(t, e = !1) {
61
+ return typeof t == "string" ? U(t) : Array.isArray(t) ? t.map((s) => !e || typeof s == "string" ? $(s) : typeof s == "object" && s ? $(s, !0) : s) : v(t) ? Object.keys(t).reduce(
62
+ (s, n) => {
63
+ const a = U(String(n)), r = a.charAt(0).toLowerCase() + a.slice(1);
64
+ return s[r] = e ? t[n] : $(t[n]), s;
65
+ },
66
+ {}
67
+ ) : t;
68
+ }
69
+ function R(t, e = !1) {
70
+ return typeof t == "string" ? M(t) : Array.isArray(t) ? t.map((s) => !e || typeof s == "string" ? R(s) : typeof s == "object" && s ? R(s, e) : s) : v(t) ? Object.keys(t).reduce(
71
+ (s, n) => {
72
+ const a = M(String(n));
73
+ return s[a] = e ? t[n] : R(t[n]), s;
74
+ },
75
+ {}
76
+ ) : t;
77
+ }
78
+ async function me(t) {
79
+ return await new Promise(function(e) {
80
+ const s = document.getElementsByTagName("head")[0], n = document.createElement("script");
81
+ n.setAttribute("type", "text/javascript"), n.setAttribute("charset", "utf-8"), n.onload = function() {
82
+ s.removeChild(n), e(!0);
83
+ }, n.onerror = function() {
84
+ s.removeChild(n), e(!1);
85
+ }, n.setAttribute("src", t), s.appendChild(n);
86
+ });
87
+ }
88
+ function Q(t, e = "数据未能正确识别") {
89
+ return typeof t == "function" ? {
90
+ guard: t,
91
+ message: e
92
+ } : {
93
+ guard: t.guard,
94
+ message: t.message || e
95
+ };
96
+ }
97
+ function D(t, e = "") {
98
+ return !e || A(t, !0) ? L(t) : (L(e) + "/" + t).replace(/\/{2,}/g, "/").replace(/:\//, "://");
99
+ }
100
+ function L(t) {
101
+ return A(t, !0) ? t.startsWith("http") ? t : ("location" in globalThis ? location.protocol : "https:") + t : ("location" in globalThis ? location.origin : "http://127.0.0.1") + "/" + t.replace(/^\/+/, "");
102
+ }
103
+ function X(t, e) {
104
+ const s = {};
105
+ return (t.match(/([^=&#?]+)=[^&#]*/g) || []).forEach(function(n) {
106
+ const a = n.split("="), r = a[0], o = decodeURIComponent(a[1] || "");
107
+ s[r] !== void 0 ? s[r] += "," + o : s[r] = o;
108
+ }), e !== !0 ? s[e] || "" : s;
109
+ }
110
+ function Y(t, e) {
111
+ if (e) {
112
+ if (e === !0)
113
+ return t.replace(/\?[^#]*/, "");
114
+ } else
115
+ return t;
116
+ const s = t.split("#"), n = s[0].split("?"), a = n[0], r = n.length > 1 ? n[1] : "", o = s.length > 1 ? "#" + s[1] : "", c = typeof e == "string" ? [e] : Array.isArray(e) ? e : [];
117
+ return !c.length || !r ? s[0] + o : (c.map((i) => i.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (a + "?" + r.replace(new RegExp("(?:^|&)(?:" + c.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + o);
118
+ }
119
+ function ye(t, e, s = !1) {
120
+ const n = typeof e == "string" ? e : Object.keys(e).map((o) => `${o}=${encodeURIComponent(e[o])}`).join("&");
121
+ if (!n)
122
+ return t;
123
+ const a = t.split("#");
124
+ s && (a[0] = Y(
125
+ a[0],
126
+ (n.match(/([^=&#?]+)=[^&#]+/g) || []).map((o) => o.replace(/=.+$/, ""))
127
+ ));
128
+ const r = a[0].indexOf("?") + 1 ? "&" : "?";
129
+ return (a[0] + r + n + (a.length > 1 ? "#" + a[1] : "")).replace(/\?&/, "?");
130
+ }
131
+ function ee(t) {
132
+ const e = t.match(/(?:\?|&)([^=]+)(?:&|$)/g);
133
+ return e ? e.join("").replace(/(?:\?|^&+|&+$)/g, "").replace(/&{2}/g, "&").split("&").sort() : [];
134
+ }
135
+ class te {
136
+ constructor(e = 500) {
137
+ f(this, "ttl");
138
+ f(this, "cache");
139
+ this.cache = {}, this.ttl = Math.max(e, 0);
140
+ }
141
+ getKey(e, s) {
142
+ const n = e.replace(/#.+/, ""), a = n.replace(/\?.+/g, ""), r = Object.assign(X(n, !0), s), o = ee(n), c = Object.keys(r).sort().map((i) => `${i}#${r[i]}`);
143
+ return `${a}_${c.join(",")}_${o.join(",")}`;
144
+ }
145
+ updateTTL(e) {
146
+ this.ttl = Math.max(e, 0);
147
+ }
148
+ get(e) {
149
+ if (this.ttl === 0)
150
+ return null;
151
+ const s = this.cache[e];
152
+ return s ? s.ttl < Date.now() ? (delete this.cache[e], null) : s.res : null;
153
+ }
154
+ set(e, s) {
155
+ this.ttl !== 0 && (this.cache[e] = {
156
+ ttl: Date.now() + this.ttl,
157
+ res: s
158
+ });
159
+ }
160
+ }
161
+ function se(t, e, s, n) {
162
+ if (e.ok && !z(e.data) && n) {
163
+ const a = Q(n, "响应数据未能正确识别");
164
+ return a.guard(e.data) || (console.error("ResponseCheckFaild", t, e.data), s.showMessage(!0, `${t} ${a.message}`), e.data = null), e;
165
+ }
166
+ return e;
167
+ }
168
+ class ne {
169
+ constructor(e) {
170
+ // 保存的配置需要部分字段强制设置默认值
171
+ f(this, "config", {
172
+ baseURL: "",
173
+ maxRetry: 0,
174
+ retryInterval: 1e3,
175
+ retryResolve: "network",
176
+ timeout: 5e3,
177
+ cacheTTL: 500,
178
+ credentials: "same-origin",
179
+ responseRule: {
180
+ ok: {
181
+ resolve: "body"
182
+ },
183
+ failed: {
184
+ resolve: "json",
185
+ messageField: "message"
186
+ }
187
+ }
188
+ });
189
+ e && this.set(e);
190
+ }
191
+ set(e) {
192
+ if (e.baseURL && !/^\/.+/.test(e.baseURL) && !A(e.baseURL))
193
+ throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"), new Error("BaseURLError");
194
+ Object.assign(this.config, e);
195
+ }
196
+ get(e) {
197
+ return this.config[e];
198
+ }
199
+ /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
200
+ getFullUrl(e) {
201
+ return e.startsWith("/") ? D(e) : D(e, this.config.baseURL);
202
+ }
203
+ /** 提示消息 */
204
+ showMessage(e, s) {
205
+ this.config.messageHandler && s && this.config.messageHandler(e, s);
206
+ }
207
+ }
208
+ class pe {
209
+ constructor(e, s) {
210
+ f(this, "agent");
211
+ f(this, "config");
212
+ f(this, "cache");
213
+ this.config = new ne(s), this.agent = e, this.cache = new te(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), this.head = this.head.bind(this);
214
+ }
215
+ /**
216
+ * 执行网络请求
217
+ */
218
+ async exec(e, s) {
219
+ try {
220
+ return await this.agent(e, this.config, s);
221
+ } catch (n) {
222
+ return console.error("RequestError", n), {
223
+ ok: !1,
224
+ status: -9,
225
+ code: "Unkonwn",
226
+ message: String(n),
227
+ headers: {},
228
+ data: null
229
+ };
230
+ }
231
+ }
232
+ /**
233
+ * 检查响应的数据类型
234
+ */
235
+ async guard(e, s, n) {
236
+ return se(e, s, this.config, n);
237
+ }
238
+ /**
239
+ * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
240
+ */
241
+ setConfig(e) {
242
+ this.config.set(e), this.cache.updateTTL(this.config.get("cacheTTL"));
243
+ }
244
+ /**
245
+ * 读取默认的请求配置
246
+ */
247
+ getConfig(e) {
248
+ return this.config.get(e);
249
+ }
250
+ /**
251
+ * 发送一个 HEAD 请求,并且不处理响应 body
252
+ */
253
+ async head(e, s) {
254
+ const n = Object.assign({}, s || null);
255
+ return n.method = "HEAD", this.guard(e, await this.exec(e, n), null);
256
+ }
257
+ async get(e, s, n) {
258
+ const a = Object.assign({}, n || null);
259
+ a.method = "GET";
260
+ const r = this.cache.getKey(e, a.params), o = this.cache.get(r);
261
+ if (o)
262
+ return this.guard(e, await o, s || null);
263
+ const c = this.exec(e, a);
264
+ return this.cache.set(r, c), this.guard(e, await c, s || null);
265
+ }
266
+ async post(e, s, n, a) {
267
+ const r = Object.assign({}, a || null);
268
+ return r.method = "POST", r.body = s, this.guard(e, await this.exec(e, r), n || null);
269
+ }
270
+ async del(e, s, n) {
271
+ const a = Object.assign({}, n || null);
272
+ return a.method = "DELETE", this.guard(e, await this.exec(e, a), s || null);
273
+ }
274
+ async put(e, s, n, a) {
275
+ const r = Object.assign({}, a || null);
276
+ return r.method = "PUT", r.body = s, this.guard(e, await this.exec(e, r), n || null);
277
+ }
278
+ async patch(e, s, n, a) {
279
+ const r = Object.assign({}, a || null);
280
+ return r.method = "PATCH", r.body = s, this.guard(e, await this.exec(e, r), n || null);
281
+ }
282
+ }
283
+ const H = "data", b = "message";
284
+ function re(t, e, s, n, a) {
285
+ const r = a || n;
286
+ return T(t) ? le(r.ok || n.ok, t, e, s) : ae(r.failed || n.failed, e, s);
287
+ }
288
+ const be = function(t) {
289
+ const e = [], s = t.failed || { resolve: "json" };
290
+ switch (e.push("- 当http状态码 <200 或者 >=400 时"), s.resolve) {
291
+ case "body":
292
+ e.push(" 将响应内容格式化为字符串并作为错误消息");
293
+ break;
294
+ case "json":
295
+ e.push(" 将响应解析为json,并读取 " + (s.messageField || b) + " 作为错误消息");
296
+ break;
297
+ }
298
+ const n = t.ok || { resolve: "body" };
299
+ switch (e.push("- 当http状态码 >=200 并且 <400 时"), n.resolve) {
300
+ case "body":
301
+ e.push(" 将响应尝试解析为 json,并作为数据内容返回");
302
+ break;
303
+ case "json":
304
+ e.push(
305
+ " 将响应解析为 json,读取 " + (n.dataField || H) + " 作为响应数据,读取 " + (n.messageField || b) + " 作为提示消息"
306
+ ), n.statusField && e.push(" 当 " + n.statusField + " 为 " + (n.statusOKValue || "空值") + " 时是成功提示,否则是错误消息"), n.ignoreMessage && e.push(" 并忽略以下消息:" + n.ignoreMessage);
307
+ break;
308
+ }
309
+ return e.join(`
310
+ `);
311
+ };
312
+ function ae(t, e, s) {
313
+ const n = t || { resolve: "json", messageField: b }, a = {
314
+ ok: !1,
315
+ code: e,
316
+ message: s,
317
+ data: null
318
+ };
319
+ switch (n.resolve) {
320
+ case "body":
321
+ a.message = x(s) || s;
322
+ break;
323
+ case "json":
324
+ const { code: r, message: o } = oe(s, n.converter, n.statusField, n.messageField);
325
+ a.code = r || e, a.message = x(s) || o;
326
+ break;
327
+ }
328
+ return a;
329
+ }
330
+ function oe(t, e, s, n = b) {
331
+ if (!S(t))
332
+ return { message: "" };
333
+ const a = k(F(t), e);
334
+ return !a || !v(a) ? { message: t } : {
335
+ code: s ? C(a, s) : "",
336
+ message: C(a, n) || t
337
+ };
338
+ }
339
+ function C(t, e) {
340
+ const s = Array.isArray(e) ? e : [e];
341
+ for (const n of s)
342
+ if (n in t)
343
+ return ce(t[n]);
344
+ return "";
345
+ }
346
+ function ce(t) {
347
+ return t ? typeof t == "string" ? t : JSON.stringify(t) : "";
348
+ }
349
+ const ie = /<title>([^<]+)<\/title>/i, ue = /<message>([^<]+)<\/message>/i;
350
+ function x(t) {
351
+ const e = t.match(ie);
352
+ if (e)
353
+ return e[1];
354
+ const s = t.match(ue);
355
+ return s ? s[1] : "";
356
+ }
357
+ function le(t, e, s, n) {
358
+ const a = t || { resolve: "body" }, r = {
359
+ ok: !0,
360
+ code: s,
361
+ message: "",
362
+ data: null
363
+ };
364
+ if (e === 204 || !n)
365
+ return r;
366
+ if (a.resolve === "body")
367
+ return r.data = S(n) ? k(F(n), t.converter) : n, r;
368
+ const o = k(F(n), t.converter);
369
+ if (!o || !v(o))
370
+ return r.ok = !1, r.code = "ResponseFormatError", r.message = "响应内容无法格式化为 Object", r;
371
+ const c = a.statusField, i = a.statusOKValue || "", l = a.dataField || H, h = a.messageField || b, u = a.ignoreMessage || "";
372
+ if (c && !(c in o))
373
+ return r.ok = !1, r.code = "ResponseFieldMissing", r.message = "响应内容找不到状态字段 " + c, r;
374
+ const d = c ? o[c] + "" : "";
375
+ return r.ok = c ? d === i : !0, r.code = d || s, r.data = l === !0 ? o : l in o ? o[l] : null, r.message = C(o, h), u && r.message && (Array.isArray(u) && u.includes(r.message) || typeof u == "string" && r.message === u) && (r.message = ""), r;
376
+ }
377
+ function T(t) {
378
+ return t >= 200 && t < 400;
379
+ }
380
+ function k(t, e) {
381
+ return e === "camelize" ? $(t) : e === "snakify" ? R(t) : t;
382
+ }
383
+ async function he(t, e, s, n, a) {
384
+ const r = a || 0, o = Math.max(0, Math.min(10, (n == null ? void 0 : n.maxRetry) ?? s.get("maxRetry") ?? 0)), c = (n == null ? void 0 : n.retryResolve) ?? s.get("retryResolve"), i = s.get("logHandler") || J;
385
+ i({
386
+ type: "prepear",
387
+ url: e,
388
+ method: (n == null ? void 0 : n.method) || "GET",
389
+ retry: r,
390
+ maxRetry: o,
391
+ message: r === 0 ? "start" : `retry ${r}/${o} start`,
392
+ headers: n == null ? void 0 : n.headers,
393
+ options: n
394
+ });
395
+ const l = Date.now(), h = await t(e, s, n), u = h.status, d = Date.now() - l, y = `[cost ${d}][${u}] ${u < 0 ? h.body : ""}`;
396
+ i({
397
+ type: "finished",
398
+ url: e,
399
+ method: h.method,
400
+ retry: r,
401
+ maxRetry: o,
402
+ message: r === 0 ? `finish ${y}` : `retry ${r}/${o} finish ${y}`,
403
+ response: h,
404
+ headers: h.headers,
405
+ cost: d
406
+ });
407
+ const w = T(u);
408
+ if (!o || c === "network" && u > 0 || c === "status" && w || Array.isArray(c) && !c.includes(u) || typeof c == "function" && c(h, r) !== !0 || r >= o)
409
+ return h;
410
+ const g = (n == null ? void 0 : n.retryInterval) ?? s.get("retryInterval") ?? 1e3;
411
+ return await N(
412
+ Math.max(
413
+ 100,
414
+ g === "2EB" ? Math.pow(2, r) * 1e3 : typeof g == "function" ? g(r + 1) || 0 : g
415
+ )
416
+ ), await he(t, e, s, n, r + 1);
417
+ }
418
+ async function we(t, e, s) {
419
+ var g;
420
+ const n = Object.assign({ method: "GET" }, s), a = O.FormData ? n.body instanceof FormData : !1, r = a && n.method !== "POST" && n.method !== "PUT" ? "POST" : n.method, o = r === "GET" || r === "HEAD" || r === "DELETE";
421
+ o && n.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete n.body);
422
+ const c = Object.assign(
423
+ a || o ? {} : {
424
+ "Content-Type": O.Blob && n.body instanceof Blob ? n.body.type || "application/octet-stream" : "application/json;charset=utf-8"
425
+ },
426
+ n.headers
427
+ ), i = n.params || {}, l = {};
428
+ Object.keys(i).forEach((p) => {
429
+ i[p] !== void 0 && (l[p] = de(i[p]));
430
+ });
431
+ const h = e.getFullUrl(t), u = ge(n.body), d = n.timeout || e.get("timeout"), y = await async function() {
432
+ var E;
433
+ const p = e.get("requestTransformer");
434
+ return p ? await p({ headers: c, params: l, method: r, url: h, body: u }) : await ((E = e.get("requestHandler")) == null ? void 0 : E(c, l, r, t));
435
+ }(), w = typeof y == "string" && y ? y : h;
436
+ return (g = e.get("logHandler")) == null || g({ type: "ready", url: w, method: r, headers: c, timeout: d, body: u }), {
437
+ url: w,
438
+ method: r,
439
+ body: u,
440
+ params: l,
441
+ headers: c,
442
+ timeout: d,
443
+ abort: n.abort,
444
+ credentials: n.credentials || e.get("credentials")
445
+ };
446
+ }
447
+ function de(t) {
448
+ return typeof t == "string" ? t : Array.isArray(t) ? t.join(",") : t + "";
449
+ }
450
+ function ge(t) {
451
+ if (t)
452
+ return typeof t == "string" || t instanceof URLSearchParams || t instanceof ArrayBuffer || O.Blob && t instanceof Blob || O.FormData && t instanceof FormData ? t : JSON.stringify(t);
453
+ }
454
+ function je(t, e, s, n) {
455
+ var o, c;
456
+ if (t.status < 0)
457
+ return _(
458
+ { ok: !1, status: t.status, code: t.statusText, headers: {}, message: "", data: null },
459
+ `${t.method} ${e} ${t.statusText}`,
460
+ t.method,
461
+ e,
462
+ s,
463
+ n
464
+ );
465
+ T(t.status) || (o = s.get("errorHandler")) == null || o(t.status, t.method, e);
466
+ const a = {
467
+ ...re(t.status, t.statusText, t.body, s.get("responseRule"), n == null ? void 0 : n.responseRule),
468
+ status: t.status,
469
+ headers: K(Object.entries(t.headers || {}).map(([i, l]) => [i.toLowerCase(), l]))
470
+ };
471
+ (c = s.get("responseHandler")) == null || c({ ...a }, t.method, e);
472
+ const r = a.ok ? a.message : `${t.method} ${e} [${a.code || t.statusText}] ${a.message || t.statusText}`;
473
+ return _(a, r, t.method, e, s, n);
474
+ }
475
+ function _(t, e, s, n, a, r) {
476
+ const o = a.get("message"), c = o === !1 || (r == null ? void 0 : r.message) === !1 ? !1 : (r == null ? void 0 : r.message) || o;
477
+ if (c !== !1) {
478
+ const i = typeof c == "function" ? c(t, s, n, e) : e;
479
+ i instanceof Error ? a.showMessage(!0, i.message) : i && typeof i == "object" && "message" in i ? a.showMessage(!1, i.message) : a.showMessage(!t.ok, i);
480
+ }
481
+ return t;
482
+ }
483
+ const $e = "1.7.1";
484
+ export {
485
+ me as A,
486
+ A as D,
487
+ pe as N,
488
+ ne as R,
489
+ O as S,
490
+ ye as U,
491
+ we as c,
492
+ K as f,
493
+ be as g,
494
+ je as h,
495
+ he as r,
496
+ $e as v
497
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";var N=Object.defineProperty;var G=(t,e,s)=>e in t?N(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var f=(t,e,s)=>(G(t,typeof e!="symbol"?e+"":e,s),s);const m=typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof window<"u"?window:{},b={fetch:"fetch"in m,window:"window"in m,FormData:"FormData"in m,Blob:"Blob"in m,wx:"wx"in m,TextDecoder:"TextDecoder"in m,AbortController:"AbortController"in m};function B(t){return t.reduce((e,[s,n])=>(s&&(e[s]=n||""),e),{})}function J(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function V(){}function j(t){return t?t[0].toLowerCase()+t.slice(1):""}const P=/_\w*/,S=/-\w*/;function U(t){const e=P.test(t)?t.replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(s,n)=>n.toUpperCase()):S.test(t)?t.replace(/(?:^-*|-*$)/g,"").replace(/-+(\w)/g,(s,n)=>n.toUpperCase()):t;return j(e)}function D(t){return P.test(t)?j(t).replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(e,s)=>"_"+s.toLowerCase()):S.test(t)?j(t.replace(/(?:^-*|-*$)/g,"")).replace(/-+(\w)/g,(e,s)=>"_"+s.toLowerCase()):j(t).replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}const W=/^(?:https?:)?\/\/.+$/i,Z=/^https?:\/\/.+$/i,z=/^\{[\d\D]*\}$/,Q=/^\[[\d\D]*\]$/;function v(t,e=!1){return e?W.test(t):Z.test(t)}function X(t){return t==null}function C(t,...e){if(!t||typeof t!="object")return!1;const s=Object.getPrototypeOf(t);return s!==Object.prototype&&s!==null?!1:e.every(n=>n in t)}function H(t){return z.test(t)||Q.test(t)}function F(t,e){try{const s=JSON.parse(t);return e?e(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);function $(t,e=!1){return typeof t=="string"?U(t):Array.isArray(t)?t.map(s=>!e||typeof s=="string"?$(s):typeof s=="object"&&s?$(s,!0):s):C(t)?Object.keys(t).reduce((s,n)=>{const a=U(String(n)),r=a.charAt(0).toLowerCase()+a.slice(1);return s[r]=e?t[n]:$(t[n]),s},{}):t}function O(t,e=!1){return typeof t=="string"?D(t):Array.isArray(t)?t.map(s=>!e||typeof s=="string"?O(s):typeof s=="object"&&s?O(s,e):s):C(t)?Object.keys(t).reduce((s,n)=>{const a=D(String(n));return s[a]=e?t[n]:O(t[n]),s},{}):t}async function Y(t){return await new Promise(function(e){const s=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("charset","utf-8"),n.onload=function(){s.removeChild(n),e(!0)},n.onerror=function(){s.removeChild(n),e(!1)},n.setAttribute("src",t),s.appendChild(n)})}function ee(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function M(t,e=""){return!e||v(t,!0)?L(t):(L(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function L(t){return v(t,!0)?t.startsWith("http")?t:("location"in globalThis?location.protocol:"https:")+t:("location"in globalThis?location.origin:"http://127.0.0.1")+"/"+t.replace(/^\/+/,"")}function te(t,e){const s={};return(t.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(n){const a=n.split("="),r=a[0],o=decodeURIComponent(a[1]||"");s[r]!==void 0?s[r]+=","+o:s[r]=o}),e!==!0?s[e]||"":s}function se(t,e){if(e){if(e===!0)return t.replace(/\?[^#]*/,"")}else return t;const s=t.split("#"),n=s[0].split("?"),a=n[0],r=n.length>1?n[1]:"",o=s.length>1?"#"+s[1]:"",c=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!c.length||!r?s[0]+o:(c.map(i=>i.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(a+"?"+r.replace(new RegExp("(?:^|&)(?:"+c.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+o)}function ne(t,e,s=!1){const n=typeof e=="string"?e:Object.keys(e).map(o=>`${o}=${encodeURIComponent(e[o])}`).join("&");if(!n)return t;const a=t.split("#");s&&(a[0]=se(a[0],(n.match(/([^=&#?]+)=[^&#]+/g)||[]).map(o=>o.replace(/=.+$/,""))));const r=a[0].indexOf("?")+1?"&":"?";return(a[0]+r+n+(a.length>1?"#"+a[1]:"")).replace(/\?&/,"?")}function re(t){const e=t.match(/(?:\?|&)([^=]+)(?:&|$)/g);return e?e.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class ae{constructor(e=500){f(this,"ttl");f(this,"cache");this.cache={},this.ttl=Math.max(e,0)}getKey(e,s){const n=e.replace(/#.+/,""),a=n.replace(/\?.+/g,""),r=Object.assign(te(n,!0),s),o=re(n),c=Object.keys(r).sort().map(i=>`${i}#${r[i]}`);return`${a}_${c.join(",")}_${o.join(",")}`}updateTTL(e){this.ttl=Math.max(e,0)}get(e){if(this.ttl===0)return null;const s=this.cache[e];return s?s.ttl<Date.now()?(delete this.cache[e],null):s.res:null}set(e,s){this.ttl!==0&&(this.cache[e]={ttl:Date.now()+this.ttl,res:s})}}function oe(t,e,s,n){if(e.ok&&!X(e.data)&&n){const a=ee(n,"响应数据未能正确识别");return a.guard(e.data)||(console.error("ResponseCheckFaild",t,e.data),s.showMessage(!0,`${t} ${a.message}`),e.data=null),e}return e}class q{constructor(e){f(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)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!v(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)}get(e){return this.config[e]}getFullUrl(e){return e.startsWith("/")?M(e):M(e,this.config.baseURL)}showMessage(e,s){this.config.messageHandler&&s&&this.config.messageHandler(e,s)}}class ce{constructor(e,s){f(this,"agent");f(this,"config");f(this,"cache");this.config=new q(s),this.agent=e,this.cache=new ae(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),this.head=this.head.bind(this)}async exec(e,s){try{return await this.agent(e,this.config,s)}catch(n){return console.error("RequestError",n),{ok:!1,status:-9,code:"Unkonwn",message:String(n),headers:{},data:null}}}async guard(e,s,n){return oe(e,s,this.config,n)}setConfig(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(e){return this.config.get(e)}async head(e,s){const n=Object.assign({},s||null);return n.method="HEAD",this.guard(e,await this.exec(e,n),null)}async get(e,s,n){const a=Object.assign({},n||null);a.method="GET";const r=this.cache.getKey(e,a.params),o=this.cache.get(r);if(o)return this.guard(e,await o,s||null);const c=this.exec(e,a);return this.cache.set(r,c),this.guard(e,await c,s||null)}async post(e,s,n,a){const r=Object.assign({},a||null);return r.method="POST",r.body=s,this.guard(e,await this.exec(e,r),n||null)}async del(e,s,n){const a=Object.assign({},n||null);return a.method="DELETE",this.guard(e,await this.exec(e,a),s||null)}async put(e,s,n,a){const r=Object.assign({},a||null);return r.method="PUT",r.body=s,this.guard(e,await this.exec(e,r),n||null)}async patch(e,s,n,a){const r=Object.assign({},a||null);return r.method="PATCH",r.body=s,this.guard(e,await this.exec(e,r),n||null)}}const I="data",w="message";function ie(t,e,s,n,a){const r=a||n;return T(t)?me(r.ok||n.ok,t,e,s):le(r.failed||n.failed,e,s)}const ue=function(t){const e=[],s=t.failed||{resolve:"json"};switch(e.push("- 当http状态码 <200 或者 >=400 时"),s.resolve){case"body":e.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":e.push(" 将响应解析为json,并读取 "+(s.messageField||w)+" 作为错误消息");break}const n=t.ok||{resolve:"body"};switch(e.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":e.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":e.push(" 将响应解析为 json,读取 "+(n.dataField||I)+" 作为响应数据,读取 "+(n.messageField||w)+" 作为提示消息"),n.statusField&&e.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&e.push(" 并忽略以下消息:"+n.ignoreMessage);break}return e.join(`
2
+ `)};function le(t,e,s){const n=t||{resolve:"json",messageField:w},a={ok:!1,code:e,message:s,data:null};switch(n.resolve){case"body":a.message=x(s)||s;break;case"json":const{code:r,message:o}=he(s,n.converter,n.statusField,n.messageField);a.code=r||e,a.message=x(s)||o;break}return a}function he(t,e,s,n=w){if(!H(t))return{message:""};const a=A(F(t),e);return!a||!C(a)?{message:t}:{code:s?k(a,s):"",message:k(a,n)||t}}function k(t,e){const s=Array.isArray(e)?e:[e];for(const n of s)if(n in t)return de(t[n]);return""}function de(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const ge=/<title>([^<]+)<\/title>/i,fe=/<message>([^<]+)<\/message>/i;function x(t){const e=t.match(ge);if(e)return e[1];const s=t.match(fe);return s?s[1]:""}function me(t,e,s,n){const a=t||{resolve:"body"},r={ok:!0,code:s,message:"",data:null};if(e===204||!n)return r;if(a.resolve==="body")return r.data=H(n)?A(F(n),t.converter):n,r;const o=A(F(n),t.converter);if(!o||!C(o))return r.ok=!1,r.code="ResponseFormatError",r.message="响应内容无法格式化为 Object",r;const c=a.statusField,i=a.statusOKValue||"",l=a.dataField||I,h=a.messageField||w,u=a.ignoreMessage||"";if(c&&!(c in o))return r.ok=!1,r.code="ResponseFieldMissing",r.message="响应内容找不到状态字段 "+c,r;const d=c?o[c]+"":"";return r.ok=c?d===i:!0,r.code=d||s,r.data=l===!0?o:l in o?o[l]:null,r.message=k(o,h),u&&r.message&&(Array.isArray(u)&&u.includes(r.message)||typeof u=="string"&&r.message===u)&&(r.message=""),r}function T(t){return t>=200&&t<400}function A(t,e){return e==="camelize"?$(t):e==="snakify"?O(t):t}async function K(t,e,s,n,a){const r=a||0,o=Math.max(0,Math.min(10,(n==null?void 0:n.maxRetry)??s.get("maxRetry")??0)),c=(n==null?void 0:n.retryResolve)??s.get("retryResolve"),i=s.get("logHandler")||V;i({type:"prepear",url:e,method:(n==null?void 0:n.method)||"GET",retry:r,maxRetry:o,message:r===0?"start":`retry ${r}/${o} start`,headers:n==null?void 0:n.headers,options:n});const l=Date.now(),h=await t(e,s,n),u=h.status,d=Date.now()-l,y=`[cost ${d}][${u}] ${u<0?h.body:""}`;i({type:"finished",url:e,method:h.method,retry:r,maxRetry:o,message:r===0?`finish ${y}`:`retry ${r}/${o} finish ${y}`,response:h,headers:h.headers,cost:d});const R=T(u);if(!o||c==="network"&&u>0||c==="status"&&R||Array.isArray(c)&&!c.includes(u)||typeof c=="function"&&c(h,r)!==!0||r>=o)return h;const g=(n==null?void 0:n.retryInterval)??s.get("retryInterval")??1e3;return await J(Math.max(100,g==="2EB"?Math.pow(2,r)*1e3:typeof g=="function"?g(r+1)||0:g)),await K(t,e,s,n,r+1)}async function ye(t,e,s){var g;const n=Object.assign({method:"GET"},s),a=b.FormData?n.body instanceof FormData:!1,r=a&&n.method!=="POST"&&n.method!=="PUT"?"POST":n.method,o=r==="GET"||r==="HEAD"||r==="DELETE";o&&n.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);const c=Object.assign(a||o?{}:{"Content-Type":b.Blob&&n.body instanceof Blob?n.body.type||"application/octet-stream":"application/json;charset=utf-8"},n.headers),i=n.params||{},l={};Object.keys(i).forEach(p=>{i[p]!==void 0&&(l[p]=pe(i[p]))});const h=e.getFullUrl(t),u=be(n.body),d=n.timeout||e.get("timeout"),y=await async function(){var E;const p=e.get("requestTransformer");return p?await p({headers:c,params:l,method:r,url:h,body:u}):await((E=e.get("requestHandler"))==null?void 0:E(c,l,r,t))}(),R=typeof y=="string"&&y?y:h;return(g=e.get("logHandler"))==null||g({type:"ready",url:R,method:r,headers:c,timeout:d,body:u}),{url:R,method:r,body:u,params:l,headers:c,timeout:d,abort:n.abort,credentials:n.credentials||e.get("credentials")}}function pe(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function be(t){if(t)return typeof t=="string"||t instanceof URLSearchParams||t instanceof ArrayBuffer||b.Blob&&t instanceof Blob||b.FormData&&t instanceof FormData?t:JSON.stringify(t)}function we(t,e,s,n){var o,c;if(t.status<0)return _({ok:!1,status:t.status,code:t.statusText,headers:{},message:"",data:null},`${t.method} ${e} ${t.statusText}`,t.method,e,s,n);T(t.status)||(o=s.get("errorHandler"))==null||o(t.status,t.method,e);const a={...ie(t.status,t.statusText,t.body,s.get("responseRule"),n==null?void 0:n.responseRule),status:t.status,headers:B(Object.entries(t.headers||{}).map(([i,l])=>[i.toLowerCase(),l]))};(c=s.get("responseHandler"))==null||c({...a},t.method,e);const r=a.ok?a.message:`${t.method} ${e} [${a.code||t.statusText}] ${a.message||t.statusText}`;return _(a,r,t.method,e,s,n)}function _(t,e,s,n,a,r){const o=a.get("message"),c=o===!1||(r==null?void 0:r.message)===!1?!1:(r==null?void 0:r.message)||o;if(c!==!1){const i=typeof c=="function"?c(t,s,n,e):e;i instanceof Error?a.showMessage(!0,i.message):i&&typeof i=="object"&&"message"in i?a.showMessage(!1,i.message):a.showMessage(!t.ok,i)}return t}const Re="1.7.1";exports.Ae=Y;exports.D=v;exports.NetRequestHandler=ce;exports.RequestGlobalConfig=q;exports.Support=b;exports.Ut=ne;exports.convertOptions=ye;exports.fromEntries=B;exports.getResponseRulesDescription=ue;exports.handleResponse=we;exports.retryRequest=K;exports.version=Re;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "1.6.7";
1
+ export declare const version = "1.7.1";
package/dist/wx.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./version-DQX6nwEA.cjs"),p=async function(t,r,n){return e.handleResponse(await e.retryRequest(l,t,r,n),t,r,n)},l=async function(t,r,n){const o=await e.convertOptions(t,r,n),u=o.method==="PATCH"?"POST":o.method,a=e.Et(o.url,o.params);return e.Support.wx?new Promise(d=>{wx.request({url:a,data:o.body,header:o.headers,method:u,dataType:"string",responseType:"text",fail(){d({url:a,method:u,status:-1,statusText:"NetworkError",body:""})},success(c){d({url:a,method:u,status:c.statusCode,statusText:c.statusCode+"",headers:{...c.header},body:o.method==="HEAD"?"":f(c.data)})}})}):{url:a,method:u,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}};function f(t){return typeof t=="string"?t:t instanceof ArrayBuffer&&e.Support.TextDecoder?new TextDecoder().decode(t):JSON.stringify(t)}function i(t){return new e.NetRequestHandler(p,t)}const s=i(),y=s.setConfig,g=s.head,h=s.get,x=s.post,w=s.del,T=s.put;exports.version=e.version;exports.NetRequest=i;exports.del=w;exports.get=h;exports.head=g;exports.post=x;exports.put=T;exports.setGlobalConfig=y;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./version-Cx7ZvtPo.cjs"),p=async function(t,r,n){return e.handleResponse(await e.retryRequest(l,t,r,n),t,r,n)},l=async function(t,r,n){const o=await e.convertOptions(t,r,n),u=o.method==="PATCH"?"POST":o.method,a=e.Ut(o.url,o.params);return e.Support.wx?new Promise(d=>{wx.request({url:a,data:o.body,header:o.headers,method:u,dataType:"string",responseType:"text",fail(){d({url:a,method:u,status:-1,statusText:"NetworkError",body:""})},success(c){d({url:a,method:u,status:c.statusCode,statusText:c.statusCode+"",headers:{...c.header},body:o.method==="HEAD"?"":f(c.data)})}})}):{url:a,method:u,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}};function f(t){return typeof t=="string"?t:t instanceof ArrayBuffer&&e.Support.TextDecoder?new TextDecoder().decode(t):JSON.stringify(t)}function i(t){return new e.NetRequestHandler(p,t)}const s=i(),y=s.setConfig,g=s.head,h=s.get,x=s.post,w=s.del,T=s.put;exports.version=e.version;exports.NetRequest=i;exports.del=w;exports.get=h;exports.head=g;exports.post=x;exports.put=T;exports.setGlobalConfig=y;
package/dist/wx.js CHANGED
@@ -1,5 +1,5 @@
1
- import { h as i, r as p, c as f, E as l, S as d, N as x } from "./version-CG8SvMVf.js";
2
- import { v as A } from "./version-CG8SvMVf.js";
1
+ import { h as i, r as p, c as f, U as l, S as d, N as x } from "./version-C-bTPkwR.js";
2
+ import { v as D } from "./version-C-bTPkwR.js";
3
3
  const h = async function(t, o, r) {
4
4
  return i(await p(y, t, o, r), t, o, r);
5
5
  }, y = async function(t, o, r) {
@@ -55,5 +55,5 @@ export {
55
55
  R as post,
56
56
  S as put,
57
57
  g as setGlobalConfig,
58
- A as version
58
+ D as version
59
59
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "1.6.7",
3
+ "version": "1.7.1",
4
4
  "description": "requst tools for seayoo web",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -79,9 +79,9 @@
79
79
  "simple-git-hooks": "^2.11.1",
80
80
  "typescript": "~5.2.2",
81
81
  "vite": "^5.2.8",
82
- "vitest": "^1.4.0"
82
+ "vitest": "1.4.0"
83
83
  },
84
84
  "dependencies": {
85
- "@seayoo-web/utils": "^1.16.4"
85
+ "@seayoo-web/utils": "^1.17.2"
86
86
  }
87
87
  }
@@ -1,5 +0,0 @@
1
- import type { NetRequestCoreFn } from "./type";
2
- /**
3
- * 基于 fetch 的网络请求包装函数
4
- */
5
- export declare const coreFetch: NetRequestCoreFn;
@@ -1,11 +0,0 @@
1
- import type { IBaseRequestOptions, NetRequestCoreFn } from "./type";
2
- export interface XHRequestOptions extends IBaseRequestOptions {
3
- onUploadProgress?: (progress: {
4
- total: number;
5
- loaded: number;
6
- }) => void;
7
- }
8
- /**
9
- * 基于 xmlHttpRequest 的请求工具,支持上传进度信息,不抛错
10
- */
11
- export declare const coreXHRequest: NetRequestCoreFn;