diff --git a/ff-request.js b/ff-request.js index d98430c..503cb84 100644 --- a/ff-request.js +++ b/ff-request.js @@ -1,29 +1,29 @@ -var pe = Object.defineProperty; -var ce = (r) => { +var de = Object.defineProperty; +var oe = (r) => { throw TypeError(r); }; -var ve = (r, e, t) => e in r ? pe(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t; -var g = (r, e, t) => ve(r, typeof e != "symbol" ? e + "" : e, t), he = (r, e, t) => e.has(r) || ce("Cannot " + t); -var s = (r, e, t) => (he(r, e, "read from private field"), t ? t.call(r) : e.get(r)), p = (r, e, t) => e.has(r) ? ce("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t), _ = (r, e, t, n) => (he(r, e, "write to private field"), n ? n.call(r, t) : e.set(r, t), t); -function we(r) { +var ge = (r, e, t) => e in r ? de(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t; +var l = (r, e, t) => ge(r, typeof e != "symbol" ? e + "" : e, t), ae = (r, e, t) => e.has(r) || oe("Cannot " + t); +var s = (r, e, t) => (ae(r, e, "read from private field"), t ? t.call(r) : e.get(r)), w = (r, e, t) => e.has(r) ? oe("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t), C = (r, e, t, n) => (ae(r, e, "write to private field"), n ? n.call(r, t) : e.set(r, t), t); +function pe(r) { return r && r.__esModule && Object.prototype.hasOwnProperty.call(r, "default") ? r.default : r; } -var fe = {}; +var ue = {}; (function(r) { (function(e) { e([], function() { - var t = -1, n = -2, i = -3, c = -4, u = -5, U = function(h, f) { - f = f || {}; - var l = f.verbose || !1; - l && console.log("Normalize the JSON Object"), h = typeof h == "string" ? this.JSON.parse(h) : h, l && console.log("Creating a empty dictionary"); - var d = { + var t = -1, n = -2, i = -3, c = -4, f = -5, U = function(h, d) { + d = d || {}; + var u = d.verbose || !1; + u && console.log("Normalize the JSON Object"), h = typeof h == "string" ? this.JSON.parse(h) : h, u && console.log("Creating a empty dictionary"); + var g = { strings: [], integers: [], floats: [] }; - l && console.log("Creating the AST"); - var v = function O(o) { - l && console.log("Calling recursiveAstBuilder with " + this.JSON.stringify(o)); + u && console.log("Creating the AST"); + var p = function O(o) { + u && console.log("Calling recursiveAstBuilder with " + this.JSON.stringify(o)); var y = typeof o; if (o === null) return { @@ -33,7 +33,7 @@ var fe = {}; if (typeof o > "u") return { type: "undefined", - index: u + index: f }; if (o instanceof Array) { var S = ["@"]; @@ -53,22 +53,22 @@ var fe = {}; index: c }; if (y === "string") { - var P = H.call(d.strings, o); - return P == -1 && (d.strings.push(T(o)), P = d.strings.length - 1), { + var P = H.call(g.strings, o); + return P == -1 && (g.strings.push(T(o)), P = g.strings.length - 1), { type: "strings", index: P }; } if (y === "number" && o % 1 === 0) { - var P = H.call(d.integers, o); - return P == -1 && (d.integers.push(m(o)), P = d.integers.length - 1), { + var P = H.call(g.integers, o); + return P == -1 && (g.integers.push(m(o)), P = g.integers.length - 1), { type: "integers", index: P }; } if (y === "number") { - var P = H.call(d.floats, o); - return P == -1 && (d.floats.push(o), P = d.floats.length - 1), { + var P = H.call(g.floats, o); + return P == -1 && (g.floats.push(o), P = g.floats.length - 1), { type: "floats", index: P }; @@ -79,11 +79,11 @@ var fe = {}; index: o ? t : n }; throw new Error("Unexpected argument of type " + typeof o); - }(h), E = d.strings.length, J = d.integers.length; - d.floats.length, l && console.log("Parsing the dictionary"); - var M = d.strings.join("|"); - return M += "^" + d.integers.join("|"), M += "^" + d.floats.join("|"), l && console.log("Parsing the structure"), M += "^" + function O(o) { - if (l && console.log("Calling a recursiveParser with " + this.JSON.stringify(o)), o instanceof Array) { + }(h), E = g.strings.length, J = g.integers.length; + g.floats.length, u && console.log("Parsing the dictionary"); + var M = g.strings.join("|"); + return M += "^" + g.integers.join("|"), M += "^" + g.floats.join("|"), u && console.log("Parsing the structure"), M += "^" + function O(o) { + if (u && console.log("Calling a recursiveParser with " + this.JSON.stringify(o)), o instanceof Array) { var y = o.shift(); for (var S in o) o.hasOwnProperty(S) && (y += O(o[S]) + "|"); @@ -101,135 +101,135 @@ var fe = {}; if (b === "null") return i; if (b === "undefined") - return u; + return f; if (b === "empty") return c; throw new TypeError("The item is alien!"); - }(v), l && console.log("Ending parser"), f.debug ? { - dictionary: d, - ast: v, + }(p), u && console.log("Ending parser"), d.debug ? { + dictionary: g, + ast: p, packed: M } : M; - }, a = function(h, f) { - f = f || {}; - var l = h.split("^"); - f.verbose && console.log("Building dictionary"); - var d = [], v = l[0]; - if (v !== "") { - v = v.split("|"), f.verbose && console.log("Parse the strings dictionary"); - for (var E = 0, J = v.length; E < J; E++) - d.push(C(v[E])); + }, a = function(h, d) { + d = d || {}; + var u = h.split("^"); + d.verbose && console.log("Building dictionary"); + var g = [], p = u[0]; + if (p !== "") { + p = p.split("|"), d.verbose && console.log("Parse the strings dictionary"); + for (var E = 0, J = p.length; E < J; E++) + g.push(_(p[E])); } - if (v = l[1], v !== "") { - v = v.split("|"), f.verbose && console.log("Parse the integers dictionary"); - for (var E = 0, J = v.length; E < J; E++) - d.push(I(v[E])); + if (p = u[1], p !== "") { + p = p.split("|"), d.verbose && console.log("Parse the integers dictionary"); + for (var E = 0, J = p.length; E < J; E++) + g.push(I(p[E])); } - if (v = l[2], v !== "") { - v = v.split("|"), f.verbose && console.log("Parse the floats dictionary"); - for (var E = 0, J = v.length; E < J; E++) - d.push(parseFloat(v[E])); + if (p = u[2], p !== "") { + p = p.split("|"), d.verbose && console.log("Parse the floats dictionary"); + for (var E = 0, J = p.length; E < J; E++) + g.push(parseFloat(p[E])); } - v = null, f.verbose && console.log("Tokenizing the structure"); - for (var M = "", O = [], o = l[3].length, E = 0; E < o; E++) { - var y = l[3].charAt(E); + p = null, d.verbose && console.log("Tokenizing the structure"); + for (var M = "", O = [], o = u[3].length, E = 0; E < o; E++) { + var y = u[3].charAt(E); y === "|" || y === "$" || y === "@" || y === "]" ? (M && (O.push(I(M)), M = ""), y !== "|" && O.push(y)) : M += y; } var S = O.length, b = 0; - return f.verbose && console.log("Starting recursive parser"), function N() { + return d.verbose && console.log("Starting recursive parser"), function N() { var P = O[b++]; - if (f.verbose && console.log("Reading collection type " + (P === "$" ? "object" : "Array")), P === "@") { - for (var w = []; b < S; b++) { + if (d.verbose && console.log("Reading collection type " + (P === "$" ? "object" : "Array")), P === "@") { + for (var v = []; b < S; b++) { var A = O[b]; - if (f.verbose && console.log("Read " + A + " symbol"), A === "]") - return w; + if (d.verbose && console.log("Read " + A + " symbol"), A === "]") + return v; if (A === "@" || A === "$") - w.push(N()); + v.push(N()); else switch (A) { case t: - w.push(!0); + v.push(!0); break; case n: - w.push(!1); + v.push(!1); break; case i: - w.push(null); + v.push(null); break; - case u: - w.push(void 0); + case f: + v.push(void 0); break; case c: - w.push(""); + v.push(""); break; default: - w.push(d[A]); + v.push(g[A]); } } - return f.verbose && console.log("Parsed " + this.JSON.stringify(w)), w; + return d.verbose && console.log("Parsed " + this.JSON.stringify(v)), v; } if (P === "$") { - for (var w = {}; b < S; b++) { + for (var v = {}; b < S; b++) { var x = O[b]; if (x === "]") - return w; - x === c ? x = "" : x = d[x]; + return v; + x === c ? x = "" : x = g[x]; var A = O[++b]; if (A === "@" || A === "$") - w[x] = N(); + v[x] = N(); else switch (A) { case t: - w[x] = !0; + v[x] = !0; break; case n: - w[x] = !1; + v[x] = !1; break; case i: - w[x] = null; + v[x] = null; break; - case u: - w[x] = void 0; + case f: + v[x] = void 0; break; case c: - w[x] = ""; + v[x] = ""; break; default: - w[x] = d[A]; + v[x] = g[A]; } } - return f.verbose && console.log("Parsed " + this.JSON.stringify(w)), w; + return d.verbose && console.log("Parsed " + this.JSON.stringify(v)), v; } throw new TypeError("Bad token " + P + " isn't a type"); }(); }, T = function(h) { - return typeof h != "string" ? h : h.replace(/[\+ \|\^\%]/g, function(f) { + return typeof h != "string" ? h : h.replace(/[\+ \|\^\%]/g, function(d) { return { " ": "+", "+": "%2B", "|": "%7C", "^": "%5E", "%": "%25" - }[f]; + }[d]; }); - }, C = function(h) { - return typeof h != "string" ? h : h.replace(/\+|%2B|%7C|%5E|%25/g, function(f) { + }, _ = function(h) { + return typeof h != "string" ? h : h.replace(/\+|%2B|%7C|%5E|%25/g, function(d) { return { "+": " ", "%2B": "+", "%7C": "|", "%5E": "^", "%25": "%" - }[f]; + }[d]; }); }, m = function(h) { return Number.prototype.toString.call(h, 36).toUpperCase(); }, I = function(h) { return parseInt(h, 36); - }, H = Array.prototype.indexOf || function(h, f) { - for (var l = f || 0, d = this.length; l < d; l++) - if (this[l] === h) - return l; + }, H = Array.prototype.indexOf || function(h, d) { + for (var u = d || 0, g = this.length; u < g; u++) + if (this[u] === h) + return u; return -1; }; return { @@ -243,10 +243,10 @@ var fe = {}; for (var i in n) r[i] = n[i]; }); -})(fe); -const le = /* @__PURE__ */ we(fe); -var $, q, j, B, W, X, z, Z, ee, te, re; -const ae = class ae { +})(ue); +const ce = /* @__PURE__ */ pe(ue); +var $, q, j, B, W, k, X, Z, ee; +const ie = class ie { /** * @param {number} code * @param {string} message @@ -256,35 +256,67 @@ const ae = class ae { */ constructor(e, t, n, i, c) { /** @type {number} */ - g(this, "code", 0); + l(this, "code", 0); /** @type {string} */ - g(this, "message", "操作成功"); + l(this, "message", "操作成功"); /** @type {unknown} */ - g(this, "data", null); + l(this, "data", null); /** @type {string} */ - g(this, "url", ""); + l(this, "url", ""); /** @type {string} */ - g(this, "res", ""); - /** @type {HttpResponse} */ - p(this, $); - // 判断返回 Response 对象, 还是 Response 中的 data - /** @type {boolean} */ - p(this, q, !0); - // 判断是否已经给出错误提示 - /** @type {boolean} */ - p(this, j, !0); - p(this, B, { - /** @param {any} __ @param {string} key */ + l(this, "res", ""); + /** + * Proxy 最终返回的对象 + * + * @type {HttpResponseProxy} + */ + w(this, $); + /** + * 判断回调使用 HttpResponse 还是 data + * + * @type {boolean} + */ + w(this, q, !0); + /** + * 是否已经显示消息 + * + * @type {boolean} + */ + w(this, j, !0); + /** + * Proxy Handler + */ + w(this, B, { + /** + * @param {any} _ + * @param {string | symbol} key + * @returns {unknown} + */ get: (e, t) => s(this, W).call(this, t), - /** @param {any} __ @param {string} key */ - set: (e, t) => { - throw new TypeError(`HttpResponse 是只读的,不能设置属性 "${t}"`); + /** + * HttpResponse 是只读对象 + * + * @param {any} _ + * @param {string | symbol} key + * @param {unknown} value + * @returns {boolean} + */ + set: (e, t, n) => { + throw new TypeError( + `HttpResponse 是只读的,不能设置属性 "${String(t)}"` + ); }, - /** @returns {string[]} */ + /** + * @returns {(string | symbol)[]} + */ ownKeys: () => Object.keys(s(this, B).getPrototypeOf() || {}), - /** @returns {HttpResponse | unknown} */ + /** + * @returns {HttpResponse | unknown} + */ getPrototypeOf: () => s(this, q) ? this : this.data, - /** @returns {PropertyDescriptor} */ + /** + * @returns {PropertyDescriptor} + */ getOwnPropertyDescriptor: () => ({ configurable: !0, enumerable: !0, @@ -293,66 +325,139 @@ const ae = class ae { }) }); /** - * @param {string} key + * Proxy 属性访问 + * + * @param {string | symbol} key * @returns {unknown} */ - p(this, W, (e) => e === "$echoMsg" ? s(this, z) : e === "msg" ? s(this, X) : e === "then" ? (_(this, j, !0), s(this, Z)) : e === "resp" ? (_(this, j, !0), s(this, ee)) : e === "catch" ? s(this, te) : e === "finally" ? s(this, re) : e === "IS_ECHO_MSG" ? s(this, j) : Reflect.get(this, e)); + w(this, W, (e) => e === "$echoMsg" ? s(this, k) : e === "then" ? (C(this, j, !0), s(this, X)) : e === "catch" ? s(this, Z) : e === "finally" ? s(this, ee) : e === "IS_ECHO_MSG" ? s(this, j) : Reflect.get(this, e)); /** - * @param {(value: unknown) => unknown} [fn] 回调参数默认是 data(isResp=false), 传 isResp=true 则是完整的 HttpResponse(含 code/message) - * @param {boolean} [isResp] - * @returns {Promise} fn 内部抛出的异常会变成 reject, 而不是像之前那样在参数求值阶段直接同步抛出(违反"永远返回 Promise"的约定, .then() 链式调用捕获不到) + * message 消息弹窗后回调 + * + * @overload + * @returns {Promise} + * + * @overload + * @param {(data: unknown) => unknown} fn + * @param {false} isResp + * @returns {Promise} + * + * @overload + * @param {(response: HttpResponse) => unknown} fn + * @param {true} isResp + * @returns {Promise} + * + * @param {(value: unknown | HttpResponse) => unknown} [fn] + * @param {boolean} [isResp=false] + * @returns {Promise} + * + * fn 内部抛出的异常会变成 reject,而不是同步抛出。 */ - p(this, X, (e = (n) => n, t = !1) => { - s(this, z).call(this), _(this, q, t); + l(this, "msg", (e = (n) => n, t = !1) => { + s(this, k).call(this), C(this, q, t); try { - return Promise.resolve(e == null ? void 0 : e(s(this, B).getPrototypeOf())); + return Promise.resolve( + e == null ? void 0 : e(s(this, B).getPrototypeOf()) + ); } catch (n) { return Promise.reject(n); } }); - g(this, "toJSON", () => ({ code: this.code, message: this.message, data: this.data, url: this.url, res: this.res })); - g(this, "toString", () => this.message); - p(this, z, () => { - s(this, j) && (_(this, j, !1), oe.onMsg(this.code, this.message)); + /** + * 使用完整 HttpResponse 对象处理响应 + * + * 与 msg() 的区别: + * + * msg(false) -> 回调拿 data + * + * msg(true) -> 回调拿 HttpResponse + * + * resp() -> 永远拿 HttpResponse + * + * @overload + * @returns {Promise} + * + * @overload + * @param {(response: HttpResponse) => unknown} fn + * @returns {Promise} + * + * @overload + * @param {undefined} fn + * @param {(reason: HttpResponse) => unknown} onrejected + * @returns {Promise} + * + * @param {(response: HttpResponse) => unknown} [fn] + * @param {(reason: HttpResponse) => unknown} [onrejected] + * @returns {Promise} + */ + l(this, "resp", (e, t) => (C(this, j, !0), [0, 1].includes(this.code) ? Promise.resolve(e == null ? void 0 : e(this)) : t ? Promise.resolve(t(s(this, $))) : Promise.reject(s(this, $)))); + /** + * 转换成 JSON + * + * @returns {HttpResponseData} + */ + l(this, "toJSON", () => ({ + code: this.code, + message: this.message, + data: this.data, + url: this.url, + res: this.res + })); + /** + * 响应消息字符串 + * + * @returns {string} + */ + l(this, "toString", () => this.message); + /** + * 显示消息 + * + * @returns {void} + */ + w(this, k, () => { + s(this, j) && (C(this, j, !1), se.onMsg(this.code, this.message)); }); /** - * @param {(value: unknown) => unknown} [fn] - * @param {((reason: unknown) => unknown) | undefined} [onrejected] + * Promise then + * + * @param {HttpResponseThenCallback | undefined} fn + * @param {HttpResponseRejectCallback} [onrejected] * @returns {Promise} */ - p(this, Z, (e, t) => [0, 1].includes(this.code) ? Promise.resolve(e == null ? void 0 : e(this.data)) : t ? Promise.resolve(t(s(this, $))) : Promise.reject(s(this, $))); + w(this, X, (e, t) => [0, 1].includes(this.code) ? Promise.resolve(e == null ? void 0 : e(this.data)) : t ? Promise.resolve(t(s(this, $))) : Promise.reject(s(this, $))); /** - * @param {(value: HttpResponse) => unknown} [fn] - * @param {((reason: unknown) => unknown) | undefined} [onrejected] + * Promise catch + * + * @param {HttpResponseRejectCallback} fn * @returns {Promise} */ - p(this, ee, (e, t) => [0, 1].includes(this.code) ? Promise.resolve(e == null ? void 0 : e(this)) : t ? Promise.resolve(t(s(this, $))) : Promise.reject(s(this, $))); - /** - * @param {(reason: HttpResponse) => unknown} fn - * @returns {Promise} - */ - p(this, te, (e) => Promise.resolve(e(s(this, $)))); + w(this, Z, (e) => Promise.resolve(e(s(this, $)))); /** + * Promise finally + * * @param {(() => void) | undefined} [fn] * @returns {Promise} */ - p(this, re, (e) => (e == null || e(), [0, 1].includes(this.code) ? Promise.resolve(s(this, B).getPrototypeOf()) : Promise.reject(s(this, $)))); - return this.code = e, this.message = t, this.data = n, this.url = i, this.res = c, _(this, $, new Proxy(this, s(this, B))); + w(this, ee, (e) => (e == null || e(), [0, 1].includes(this.code) ? Promise.resolve(s(this, B).getPrototypeOf()) : Promise.reject(s(this, $)))); + return this.code = e, this.message = t, this.data = n, this.url = i, this.res = c, C(this, $, new Proxy(this, s(this, B))); } static [Symbol.hasInstance](e) { - return (e == null ? void 0 : e.constructor) === ae || (e == null ? void 0 : e[Symbol.for("HttpResponse")]) === !0; + return (e == null ? void 0 : e.constructor) === ie || (e == null ? void 0 : e[Symbol.for("HttpResponse")]) === !0; } }; -$ = new WeakMap(), q = new WeakMap(), j = new WeakMap(), B = new WeakMap(), W = new WeakMap(), X = new WeakMap(), z = new WeakMap(), Z = new WeakMap(), ee = new WeakMap(), te = new WeakMap(), re = new WeakMap(); -let L = ae; -const ie = (r, e, t, n = "/", i = "") => new L(r, e, t, n, i); -var de = [ +$ = new WeakMap(), q = new WeakMap(), j = new WeakMap(), B = new WeakMap(), W = new WeakMap(), k = new WeakMap(), X = new WeakMap(), Z = new WeakMap(), ee = new WeakMap(); +let L = ie; +const ne = (r, e, t, n = "/", i = "") => ( + /** @type {HttpResponseProxy} */ + new L(r, e, t, n, i) +); +var le = [ "utf8", "utf-8", "unicode-1-1-utf-8" ]; -function ye(r) { - if (de.indexOf(r) < 0 && typeof r < "u" && r != null) +function ve(r) { + if (le.indexOf(r) < 0 && typeof r < "u" && r != null) throw new RangeError("Invalid encoding type. Only utf-8 is supported"); this.encoding = "utf-8", this.encode = function(e) { if (typeof e != "string") @@ -364,8 +469,8 @@ function ye(r) { return n; }; } -function be(r) { - if (de.indexOf(r) < 0 && typeof r < "u" && r != null) +function we(r) { + if (le.indexOf(r) < 0 && typeof r < "u" && r != null) throw new RangeError("Invalid encoding type. Only utf-8 is supported"); this.encoding = "utf-8", this.decode = function(e, t) { if (typeof e > "u") @@ -375,44 +480,44 @@ function be(r) { throw new TypeError("stream option must be boolean"); if (ArrayBuffer.isView(e)) { var i = new Uint8Array(e.buffer, e.byteOffset, e.byteLength), c = new Array(i.length); - for (let u = 0; u < i.length; u++) - c[u] = String.fromCharCode(i[u]); + for (let f = 0; f < i.length; f++) + c[f] = String.fromCharCode(i[f]); return decodeURIComponent(escape(c.join(""))); } else throw new TypeError("passed argument must be an array buffer view"); }; } -var ge = { - TextEncoder: ye, - TextDecoder: be +var fe = { + TextEncoder: ve, + TextDecoder: we }; -const Ee = new ge.TextEncoder("utf8"), Pe = new ge.TextDecoder("utf8"); -function Te(r) { +const ye = new fe.TextEncoder("utf8"), be = new fe.TextDecoder("utf8"); +function Ee(r) { let e = 5381; for (let t = 0; t < r.length; t++) e = e * 33 ^ r.charCodeAt(t); return (e >>> 0).toString(16); } -function Oe(r, e) { +function Pe(r, e) { return r.replace(new RegExp(`^${e}+|${e}+$`, "g"), ""); } -function Se(r) { - return Ee.encode(r || ""); +function Te(r) { + return ye.encode(r || ""); } -function Ne(r) { - return Pe.decode(new DataView(r), {}); +function _e(r) { + return be.decode(new DataView(r), {}); } -const xe = 62, Q = 30, ue = 31, me = 63; -class Ae { +const Oe = 62, Q = 30, he = 31, Se = 63; +class xe { /** * @param {string} alphabet 62 位编码字母表 */ constructor(e) { /** @type {string[]} */ - g(this, "encodeTable", []); + l(this, "encodeTable", []); /** @type {Uint8Array} */ - g(this, "decodeMap", new Uint8Array(256).fill(255)); - if (e.length !== xe) + l(this, "decodeMap", new Uint8Array(256).fill(255)); + if (e.length !== Oe) throw new Error("Encoding alphabet must be 62 characters long"); if (e.includes(` `) || e.includes("\r")) @@ -428,7 +533,7 @@ class Ae { */ encode(e) { if (!e || e.length === 0) return ""; - const t = new _e(this).encodeV2(e); + const t = new me(this).encodeV2(e); return String.fromCharCode(...t); } /** @@ -438,55 +543,55 @@ class Ae { */ decode(e) { if (!e || e.length === 0) return ""; - const t = new Ce(this).decode(e); + const t = new Ae(this).decode(e); return new TextDecoder().decode(t); } } -var V; -class _e { +var z; +class me { /** * @param {Base62} b62 */ constructor(e) { /** @type {Base62} */ - p(this, V); + w(this, z); /** @type {Uint8Array} */ - g(this, "src", new Uint8Array()); + l(this, "src", new Uint8Array()); /** @type {number} */ - g(this, "pos", 0); - _(this, V, e); + l(this, "pos", 0); + C(this, z, e); } /** @returns {number} */ get6bits() { let e = this.pos & 7, t = this.pos >> 3; e === 0 && (t -= 1, e = 8); let n = this.src[t] >> 8 - e; - return e < 6 && t > 0 && (n |= this.src[t - 1] << e), n & me; + return e < 6 && t > 0 && (n |= this.src[t - 1] << e), n & Se; } /** * @param {string} src * @returns {number[]} */ encodeV2(e) { - this.src = Se(e), this.pos = this.src.length * 8; + this.src = Te(e), this.pos = this.src.length * 8; const t = []; for (; this.pos > 0; ) { let n = 6, i = this.get6bits(); - (i & Q) === Q && ((this.pos > 6 || i > ue) && (n = 5), i &= ue), t.push(s(this, V).encodeTable[i].charCodeAt(0)), this.pos -= n; + (i & Q) === Q && ((this.pos > 6 || i > he) && (n = 5), i &= he), t.push(s(this, z).encodeTable[i].charCodeAt(0)), this.pos -= n; } return t; } } -V = new WeakMap(); -var k; -class Ce { +z = new WeakMap(); +var V; +class Ae { /** * @param {Base62} b62 */ constructor(e) { /** @type {Base62} */ - p(this, k); - _(this, k, e); + w(this, V); + C(this, V, e); } /** * @param {string} src @@ -495,24 +600,24 @@ class Ce { decode(e) { const t = new Uint8Array(Math.ceil(e.length * 6 / 8) + 1); let n = t.length, i = 0, c = 0; - for (let u = 0; u < e.length; u++) { - const U = e[u].charCodeAt(0), a = s(this, k).decodeMap[U]; + for (let f = 0; f < e.length; f++) { + const U = e[f].charCodeAt(0), a = s(this, V).decodeMap[U]; if (a === 255) - throw new Error(`CorruptInputError at index ${u}`); - u === e.length - 1 ? (c |= a << i, i += Math.ceil(Math.log2(a + 1))) : (a & Q) === Q ? (c |= a << i, i += 5) : (c |= a << i, i += 6), i >= 8 && (n--, t[n] = c & 255, i %= 8, c >>= 8); + throw new Error(`CorruptInputError at index ${f}`); + f === e.length - 1 ? (c |= a << i, i += Math.ceil(Math.log2(a + 1))) : (a & Q) === Q ? (c |= a << i, i += 5) : (c |= a << i, i += 6), i >= 8 && (n--, t[n] = c & 255, i %= 8, c >>= 8); } return i > 0 && (n--, t[n] = c & 255), t.slice(n); } } -k = new WeakMap(); +V = new WeakMap(); Promise.withResolvers || (Promise.withResolvers = function() { let r, e; return { promise: new Promise((n, i) => { r = n, e = i; }), resolve: r, reject: e }; }); -var G, D, ne, R, F, K, se, Y; -class oe { +var G, D, te, R, F, K, re, Y; +class se { /** * @param {string} [appKey] * @param {string} [appSecret] @@ -520,31 +625,31 @@ class oe { */ constructor(e, t, n) { /** @type {RequestFn | undefined} */ - p(this, G); + w(this, G); /** @type {Base62 | undefined} */ - p(this, D); + w(this, D); /** @type {string | undefined} */ - p(this, ne); - p(this, R, { + w(this, te); + w(this, R, { /** @type {Map} */ "#": /* @__PURE__ */ new Map(), /** @type {Map} */ $: /* @__PURE__ */ new Map() }); /** @type {Map>} */ - p(this, F, /* @__PURE__ */ new Map()); + w(this, F, /* @__PURE__ */ new Map()); /** @type {Set<[string, '#' | '$', RequestOptions & { method: string }, boolean]>} */ - p(this, K, /* @__PURE__ */ new Set()); + w(this, K, /* @__PURE__ */ new Set()); /** * 初始化请求实例 * @param {string} [appKey] * @param {string} [appSecret] * @param {RequestFn} [reqFn] */ - g(this, "init", (e, t, n) => { - e && _(this, ne, e), n && _(this, G, n), t && _(this, D, new Ae(t)), s(this, se).call(this); + l(this, "init", (e, t, n) => { + e && C(this, te, e), n && C(this, G, n), t && C(this, D, new xe(t)), s(this, re).call(this); }); - p(this, se, () => { + w(this, re, () => { !s(this, K).size || !s(this, G) || (s(this, K).forEach((e) => s(this, Y).call(this, ...e)), s(this, K).clear()); }); /** @@ -553,32 +658,32 @@ class oe { * @param {RequestOptions & { method: string }} params * @param {boolean} [isCacheRequest] */ - p(this, Y, (e, t, n, i = !1) => { + w(this, Y, (e, t, n, i = !1) => { if (!s(this, G)) s(this, K).add([e, t, n, i]); else { - const { url: c, method: u, ...U } = n || {}; - s(this, G).call(this, { url: c, method: u, ...U }).then((a) => { + const { url: c, method: f, ...U } = n || {}; + s(this, G).call(this, { url: c, method: f, ...U }).then((a) => { if (![0, 1].includes(a.code)) - throw ie(a.code ?? -1, a.msg ?? "响应格式错误", a.data, c, a == null ? void 0 : a.res); + throw ne(a.code ?? -1, a.msg ?? "响应格式错误", a.data, c, a == null ? void 0 : a.res); return [a.code, a.msg, a.data, c, (a == null ? void 0 : a.res) ?? ""]; }).then((a) => { const T = ( /** @type {CacheEntry} */ a ); - return (t == "#" || u == "GET") && s(this, R)[t].set(e, T), t != "#" && u == "GET" && !i && setTimeout(() => { + return (t == "#" || f == "GET") && s(this, R)[t].set(e, T), t != "#" && f == "GET" && !i && setTimeout(() => { s(this, R)[t].delete(e); }, 300), T; }).then((a) => { var T; - return (T = s(this, F).get(e)) == null ? void 0 : T.forEach((C, m, I) => { - C && C[0](a), delete I[m]; + return (T = s(this, F).get(e)) == null ? void 0 : T.forEach((_, m, I) => { + _ && _[0](a), delete I[m]; }); }).catch((a) => { var T; - s(this, R)[t].delete(e), (T = s(this, F).get(e)) == null || T.forEach((C, m, I) => { - C && C[1](a instanceof L ? a : ie(-1, a, null, c)), delete I[m]; + s(this, R)[t].delete(e), (T = s(this, F).get(e)) == null || T.forEach((_, m, I) => { + _ && _[1](a instanceof L ? a : ne(-1, a, null, c)), delete I[m]; }); }).finally(() => s(this, F).delete(e)); } @@ -589,33 +694,33 @@ class oe { * @param {boolean} [isCacheRequest] * @returns {any} 返回 Proxy 包裹的 Promise,支持链式调用 .then / .catch / .msg / .resp */ - g(this, "request", ({ url: e = "/", method: t = "GET", ...n }, i = !1) => { + l(this, "request", ({ url: e = "/", method: t = "GET", ...n }, i = !1) => { var m, I; - e = Oe(e, "/"); + e = Pe(e, "/"); const c = ( /** @type {HttpMethod} */ t.toUpperCase() - ), u = Te(JSON.stringify([e, c, n])), U = ( + ), f = Ee(JSON.stringify([e, c, n])), U = ( /** @type {'#' | '$'} */ (m = e == null ? void 0 : e.includes) != null && m.call(e, "/_/") ? "#" : "$" - ), { promise: a, resolve: T, reject: C } = Promise.withResolvers(); - return s(this, R)[U].has(u) ? (console.log("cache", e), T(s(this, R)[U].get(u))) : s(this, F).has(u) ? (I = s(this, F).get(u)) == null || I.push([T, C]) : (s(this, F).set(u, [[T, C]]), s(this, Y).call(this, u, U, { url: e, method: c, ...n }, i)), new Proxy(a, { + ), { promise: a, resolve: T, reject: _ } = Promise.withResolvers(); + return s(this, R)[U].has(f) ? (console.log("cache", e), T(s(this, R)[U].get(f))) : s(this, F).has(f) ? (I = s(this, F).get(f)) == null || I.push([T, _]) : (s(this, F).set(f, [[T, _]]), s(this, Y).call(this, f, U, { url: e, method: c, ...n }, i)), new Proxy(a, { // Symbol.for('HttpResponse') 是标记,用于外部 instanceof 识别此 Proxy 为 HttpResponse 类型 - get: (H, h) => h === Symbol.for("HttpResponse") ? !0 : (...f) => H.then((l) => ( + get: (H, h) => h === Symbol.for("HttpResponse") ? !0 : (...d) => H.then((u) => ( /** @type {any} */ - ie( + ne( .../** @type {[number, string, unknown, string, string]} */ - l - )[h](...f) - )).catch((l) => { - if (!(l instanceof L)) throw l; + u + )[h](...d) + )).catch((u) => { + if (!(u instanceof L)) throw u; return typeof /** @type {any} */ - l[h] == "function" ? ( + u[h] == "function" ? ( /** @type {any} */ - l[h](...f) + u[h](...d) ) : ( /** @type {any} */ - l[h] + u[h] ); }) }); @@ -625,57 +730,57 @@ class oe { * @param {string} url * @param {Record} [params] */ - g(this, "get", (e, t = {}) => this.request({ url: e, method: "GET", params: t })); + l(this, "get", (e, t = {}) => this.request({ url: e, method: "GET", params: t })); /** * POST 请求 * @param {string} url * @param {unknown} [data] * @param {Record} [params] */ - g(this, "post", (e, t = {}, n = {}) => this.request({ url: e, method: "POST", data: t, params: n })); + l(this, "post", (e, t = {}, n = {}) => this.request({ url: e, method: "POST", data: t, params: n })); /** * PUT 请求 * @param {string} url * @param {unknown} [data] * @param {Record} [params] */ - g(this, "put", (e, t = {}, n = {}) => this.request({ url: e, method: "PUT", data: t, params: n })); + l(this, "put", (e, t = {}, n = {}) => this.request({ url: e, method: "PUT", data: t, params: n })); /** * DELETE 请求 * @param {string} url * @param {unknown} [data] * @param {Record} [params] */ - g(this, "del", (e, t = {}, n = {}) => this.request({ url: e, method: "DELETE", data: t, params: n })); + l(this, "del", (e, t = {}, n = {}) => this.request({ url: e, method: "DELETE", data: t, params: n })); /** * 下载(待实现) * @param {string} url * @param {Record} [params] */ - g(this, "download", (e, t) => { + l(this, "download", (e, t) => { }); /** * 永久缓存 GET 请求 * @param {string} url * @param {Record} [params] */ - g(this, "cache", (e, t = {}) => this.request({ url: e, method: "GET", params: t }, !0)); + l(this, "cache", (e, t = {}) => this.request({ url: e, method: "GET", params: t }, !0)); /** * 通过 Base62 编码参数请求列表接口 * @param {string} code * @param {Base62Param} [base62param] */ - g(this, "list", (e, t = {}) => this.get(`/api/${e}/${this.encode( + l(this, "list", (e, t = {}) => this.get(`/api/${e}/${this.encode( /** @type {Record} */ t )}`)); - g(this, "getAppInfo", () => { + l(this, "getAppInfo", () => { }); /** * 清除缓存 * @param {boolean} [isSystem] 是否同时清除系统缓存(`/_/` 路由) */ - g(this, "refreshCache", (e = !1) => { + l(this, "refreshCache", (e = !1) => { e && s(this, R)["#"].clear(), s(this, R).$.clear(); }); /** @@ -684,13 +789,13 @@ class oe { * @param {object} [defaultValue] * @returns {unknown} */ - g(this, "decode", (e = "", t = {}) => { + l(this, "decode", (e = "", t = {}) => { if (e === void 0 || e === "" || e === null) return t; try { if (!s(this, D)) throw new Error("未初始化 appSecret,请先通过 init 设置 appSecret"); const n = s(this, D).decode(e); - return le.unpack(n); + return ce.unpack(n); } catch { return console.warn("core.decode", e), t; } @@ -700,27 +805,27 @@ class oe { * @param {Record | unknown[]} [json] * @returns {string} */ - g(this, "encode", (e = {}) => { + l(this, "encode", (e = {}) => { if (!s(this, D)) throw new Error("未初始化 appSecret,请先通过 init 设置 appSecret"); const t = JSON.stringify(e, (n, i) => i === void 0 ? null : i); - return s(this, D).encode(le.pack(t)); + return s(this, D).encode(ce.pack(t)); }); this.init(e, t, n); } } -G = new WeakMap(), D = new WeakMap(), ne = new WeakMap(), R = new WeakMap(), F = new WeakMap(), K = new WeakMap(), se = new WeakMap(), Y = new WeakMap(); -oe.onUnhandledRejection = (r) => { +G = new WeakMap(), D = new WeakMap(), te = new WeakMap(), R = new WeakMap(), F = new WeakMap(), K = new WeakMap(), re = new WeakMap(), Y = new WeakMap(); +se.onUnhandledRejection = (r) => { var t; const e = r instanceof L ? r : (r == null ? void 0 : r.reason) instanceof L ? r.reason : null; e != null && e.IS_ECHO_MSG && (e.$echoMsg(), (t = r == null ? void 0 : r.preventDefault) == null || t.call(r)); }; -oe.onMsg = (r, e) => [0, 1].includes(r) ? console.log(e) : console.warn(e); +se.onMsg = (r, e) => [0, 1].includes(r) ? console.log(e) : console.warn(e); export { L as HttpResponse, - ie as NewHttpResponse, - oe as default, - Te as signature, - Se as str2uint8array, - Oe as trim, - Ne as uint8array2str + ne as NewHttpResponse, + se as default, + Ee as signature, + Te as str2uint8array, + Pe as trim, + _e as uint8array2str }; diff --git a/ff-request.umd.cjs b/ff-request.umd.cjs index 3a7ac7e..924b080 100644 --- a/ff-request.umd.cjs +++ b/ff-request.umd.cjs @@ -1,2 +1,2 @@ -(function(o,f){typeof exports=="object"&&typeof module<"u"?f(exports):typeof define=="function"&&define.amd?define(["exports"],f):(o=typeof globalThis<"u"?globalThis:o||self,f(o["ff-request"]={}))})(this,function(o){"use strict";var Me=Object.defineProperty;var we=o=>{throw TypeError(o)};var Ne=(o,f,P)=>f in o?Me(o,f,{enumerable:!0,configurable:!0,writable:!0,value:P}):o[f]=P;var v=(o,f,P)=>Ne(o,typeof f!="symbol"?f+"":f,P),be=(o,f,P)=>f.has(o)||we("Cannot "+P);var n=(o,f,P)=>(be(o,f,"read from private field"),P?P.call(o):f.get(o)),y=(o,f,P)=>f.has(o)?we("Cannot add the same private member more than once"):f instanceof WeakSet?f.add(o):f.set(o,P),N=(o,f,P,V)=>(be(o,f,"write to private field"),V?V.call(o,P):f.set(o,P),P);var R,k,G,H,ne,se,Y,ie,oe,ae,ce,Q,W,L,K,ue,$,F,q,le,X;function f(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var P={};(function(s){(function(e){e([],function(){var t=-1,r=-2,i=-3,u=-4,d=-5,B=function(l,g){g=g||{};var h=g.verbose||!1;h&&console.log("Normalize the JSON Object"),l=typeof l=="string"?this.JSON.parse(l):l,h&&console.log("Creating a empty dictionary");var p={strings:[],integers:[],floats:[]};h&&console.log("Creating the AST");var w=function x(a){h&&console.log("Calling recursiveAstBuilder with "+this.JSON.stringify(a));var E=typeof a;if(a===null)return{type:"null",index:i};if(typeof a>"u")return{type:"undefined",index:d};if(a instanceof Array){var _=["@"];for(var T in a)a.hasOwnProperty(T)&&_.push(x(a[T]));return _}if(E==="object"){var _=["$"];for(var j in a)a.hasOwnProperty(j)&&(_.push(x(j)),_.push(x(a[j])));return _}if(a==="")return{type:"empty",index:u};if(E==="string"){var S=Z.call(p.strings,a);return S==-1&&(p.strings.push(m(a)),S=p.strings.length-1),{type:"strings",index:S}}if(E==="number"&&a%1===0){var S=Z.call(p.integers,a);return S==-1&&(p.integers.push(C(a)),S=p.integers.length-1),{type:"integers",index:S}}if(E==="number"){var S=Z.call(p.floats,a);return S==-1&&(p.floats.push(a),S=p.floats.length-1),{type:"floats",index:S}}if(E==="boolean")return{type:"boolean",index:a?t:r};throw new Error("Unexpected argument of type "+typeof a)}(l),O=p.strings.length,z=p.integers.length;p.floats.length,h&&console.log("Parsing the dictionary");var I=p.strings.join("|");return I+="^"+p.integers.join("|"),I+="^"+p.floats.join("|"),h&&console.log("Parsing the structure"),I+="^"+function x(a){if(h&&console.log("Calling a recursiveParser with "+this.JSON.stringify(a)),a instanceof Array){var E=a.shift();for(var _ in a)a.hasOwnProperty(_)&&(E+=x(a[_])+"|");return(E[E.length-1]==="|"?E.slice(0,-1):E)+"]"}var T=a.type,j=a.index;if(T==="strings")return C(j);if(T==="integers")return C(O+j);if(T==="floats")return C(O+z+j);if(T==="boolean")return a.index;if(T==="null")return i;if(T==="undefined")return d;if(T==="empty")return u;throw new TypeError("The item is alien!")}(w),h&&console.log("Ending parser"),g.debug?{dictionary:p,ast:w,packed:I}:I},c=function(l,g){g=g||{};var h=l.split("^");g.verbose&&console.log("Building dictionary");var p=[],w=h[0];if(w!==""){w=w.split("|"),g.verbose&&console.log("Parse the strings dictionary");for(var O=0,z=w.length;On(this,ne).call(this,t),set:(e,t)=>{throw new TypeError(`HttpResponse 是只读的,不能设置属性 "${t}"`)},ownKeys:()=>Object.keys(n(this,H).getPrototypeOf()||{}),getPrototypeOf:()=>n(this,k)?this:this.data,getOwnPropertyDescriptor:()=>({configurable:!0,enumerable:!0,writable:!0,value:n(this,H).getPrototypeOf()})});y(this,ne,e=>e==="$echoMsg"?n(this,Y):e==="msg"?n(this,se):e==="then"?(N(this,G,!0),n(this,ie)):e==="resp"?(N(this,G,!0),n(this,oe)):e==="catch"?n(this,ae):e==="finally"?n(this,ce):e==="IS_ECHO_MSG"?n(this,G):Reflect.get(this,e));y(this,se,(e=r=>r,t=!1)=>{n(this,Y).call(this),N(this,k,t);try{return Promise.resolve(e==null?void 0:e(n(this,H).getPrototypeOf()))}catch(r){return Promise.reject(r)}});v(this,"toJSON",()=>({code:this.code,message:this.message,data:this.data,url:this.url,res:this.res}));v(this,"toString",()=>this.message);y(this,Y,()=>{n(this,G)&&(N(this,G,!1),re.onMsg(this.code,this.message))});y(this,ie,(e,t)=>[0,1].includes(this.code)?Promise.resolve(e==null?void 0:e(this.data)):t?Promise.resolve(t(n(this,R))):Promise.reject(n(this,R)));y(this,oe,(e,t)=>[0,1].includes(this.code)?Promise.resolve(e==null?void 0:e(this)):t?Promise.resolve(t(n(this,R))):Promise.reject(n(this,R)));y(this,ae,e=>Promise.resolve(e(n(this,R))));y(this,ce,e=>(e==null||e(),[0,1].includes(this.code)?Promise.resolve(n(this,H).getPrototypeOf()):Promise.reject(n(this,R))));return this.code=e,this.message=t,this.data=r,this.url=i,this.res=u,N(this,R,new Proxy(this,n(this,H)))}static[Symbol.hasInstance](e){return(e==null?void 0:e.constructor)===he||(e==null?void 0:e[Symbol.for("HttpResponse")])===!0}};R=new WeakMap,k=new WeakMap,G=new WeakMap,H=new WeakMap,ne=new WeakMap,se=new WeakMap,Y=new WeakMap,ie=new WeakMap,oe=new WeakMap,ae=new WeakMap,ce=new WeakMap;let J=he;const ee=(s,e,t,r="/",i="")=>new J(s,e,t,r,i);var fe=["utf8","utf-8","unicode-1-1-utf-8"];function Ee(s){if(fe.indexOf(s)<0&&typeof s<"u"&&s!=null)throw new RangeError("Invalid encoding type. Only utf-8 is supported");this.encoding="utf-8",this.encode=function(e){if(typeof e!="string")throw new TypeError("passed argument must be of tye string");var t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);const i=t.split("");for(let u=0;u"u")return"";var r=typeof t<"u"&&r in t?t.stream:!1;if(typeof r!="boolean")throw new TypeError("stream option must be boolean");if(ArrayBuffer.isView(e)){var i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),u=new Array(i.length);for(let d=0;d>>0).toString(16)}function pe(s,e){return s.replace(new RegExp(`^${e}+|${e}+$`,"g"),"")}function ve(s){return Pe.encode(s||"")}function Se(s){return Oe.decode(new DataView(s),{})}const me=62,te=30,ye=31,xe=63;class _e{constructor(e){v(this,"encodeTable",[]);v(this,"decodeMap",new Uint8Array(256).fill(255));if(e.length!==me)throw new Error("Encoding alphabet must be 62 characters long");if(e.includes(` -`)||e.includes("\r"))throw new Error("Encoding alphabet contains newline character");this.encodeTable=e.split(""),this.decodeMap=new Uint8Array(256).fill(255);for(let t=0;t>3;e===0&&(t-=1,e=8);let r=this.src[t]>>8-e;return e<6&&t>0&&(r|=this.src[t-1]<0;){let r=6,i=this.get6bits();(i&te)===te&&((this.pos>6||i>ye)&&(r=5),i&=ye),t.push(n(this,Q).encodeTable[i].charCodeAt(0)),this.pos-=r}return t}}Q=new WeakMap;class Ce{constructor(e){y(this,W);N(this,W,e)}decode(e){const t=new Uint8Array(Math.ceil(e.length*6/8)+1);let r=t.length,i=0,u=0;for(let d=0;d=8&&(r--,t[r]=u&255,i%=8,u>>=8)}return i>0&&(r--,t[r]=u&255),t.slice(r)}}W=new WeakMap,Promise.withResolvers||(Promise.withResolvers=function(){let s,e;return{promise:new Promise((r,i)=>{s=r,e=i}),resolve:s,reject:e}});class re{constructor(e,t,r){y(this,L);y(this,K);y(this,ue);y(this,$,{"#":new Map,$:new Map});y(this,F,new Map);y(this,q,new Set);v(this,"init",(e,t,r)=>{e&&N(this,ue,e),r&&N(this,L,r),t&&N(this,K,new _e(t)),n(this,le).call(this)});y(this,le,()=>{!n(this,q).size||!n(this,L)||(n(this,q).forEach(e=>n(this,X).call(this,...e)),n(this,q).clear())});y(this,X,(e,t,r,i=!1)=>{if(!n(this,L))n(this,q).add([e,t,r,i]);else{const{url:u,method:d,...B}=r||{};n(this,L).call(this,{url:u,method:d,...B}).then(c=>{if(![0,1].includes(c.code))throw ee(c.code??-1,c.msg??"响应格式错误",c.data,u,c==null?void 0:c.res);return[c.code,c.msg,c.data,u,(c==null?void 0:c.res)??""]}).then(c=>{const m=c;return(t=="#"||d=="GET")&&n(this,$)[t].set(e,m),t!="#"&&d=="GET"&&!i&&setTimeout(()=>{n(this,$)[t].delete(e)},300),m}).then(c=>{var m;return(m=n(this,F).get(e))==null?void 0:m.forEach((U,C,D)=>{U&&U[0](c),delete D[C]})}).catch(c=>{var m;n(this,$)[t].delete(e),(m=n(this,F).get(e))==null||m.forEach((U,C,D)=>{U&&U[1](c instanceof J?c:ee(-1,c,null,u)),delete D[C]})}).finally(()=>n(this,F).delete(e))}});v(this,"request",({url:e="/",method:t="GET",...r},i=!1)=>{var C,D;e=pe(e,"/");const u=t.toUpperCase(),d=ge(JSON.stringify([e,u,r])),B=(C=e==null?void 0:e.includes)!=null&&C.call(e,"/_/")?"#":"$",{promise:c,resolve:m,reject:U}=Promise.withResolvers();return n(this,$)[B].has(d)?(console.log("cache",e),m(n(this,$)[B].get(d))):n(this,F).has(d)?(D=n(this,F).get(d))==null||D.push([m,U]):(n(this,F).set(d,[[m,U]]),n(this,X).call(this,d,B,{url:e,method:u,...r},i)),new Proxy(c,{get:(Z,l)=>l===Symbol.for("HttpResponse")?!0:(...g)=>Z.then(h=>ee(...h)[l](...g)).catch(h=>{if(!(h instanceof J))throw h;return typeof h[l]=="function"?h[l](...g):h[l]})})});v(this,"get",(e,t={})=>this.request({url:e,method:"GET",params:t}));v(this,"post",(e,t={},r={})=>this.request({url:e,method:"POST",data:t,params:r}));v(this,"put",(e,t={},r={})=>this.request({url:e,method:"PUT",data:t,params:r}));v(this,"del",(e,t={},r={})=>this.request({url:e,method:"DELETE",data:t,params:r}));v(this,"download",(e,t)=>{});v(this,"cache",(e,t={})=>this.request({url:e,method:"GET",params:t},!0));v(this,"list",(e,t={})=>this.get(`/api/${e}/${this.encode(t)}`));v(this,"getAppInfo",()=>{});v(this,"refreshCache",(e=!1)=>{e&&n(this,$)["#"].clear(),n(this,$).$.clear()});v(this,"decode",(e="",t={})=>{if(e===void 0||e===""||e===null)return t;try{if(!n(this,K))throw new Error("未初始化 appSecret,请先通过 init 设置 appSecret");const r=n(this,K).decode(e);return V.unpack(r)}catch{return console.warn("core.decode",e),t}});v(this,"encode",(e={})=>{if(!n(this,K))throw new Error("未初始化 appSecret,请先通过 init 设置 appSecret");const t=JSON.stringify(e,(r,i)=>i===void 0?null:i);return n(this,K).encode(V.pack(t))});this.init(e,t,r)}}L=new WeakMap,K=new WeakMap,ue=new WeakMap,$=new WeakMap,F=new WeakMap,q=new WeakMap,le=new WeakMap,X=new WeakMap,re.onUnhandledRejection=s=>{var t;const e=s instanceof J?s:(s==null?void 0:s.reason)instanceof J?s.reason:null;e!=null&&e.IS_ECHO_MSG&&(e.$echoMsg(),(t=s==null?void 0:s.preventDefault)==null||t.call(s))},re.onMsg=(s,e)=>[0,1].includes(s)?console.log(e):console.warn(e),o.HttpResponse=J,o.NewHttpResponse=ee,o.default=re,o.signature=ge,o.str2uint8array=ve,o.trim=pe,o.uint8array2str=Se,Object.defineProperties(o,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}); +(function(o,d){typeof exports=="object"&&typeof module<"u"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(o=typeof globalThis<"u"?globalThis:o||self,d(o["ff-request"]={}))})(this,function(o){"use strict";var _e=Object.defineProperty;var ve=o=>{throw TypeError(o)};var Ce=(o,d,P)=>d in o?_e(o,d,{enumerable:!0,configurable:!0,writable:!0,value:P}):o[d]=P;var f=(o,d,P)=>Ce(o,typeof d!="symbol"?d+"":d,P),ye=(o,d,P)=>d.has(o)||ve("Cannot "+P);var n=(o,d,P)=>(ye(o,d,"read from private field"),P?P.call(o):d.get(o)),b=(o,d,P)=>d.has(o)?ve("Cannot add the same private member more than once"):d instanceof WeakSet?d.add(o):d.set(o,P),N=(o,d,P,z)=>(ye(o,d,"write to private field"),z?z.call(o,P):d.set(o,P),P);var R,V,G,H,ne,Y,se,ie,oe,Q,W,L,K,ae,$,F,q,ce,X;function d(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var P={};(function(s){(function(e){e([],function(){var t=-1,r=-2,i=-3,u=-4,g=-5,B=function(h,p){p=p||{};var l=p.verbose||!1;l&&console.log("Normalize the JSON Object"),h=typeof h=="string"?this.JSON.parse(h):h,l&&console.log("Creating a empty dictionary");var v={strings:[],integers:[],floats:[]};l&&console.log("Creating the AST");var y=function x(a){l&&console.log("Calling recursiveAstBuilder with "+this.JSON.stringify(a));var E=typeof a;if(a===null)return{type:"null",index:i};if(typeof a>"u")return{type:"undefined",index:g};if(a instanceof Array){var A=["@"];for(var T in a)a.hasOwnProperty(T)&&A.push(x(a[T]));return A}if(E==="object"){var A=["$"];for(var j in a)a.hasOwnProperty(j)&&(A.push(x(j)),A.push(x(a[j])));return A}if(a==="")return{type:"empty",index:u};if(E==="string"){var O=Z.call(v.strings,a);return O==-1&&(v.strings.push(m(a)),O=v.strings.length-1),{type:"strings",index:O}}if(E==="number"&&a%1===0){var O=Z.call(v.integers,a);return O==-1&&(v.integers.push(C(a)),O=v.integers.length-1),{type:"integers",index:O}}if(E==="number"){var O=Z.call(v.floats,a);return O==-1&&(v.floats.push(a),O=v.floats.length-1),{type:"floats",index:O}}if(E==="boolean")return{type:"boolean",index:a?t:r};throw new Error("Unexpected argument of type "+typeof a)}(h),S=v.strings.length,k=v.integers.length;v.floats.length,l&&console.log("Parsing the dictionary");var I=v.strings.join("|");return I+="^"+v.integers.join("|"),I+="^"+v.floats.join("|"),l&&console.log("Parsing the structure"),I+="^"+function x(a){if(l&&console.log("Calling a recursiveParser with "+this.JSON.stringify(a)),a instanceof Array){var E=a.shift();for(var A in a)a.hasOwnProperty(A)&&(E+=x(a[A])+"|");return(E[E.length-1]==="|"?E.slice(0,-1):E)+"]"}var T=a.type,j=a.index;if(T==="strings")return C(j);if(T==="integers")return C(S+j);if(T==="floats")return C(S+k+j);if(T==="boolean")return a.index;if(T==="null")return i;if(T==="undefined")return g;if(T==="empty")return u;throw new TypeError("The item is alien!")}(y),l&&console.log("Ending parser"),p.debug?{dictionary:v,ast:y,packed:I}:I},c=function(h,p){p=p||{};var l=h.split("^");p.verbose&&console.log("Building dictionary");var v=[],y=l[0];if(y!==""){y=y.split("|"),p.verbose&&console.log("Parse the strings dictionary");for(var S=0,k=y.length;Sn(this,ne).call(this,t),set:(e,t,r)=>{throw new TypeError(`HttpResponse 是只读的,不能设置属性 "${String(t)}"`)},ownKeys:()=>Object.keys(n(this,H).getPrototypeOf()||{}),getPrototypeOf:()=>n(this,V)?this:this.data,getOwnPropertyDescriptor:()=>({configurable:!0,enumerable:!0,writable:!0,value:n(this,H).getPrototypeOf()})});b(this,ne,e=>e==="$echoMsg"?n(this,Y):e==="then"?(N(this,G,!0),n(this,se)):e==="catch"?n(this,ie):e==="finally"?n(this,oe):e==="IS_ECHO_MSG"?n(this,G):Reflect.get(this,e));f(this,"msg",(e=r=>r,t=!1)=>{n(this,Y).call(this),N(this,V,t);try{return Promise.resolve(e==null?void 0:e(n(this,H).getPrototypeOf()))}catch(r){return Promise.reject(r)}});f(this,"resp",(e,t)=>(N(this,G,!0),[0,1].includes(this.code)?Promise.resolve(e==null?void 0:e(this)):t?Promise.resolve(t(n(this,R))):Promise.reject(n(this,R))));f(this,"toJSON",()=>({code:this.code,message:this.message,data:this.data,url:this.url,res:this.res}));f(this,"toString",()=>this.message);b(this,Y,()=>{n(this,G)&&(N(this,G,!1),re.onMsg(this.code,this.message))});b(this,se,(e,t)=>[0,1].includes(this.code)?Promise.resolve(e==null?void 0:e(this.data)):t?Promise.resolve(t(n(this,R))):Promise.reject(n(this,R)));b(this,ie,e=>Promise.resolve(e(n(this,R))));b(this,oe,e=>(e==null||e(),[0,1].includes(this.code)?Promise.resolve(n(this,H).getPrototypeOf()):Promise.reject(n(this,R))));return this.code=e,this.message=t,this.data=r,this.url=i,this.res=u,N(this,R,new Proxy(this,n(this,H)))}static[Symbol.hasInstance](e){return(e==null?void 0:e.constructor)===ue||(e==null?void 0:e[Symbol.for("HttpResponse")])===!0}};R=new WeakMap,V=new WeakMap,G=new WeakMap,H=new WeakMap,ne=new WeakMap,Y=new WeakMap,se=new WeakMap,ie=new WeakMap,oe=new WeakMap;let J=ue;const ee=(s,e,t,r="/",i="")=>new J(s,e,t,r,i);var he=["utf8","utf-8","unicode-1-1-utf-8"];function we(s){if(he.indexOf(s)<0&&typeof s<"u"&&s!=null)throw new RangeError("Invalid encoding type. Only utf-8 is supported");this.encoding="utf-8",this.encode=function(e){if(typeof e!="string")throw new TypeError("passed argument must be of tye string");var t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);const i=t.split("");for(let u=0;u"u")return"";var r=typeof t<"u"&&r in t?t.stream:!1;if(typeof r!="boolean")throw new TypeError("stream option must be boolean");if(ArrayBuffer.isView(e)){var i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),u=new Array(i.length);for(let g=0;g>>0).toString(16)}function de(s,e){return s.replace(new RegExp(`^${e}+|${e}+$`,"g"),"")}function ge(s){return Ee.encode(s||"")}function Pe(s){return Te.decode(new DataView(s),{})}const Se=62,te=30,pe=31,Oe=63;class me{constructor(e){f(this,"encodeTable",[]);f(this,"decodeMap",new Uint8Array(256).fill(255));if(e.length!==Se)throw new Error("Encoding alphabet must be 62 characters long");if(e.includes(` +`)||e.includes("\r"))throw new Error("Encoding alphabet contains newline character");this.encodeTable=e.split(""),this.decodeMap=new Uint8Array(256).fill(255);for(let t=0;t>3;e===0&&(t-=1,e=8);let r=this.src[t]>>8-e;return e<6&&t>0&&(r|=this.src[t-1]<0;){let r=6,i=this.get6bits();(i&te)===te&&((this.pos>6||i>pe)&&(r=5),i&=pe),t.push(n(this,Q).encodeTable[i].charCodeAt(0)),this.pos-=r}return t}}Q=new WeakMap;class Ae{constructor(e){b(this,W);N(this,W,e)}decode(e){const t=new Uint8Array(Math.ceil(e.length*6/8)+1);let r=t.length,i=0,u=0;for(let g=0;g=8&&(r--,t[r]=u&255,i%=8,u>>=8)}return i>0&&(r--,t[r]=u&255),t.slice(r)}}W=new WeakMap,Promise.withResolvers||(Promise.withResolvers=function(){let s,e;return{promise:new Promise((r,i)=>{s=r,e=i}),resolve:s,reject:e}});class re{constructor(e,t,r){b(this,L);b(this,K);b(this,ae);b(this,$,{"#":new Map,$:new Map});b(this,F,new Map);b(this,q,new Set);f(this,"init",(e,t,r)=>{e&&N(this,ae,e),r&&N(this,L,r),t&&N(this,K,new me(t)),n(this,ce).call(this)});b(this,ce,()=>{!n(this,q).size||!n(this,L)||(n(this,q).forEach(e=>n(this,X).call(this,...e)),n(this,q).clear())});b(this,X,(e,t,r,i=!1)=>{if(!n(this,L))n(this,q).add([e,t,r,i]);else{const{url:u,method:g,...B}=r||{};n(this,L).call(this,{url:u,method:g,...B}).then(c=>{if(![0,1].includes(c.code))throw ee(c.code??-1,c.msg??"响应格式错误",c.data,u,c==null?void 0:c.res);return[c.code,c.msg,c.data,u,(c==null?void 0:c.res)??""]}).then(c=>{const m=c;return(t=="#"||g=="GET")&&n(this,$)[t].set(e,m),t!="#"&&g=="GET"&&!i&&setTimeout(()=>{n(this,$)[t].delete(e)},300),m}).then(c=>{var m;return(m=n(this,F).get(e))==null?void 0:m.forEach((U,C,D)=>{U&&U[0](c),delete D[C]})}).catch(c=>{var m;n(this,$)[t].delete(e),(m=n(this,F).get(e))==null||m.forEach((U,C,D)=>{U&&U[1](c instanceof J?c:ee(-1,c,null,u)),delete D[C]})}).finally(()=>n(this,F).delete(e))}});f(this,"request",({url:e="/",method:t="GET",...r},i=!1)=>{var C,D;e=de(e,"/");const u=t.toUpperCase(),g=fe(JSON.stringify([e,u,r])),B=(C=e==null?void 0:e.includes)!=null&&C.call(e,"/_/")?"#":"$",{promise:c,resolve:m,reject:U}=Promise.withResolvers();return n(this,$)[B].has(g)?(console.log("cache",e),m(n(this,$)[B].get(g))):n(this,F).has(g)?(D=n(this,F).get(g))==null||D.push([m,U]):(n(this,F).set(g,[[m,U]]),n(this,X).call(this,g,B,{url:e,method:u,...r},i)),new Proxy(c,{get:(Z,h)=>h===Symbol.for("HttpResponse")?!0:(...p)=>Z.then(l=>ee(...l)[h](...p)).catch(l=>{if(!(l instanceof J))throw l;return typeof l[h]=="function"?l[h](...p):l[h]})})});f(this,"get",(e,t={})=>this.request({url:e,method:"GET",params:t}));f(this,"post",(e,t={},r={})=>this.request({url:e,method:"POST",data:t,params:r}));f(this,"put",(e,t={},r={})=>this.request({url:e,method:"PUT",data:t,params:r}));f(this,"del",(e,t={},r={})=>this.request({url:e,method:"DELETE",data:t,params:r}));f(this,"download",(e,t)=>{});f(this,"cache",(e,t={})=>this.request({url:e,method:"GET",params:t},!0));f(this,"list",(e,t={})=>this.get(`/api/${e}/${this.encode(t)}`));f(this,"getAppInfo",()=>{});f(this,"refreshCache",(e=!1)=>{e&&n(this,$)["#"].clear(),n(this,$).$.clear()});f(this,"decode",(e="",t={})=>{if(e===void 0||e===""||e===null)return t;try{if(!n(this,K))throw new Error("未初始化 appSecret,请先通过 init 设置 appSecret");const r=n(this,K).decode(e);return z.unpack(r)}catch{return console.warn("core.decode",e),t}});f(this,"encode",(e={})=>{if(!n(this,K))throw new Error("未初始化 appSecret,请先通过 init 设置 appSecret");const t=JSON.stringify(e,(r,i)=>i===void 0?null:i);return n(this,K).encode(z.pack(t))});this.init(e,t,r)}}L=new WeakMap,K=new WeakMap,ae=new WeakMap,$=new WeakMap,F=new WeakMap,q=new WeakMap,ce=new WeakMap,X=new WeakMap,re.onUnhandledRejection=s=>{var t;const e=s instanceof J?s:(s==null?void 0:s.reason)instanceof J?s.reason:null;e!=null&&e.IS_ECHO_MSG&&(e.$echoMsg(),(t=s==null?void 0:s.preventDefault)==null||t.call(s))},re.onMsg=(s,e)=>[0,1].includes(s)?console.log(e):console.warn(e),o.HttpResponse=J,o.NewHttpResponse=ee,o.default=re,o.signature=fe,o.str2uint8array=ge,o.trim=de,o.uint8array2str=Pe,Object.defineProperties(o,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}); diff --git a/package.json b/package.json index 9af6c8c..5fc276b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ff-request", - "version": "0.11.4", + "version": "0.12.1", "type": "module", "main": "./ff-request.umd.cjs", "module": "./ff-request.js", diff --git a/types/base62.d.ts b/types/base62.d.ts new file mode 100644 index 0000000..84708b4 --- /dev/null +++ b/types/base62.d.ts @@ -0,0 +1,26 @@ +export default Base62; +/** + * Base62 编码解码类 + */ +declare class Base62 { + /** + * @param {string} alphabet 62 位编码字母表 + */ + constructor(alphabet: string); + /** @type {string[]} */ + encodeTable: string[]; + /** @type {Uint8Array} */ + decodeMap: Uint8Array; + /** + * 将字符串编码为 Base62 字符串 + * @param {string} src + * @returns {string} + */ + encode(src: string): string; + /** + * 将 Base62 字符串解码为原始字符串 + * @param {string} src + * @returns {string} + */ + decode(src: string): string; +} diff --git a/types/httpRequest.d.ts b/types/httpRequest.d.ts new file mode 100644 index 0000000..aa85597 --- /dev/null +++ b/types/httpRequest.d.ts @@ -0,0 +1,102 @@ +import { RequestFn, RequestOptions, Base62Param } from './types/httpRequest'; +export default HttpRequest; +declare class HttpRequest { + /** + * @param {string} [appKey] + * @param {string} [appSecret] + * @param {RequestFn} [reqFn] + */ + constructor(appKey?: string, appSecret?: string, reqFn?: RequestFn); + /** + * 初始化请求实例 + * @param {string} [appKey] + * @param {string} [appSecret] + * @param {RequestFn} [reqFn] + */ + init: (appKey?: string, appSecret?: string, reqFn?: RequestFn) => void; + /** + * 发起请求,支持缓存与并发合并 + * @param {RequestOptions} options + * @param {boolean} [isCacheRequest] + * @returns {any} 返回 Proxy 包裹的 Promise,支持链式调用 .then / .catch / .msg / .resp + */ + request: ({ url, method, ...params }: RequestOptions, isCacheRequest?: boolean) => any; + /** + * GET 请求 + * @param {string} url + * @param {Record} [params] + */ + get: (url: string, params?: Record) => any; + /** + * POST 请求 + * @param {string} url + * @param {unknown} [data] + * @param {Record} [params] + */ + post: (url: string, data?: unknown, params?: Record) => any; + /** + * PUT 请求 + * @param {string} url + * @param {unknown} [data] + * @param {Record} [params] + */ + put: (url: string, data?: unknown, params?: Record) => any; + /** + * DELETE 请求 + * @param {string} url + * @param {unknown} [data] + * @param {Record} [params] + */ + del: (url: string, data?: unknown, params?: Record) => any; + /** + * 下载(待实现) + * @param {string} url + * @param {Record} [params] + */ + download: (url: string, params?: Record) => void; + /** + * 永久缓存 GET 请求 + * @param {string} url + * @param {Record} [params] + */ + cache: (url: string, params?: Record) => any; + /** + * 通过 Base62 编码参数请求列表接口 + * @param {string} code + * @param {Base62Param} [base62param] + */ + list: (code: string, base62param?: Base62Param) => any; + getAppInfo: () => void; + /** + * 清除缓存 + * @param {boolean} [isSystem] 是否同时清除系统缓存(`/_/` 路由) + */ + refreshCache: (isSystem?: boolean) => void; + /** + * 解码 Base62 字符串为 JSON 对象 + * @param {string} [str] + * @param {object} [defaultValue] + * @returns {unknown} + */ + decode: (str?: string, defaultValue?: object) => unknown; + /** + * 将 JSON 对象编码为 Base62 字符串 + * @param {Record | unknown[]} [json] + * @returns {string} + */ + encode: (json?: Record | unknown[]) => string; + #private; +} +declare namespace HttpRequest { + /** + * 全局未处理 rejection 处理器,适配浏览器和 Node 环境 + * @param {any} e + */ + function onUnhandledRejection(e: any): void; + /** + * 全局消息回调,默认打印到控制台 + * @param {number} code + * @param {string} msg + */ + function onMsg(code: number, msg: string): void; +} diff --git a/types/httpResponse.d.ts b/types/httpResponse.d.ts new file mode 100644 index 0000000..47f06f0 --- /dev/null +++ b/types/httpResponse.d.ts @@ -0,0 +1,91 @@ +import { HttpResponseProxy, HttpResponseData } from './types/httpResponse'; +export default HttpResponse; +export function NewHttpResponse(code: number, message: string, data: unknown, url?: string, res?: string): HttpResponseProxy; +/** + * HTTP 响应对象 + */ +export class HttpResponse { + static [Symbol.hasInstance](instance: any): boolean; + /** + * @param {number} code + * @param {string} message + * @param {unknown} data + * @param {string} url + * @param {string} res + */ + constructor(code: number, message: string, data: unknown, url: string, res: string); + /** @type {number} */ + code: number; + /** @type {string} */ + message: string; + /** @type {unknown} */ + data: unknown; + /** @type {string} */ + url: string; + /** @type {string} */ + res: string; + /** + * message 消息弹窗后回调 + * + * @overload + * @returns {Promise} + * + * @overload + * @param {(data: unknown) => unknown} fn + * @param {false} isResp + * @returns {Promise} + * + * @overload + * @param {(response: HttpResponse) => unknown} fn + * @param {true} isResp + * @returns {Promise} + * + * @param {(value: unknown | HttpResponse) => unknown} [fn] + * @param {boolean} [isResp=false] + * @returns {Promise} + * + * fn 内部抛出的异常会变成 reject,而不是同步抛出。 + */ + msg: (fn?: (value: unknown | HttpResponse) => unknown, isResp?: boolean) => Promise; + /** + * 使用完整 HttpResponse 对象处理响应 + * + * 与 msg() 的区别: + * + * msg(false) -> 回调拿 data + * + * msg(true) -> 回调拿 HttpResponse + * + * resp() -> 永远拿 HttpResponse + * + * @overload + * @returns {Promise} + * + * @overload + * @param {(response: HttpResponse) => unknown} fn + * @returns {Promise} + * + * @overload + * @param {undefined} fn + * @param {(reason: HttpResponse) => unknown} onrejected + * @returns {Promise} + * + * @param {(response: HttpResponse) => unknown} [fn] + * @param {(reason: HttpResponse) => unknown} [onrejected] + * @returns {Promise} + */ + resp: (fn?: (response: HttpResponse) => unknown, onrejected?: (reason: HttpResponse) => unknown) => Promise; + /** + * 转换成 JSON + * + * @returns {HttpResponseData} + */ + toJSON: () => HttpResponseData; + /** + * 响应消息字符串 + * + * @returns {string} + */ + toString: () => string; + #private; +} diff --git a/types/index.d.ts b/types/index.d.ts index 3b48da3..e3b99d9 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,208 +1,3 @@ -declare interface Base62Param { - /** 当前选中的 tab 标识 */ - tab?: string - /** 当前页码 */ - page?: number - /** 每页条数 */ - pageSize?: number - /** 筛选条件 */ - condition?: Record - /** 侧边栏选中项标识 */ - sider?: string - /** 搜索关键词 */ - keyword?: string -} - -declare type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' - -declare class HttpRequest { - /** - * @param {string} [appKey] - * @param {string} [appSecret] - * @param {RequestFn} [reqFn] - */ - constructor(appKey?: string, appSecret?: string, reqFn?: RequestFn); - /** - * 初始化请求实例 - * @param {string} [appKey] - * @param {string} [appSecret] - * @param {RequestFn} [reqFn] - */ - init: (appKey?: string, appSecret?: string, reqFn?: RequestFn) => void; - /** - * 发起请求,支持缓存与并发合并 - * @param {RequestOptions} options - * @param {boolean} [isCacheRequest] - * @returns {any} 返回 Proxy 包裹的 Promise,支持链式调用 .then / .catch / .msg / .resp - */ - request: ({ url, method, ...params }: RequestOptions, isCacheRequest?: boolean) => any; - /** - * GET 请求 - * @param {string} url - * @param {Record} [params] - */ - get: (url: string, params?: Record) => any; - /** - * POST 请求 - * @param {string} url - * @param {unknown} [data] - * @param {Record} [params] - */ - post: (url: string, data?: unknown, params?: Record) => any; - /** - * PUT 请求 - * @param {string} url - * @param {unknown} [data] - * @param {Record} [params] - */ - put: (url: string, data?: unknown, params?: Record) => any; - /** - * DELETE 请求 - * @param {string} url - * @param {unknown} [data] - * @param {Record} [params] - */ - del: (url: string, data?: unknown, params?: Record) => any; - /** - * 下载(待实现) - * @param {string} url - * @param {Record} [params] - */ - download: (url: string, params?: Record) => void; - /** - * 永久缓存 GET 请求 - * @param {string} url - * @param {Record} [params] - */ - cache: (url: string, params?: Record) => any; - /** - * 通过 Base62 编码参数请求列表接口 - * @param {string} code - * @param {Base62Param} [base62param] - */ - list: (code: string, base62param?: Base62Param) => any; - getAppInfo: () => void; - /** - * 清除缓存 - * @param {boolean} [isSystem] 是否同时清除系统缓存(`/_/` 路由) - */ - refreshCache: (isSystem?: boolean) => void; - /** - * 解码 Base62 字符串为 JSON 对象 - * @param {string} [str] - * @param {object} [defaultValue] - * @returns {unknown} - */ - decode: (str?: string, defaultValue?: object) => unknown; - /** - * 将 JSON 对象编码为 Base62 字符串 - * @param {Record | unknown[]} [json] - * @returns {string} - */ - encode: (json?: Record | unknown[]) => string; - #private; -} - -declare namespace HttpRequest { - /** - * 全局未处理 rejection 处理器,适配浏览器和 Node 环境 - * @param {any} e - */ - function onUnhandledRejection(e: any): void; - /** - * 全局消息回调,默认打印到控制台 - * @param {number} code - * @param {string} msg - */ - function onMsg(code: number, msg: string): void; -} -export default HttpRequest; - -/** - * @typedef {Object} HttpResponseData@typedef {Object} HttpResponseData - * @property {number} code - * @property {string} message - * @property {unknown} data - * @property {string} url - * @property {string} res - */ -export declare class HttpResponse { - static [Symbol.hasInstance](instance: any): boolean; - /** - * @param {number} code - * @param {string} message - * @param {unknown} data - * @param {string} url - * @param {string} res - */ - constructor(code: number, message: string, data: unknown, url: string, res: string); - /** @type {number} */ - code: number; - /** @type {string} */ - message: string; - /** @type {unknown} */ - data: unknown; - /** @type {string} */ - url: string; - /** @type {string} */ - res: string; - toJSON: () => { - code: number; - message: string; - data: unknown; - url: string; - res: string; - }; - toString: () => string; - msg(fn?: (value: unknown) => unknown, isResp?: false): Promise; - msg(fn?: (value: HttpResponse) => unknown, isResp: true): Promise; - then(fn?: (value: unknown) => unknown, onrejected?: (reason: unknown) => unknown): Promise; - resp(fn?: (value: HttpResponse) => unknown, onrejected?: (reason: unknown) => unknown): Promise; - catch(fn: (reason: HttpResponse) => unknown): Promise; - finally(fn?: () => void): Promise; - #private; -} - -export declare function NewHttpResponse(code: number, message: string, data: unknown, url?: string, res?: string): HttpResponse; - -declare type RequestFn = ( -config: RequestOptions & Record -) => Promise<{ code: number; msg: string; data: unknown; res?: string }> - -declare interface RequestOptions { - url?: string - method?: HttpMethod - params?: Record - data?: unknown -} - -/** - * DJB2 算法 —— 将字符串散列为十六进制字符串 - * @param {string} input - * @returns {string} - */ -export declare function signature(input: string): string; - -/** - * 将字符串编码为 Uint8Array - * @param {string} str - * @returns {Uint8Array} - */ -export declare function str2uint8array(str: string): Uint8Array; - -/** - * 去除字符串首尾指定字符 - * @param {string} str - * @param {string} char - * @returns {string} - */ -export declare function trim(str: string, char: string): string; - -/** - * 将 ArrayBuffer 解码为字符串 - * @param {ArrayBuffer} buffer - * @returns {string} - */ -export declare function uint8array2str(buffer: ArrayBuffer): string; - -export { } +export { default } from './httpRequest.js'; +export * from './util.js'; +export { default as HttpResponse, NewHttpResponse } from './httpResponse.js'; diff --git a/types/types/httpRequest.d.ts b/types/types/httpRequest.d.ts new file mode 100644 index 0000000..c950ce1 --- /dev/null +++ b/types/types/httpRequest.d.ts @@ -0,0 +1,30 @@ +export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' + +export interface Base62Param { + /** 当前选中的 tab 标识 */ + tab?: string + /** 当前页码 */ + page?: number + /** 每页条数 */ + pageSize?: number + /** 筛选条件 */ + condition?: Record + /** 侧边栏选中项标识 */ + sider?: string + /** 搜索关键词 */ + keyword?: string +} + +export interface RequestOptions { + url?: string + method?: HttpMethod + params?: Record + data?: unknown +} + +export type RequestFn = ( + config: RequestOptions & Record +) => Promise<{ code: number; msg: string; data: unknown; res?: string }> + +/** [code, msg, data, url, res] */ +export type CacheEntry = [number, string, unknown, string, string] diff --git a/types/types/httpResponse.d.ts b/types/types/httpResponse.d.ts new file mode 100644 index 0000000..d5fcd16 --- /dev/null +++ b/types/types/httpResponse.d.ts @@ -0,0 +1,49 @@ +import { default as HttpResponse } from '../httpResponse.js'; +export type HttpResponseData = { + code: number + message: string + data: unknown + url: string + res: string +} + +/** then 成功回调 */ +export type HttpResponseThenCallback = (value: unknown) => unknown + +/** Promise reject 回调 */ +export type HttpResponseRejectCallback = (reason: HttpResponse) => unknown + +/** Proxy 动态提供的 Promise API */ +export type HttpResponseProxyAPI = { + then: ( + fn: HttpResponseThenCallback | undefined, + onrejected?: HttpResponseRejectCallback + ) => Promise + + catch: (fn: HttpResponseRejectCallback) => Promise + + finally: (fn?: () => void) => Promise +} + +/** + * HttpResponse 最终对外类型 + * + * HttpResponse 本身提供: + * + * - code + * - message + * - data + * - url + * - res + * - msg() + * - resp() + * - toJSON() + * - toString() + * + * Proxy 额外提供: + * + * - then() + * - catch() + * - finally() + */ +export type HttpResponseProxy = HttpResponse & HttpResponseProxyAPI diff --git a/types/util.d.ts b/types/util.d.ts new file mode 100644 index 0000000..33f808b --- /dev/null +++ b/types/util.d.ts @@ -0,0 +1,25 @@ +/** + * DJB2 算法 —— 将字符串散列为十六进制字符串 + * @param {string} input + * @returns {string} + */ +export function signature(input: string): string; +/** + * 去除字符串首尾指定字符 + * @param {string} str + * @param {string} char + * @returns {string} + */ +export function trim(str: string, char: string): string; +/** + * 将字符串编码为 Uint8Array + * @param {string} str + * @returns {Uint8Array} + */ +export function str2uint8array(str: string): Uint8Array; +/** + * 将 ArrayBuffer 解码为字符串 + * @param {ArrayBuffer} buffer + * @returns {string} + */ +export function uint8array2str(buffer: ArrayBuffer): string;