Files
ff-request-dist/ff-request.js

701 lines
24 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
var de = Object.defineProperty;
var oe = (r) => {
throw TypeError(r);
};
var ge = (r, e, t) => e in r ? de(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
var g = (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 he = {};
(function(r) {
(function(e) {
e([], function() {
var t = -1, n = -2, i = -3, o = -4, l = -5, R = function(u, f) {
f = f || {};
var h = f.verbose || !1;
h && console.log("Normalize the JSON Object"), u = typeof u == "string" ? this.JSON.parse(u) : u, h && console.log("Creating a empty dictionary");
var d = {
strings: [],
integers: [],
floats: []
};
h && console.log("Creating the AST");
var p = function P(a) {
h && console.log("Calling recursiveAstBuilder with " + this.JSON.stringify(a));
var y = typeof a;
if (a === null)
return {
type: "null",
index: i
};
if (typeof a > "u")
return {
type: "undefined",
index: l
};
if (a instanceof Array) {
var S = ["@"];
for (var b in a)
a.hasOwnProperty(b) && S.push(P(a[b]));
return S;
}
if (y === "object") {
var S = ["$"];
for (var m in a)
a.hasOwnProperty(m) && (S.push(P(m)), S.push(P(a[m])));
return S;
}
if (a === "")
return {
type: "empty",
index: o
};
if (y === "string") {
var O = H.call(d.strings, a);
return O == -1 && (d.strings.push(T(a)), O = d.strings.length - 1), {
type: "strings",
index: O
};
}
if (y === "number" && a % 1 === 0) {
var O = H.call(d.integers, a);
return O == -1 && (d.integers.push(_(a)), O = d.integers.length - 1), {
type: "integers",
index: O
};
}
if (y === "number") {
var O = H.call(d.floats, a);
return O == -1 && (d.floats.push(a), O = d.floats.length - 1), {
type: "floats",
index: O
};
}
if (y === "boolean")
return {
type: "boolean",
index: a ? t : n
};
throw new Error("Unexpected argument of type " + typeof a);
}(u), E = d.strings.length, j = d.integers.length;
d.floats.length, h && console.log("Parsing the dictionary");
var N = d.strings.join("|");
return N += "^" + d.integers.join("|"), N += "^" + d.floats.join("|"), h && console.log("Parsing the structure"), N += "^" + function P(a) {
if (h && console.log("Calling a recursiveParser with " + this.JSON.stringify(a)), a instanceof Array) {
var y = a.shift();
for (var S in a)
a.hasOwnProperty(S) && (y += P(a[S]) + "|");
return (y[y.length - 1] === "|" ? y.slice(0, -1) : y) + "]";
}
var b = a.type, m = a.index;
if (b === "strings")
return _(m);
if (b === "integers")
return _(E + m);
if (b === "floats")
return _(E + j + m);
if (b === "boolean")
return a.index;
if (b === "null")
return i;
if (b === "undefined")
return l;
if (b === "empty")
return o;
throw new TypeError("The item is alien!");
}(p), h && console.log("Ending parser"), f.debug ? {
dictionary: d,
ast: p,
packed: N
} : N;
}, c = function(u, f) {
f = f || {};
var h = u.split("^");
f.verbose && console.log("Building dictionary");
var d = [], p = h[0];
if (p !== "") {
p = p.split("|"), f.verbose && console.log("Parse the strings dictionary");
for (var E = 0, j = p.length; E < j; E++)
d.push(M(p[E]));
}
if (p = h[1], p !== "") {
p = p.split("|"), f.verbose && console.log("Parse the integers dictionary");
for (var E = 0, j = p.length; E < j; E++)
d.push(U(p[E]));
}
if (p = h[2], p !== "") {
p = p.split("|"), f.verbose && console.log("Parse the floats dictionary");
for (var E = 0, j = p.length; E < j; E++)
d.push(parseFloat(p[E]));
}
p = null, f.verbose && console.log("Tokenizing the structure");
for (var N = "", P = [], a = h[3].length, E = 0; E < a; E++) {
var y = h[3].charAt(E);
y === "|" || y === "$" || y === "@" || y === "]" ? (N && (P.push(U(N)), N = ""), y !== "|" && P.push(y)) : N += y;
}
var S = P.length, b = 0;
return f.verbose && console.log("Starting recursive parser"), function m() {
var O = P[b++];
if (f.verbose && console.log("Reading collection type " + (O === "$" ? "object" : "Array")), O === "@") {
for (var v = []; b < S; b++) {
var A = P[b];
if (f.verbose && console.log("Read " + A + " symbol"), A === "]")
return v;
if (A === "@" || A === "$")
v.push(m());
else
switch (A) {
case t:
v.push(!0);
break;
case n:
v.push(!1);
break;
case i:
v.push(null);
break;
case l:
v.push(void 0);
break;
case o:
v.push("");
break;
default:
v.push(d[A]);
}
}
return f.verbose && console.log("Parsed " + this.JSON.stringify(v)), v;
}
if (O === "$") {
for (var v = {}; b < S; b++) {
var x = P[b];
if (x === "]")
return v;
x === o ? x = "" : x = d[x];
var A = P[++b];
if (A === "@" || A === "$")
v[x] = m();
else
switch (A) {
case t:
v[x] = !0;
break;
case n:
v[x] = !1;
break;
case i:
v[x] = null;
break;
case l:
v[x] = void 0;
break;
case o:
v[x] = "";
break;
default:
v[x] = d[A];
}
}
return f.verbose && console.log("Parsed " + this.JSON.stringify(v)), v;
}
throw new TypeError("Bad token " + O + " isn't a type");
}();
}, T = function(u) {
return typeof u != "string" ? u : u.replace(/[\+ \|\^\%]/g, function(f) {
return {
" ": "+",
"+": "%2B",
"|": "%7C",
"^": "%5E",
"%": "%25"
}[f];
});
}, M = function(u) {
return typeof u != "string" ? u : u.replace(/\+|%2B|%7C|%5E|%25/g, function(f) {
return {
"+": " ",
"%2B": "+",
"%7C": "|",
"%5E": "^",
"%25": "%"
}[f];
});
}, _ = function(u) {
return Number.prototype.toString.call(u, 36).toUpperCase();
}, U = function(u) {
return parseInt(u, 36);
}, H = Array.prototype.indexOf || function(u, f) {
for (var h = f || 0, d = this.length; h < d; h++)
if (this[h] === u)
return h;
return -1;
};
return {
JSON,
pack: R,
unpack: c
};
});
})(function(e, t) {
var n = t();
for (var i in n)
r[i] = n[i];
});
})(he);
const ce = /* @__PURE__ */ pe(he);
var B, L, G, I, Q, W, q, X, Z, ee;
class se {
/**
* @param {number} code
* @param {string} message
* @param {unknown} data
* @param {string} url
* @param {string} res
*/
constructor(e, t, n, i, o) {
/** @type {number} */
g(this, "code", 0);
/** @type {string} */
g(this, "message", "操作成功");
/** @type {unknown} */
g(this, "data", null);
/** @type {string} */
g(this, "url", "");
/** @type {string} */
g(this, "res", "");
/** @type {HttpResponse} */
w(this, B);
// 判断返回 Response 对象, 还是 Response 中的 data
/** @type {boolean} */
w(this, L, !0);
// 判断是否已经给出错误提示
/** @type {boolean} */
w(this, G, !0);
w(this, I, {
/** @param {any} __ @param {string} key */
get: (e, t) => s(this, Q).call(this, t),
/** @returns {string[]} */
ownKeys: () => Object.keys(s(this, I).getPrototypeOf() || {}),
/** @returns {HttpResponse | unknown} */
getPrototypeOf: () => s(this, L) ? this : this.data,
/** @returns {PropertyDescriptor} */
getOwnPropertyDescriptor: () => ({
configurable: !0,
enumerable: !0,
writable: !0,
value: s(this, I).getPrototypeOf()
})
});
/**
* @param {string} key
* @returns {unknown}
*/
w(this, Q, (e) => e === "$echoMsg" ? s(this, q) : e === "msg" ? s(this, W) : e === "then" || e === "resp" ? (C(this, G, !0), C(this, L, e === "resp"), s(this, X)) : e === "catch" ? s(this, Z) : e === "finally" ? s(this, ee) : e === "IS_ECHO_MSG" ? s(this, G) : Reflect.get(this, e));
/**
* @param {(value: unknown) => unknown} [fn]
* @param {boolean} [isResp]
* @returns {Promise<unknown>}
*/
w(this, W, (e = (n) => n, t = !1) => (s(this, q).call(this), C(this, L, t), Promise.resolve(e == null ? void 0 : e(s(this, I).getPrototypeOf()))));
w(this, q, () => {
s(this, G) && (C(this, G, !1), ie.onMsg(this.code, this.message));
});
/**
* @param {(value: unknown) => unknown} [fn]
* @returns {Promise<unknown>}
*/
w(this, X, (e) => [0, 1].includes(this.code) ? Promise.resolve(e == null ? void 0 : e(s(this, I).getPrototypeOf())) : Promise.reject(s(this, B)));
/**
* @param {(reason: HttpResponse) => unknown} fn
* @returns {Promise<unknown>}
*/
w(this, Z, (e) => Promise.resolve(e(s(this, B))));
/**
* @param {(() => void) | undefined} [fn]
* @returns {Promise<unknown>}
*/
w(this, ee, (e) => (e == null || e(), [0, 1].includes(this.code) ? Promise.resolve(s(this, I).getPrototypeOf()) : Promise.reject(s(this, B))));
return this.code = e, this.message = t, this.data = n, this.url = i, this.res = o, C(this, B, new Proxy(this, s(this, I)));
}
}
B = new WeakMap(), L = new WeakMap(), G = new WeakMap(), I = new WeakMap(), Q = new WeakMap(), W = new WeakMap(), q = new WeakMap(), X = new WeakMap(), Z = new WeakMap(), ee = new WeakMap();
const ne = (r, e, t, n = "/", i = "") => new se(r, e, t, n, i);
var ue = [
"utf8",
"utf-8",
"unicode-1-1-utf-8"
];
function ve(r) {
if (ue.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")
throw new TypeError("passed argument must be of tye string");
var t = unescape(encodeURIComponent(e)), n = new Uint8Array(t.length);
const i = t.split("");
for (let o = 0; o < i.length; o++)
n[o] = i[o].charCodeAt(0);
return n;
};
}
function we(r) {
if (ue.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")
return "";
var n = typeof t < "u" && n in t ? t.stream : !1;
if (typeof n != "boolean")
throw new TypeError("stream option must be boolean");
if (ArrayBuffer.isView(e)) {
var i = new Uint8Array(e.buffer, e.byteOffset, e.byteLength), o = new Array(i.length);
for (let l = 0; l < i.length; l++)
o[l] = String.fromCharCode(i[l]);
return decodeURIComponent(escape(o.join("")));
} else
throw new TypeError("passed argument must be an array buffer view");
};
}
var fe = {
TextEncoder: ve,
TextDecoder: we
};
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) {
return r.replace(new RegExp(`^${e}+|${e}+$`, "g"), "");
}
function Te(r) {
return ye.encode(r || "");
}
function Me(r) {
return be.decode(new DataView(r), {});
}
const Pe = 62, Y = 30, le = 31, Se = 63;
class xe {
/**
* @param {string} alphabet 62 位编码字母表
*/
constructor(e) {
/** @type {string[]} */
g(this, "encodeTable", []);
/** @type {Uint8Array} */
g(this, "decodeMap", new Uint8Array(256).fill(255));
if (e.length !== Pe)
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 < e.length; t++)
this.decodeMap[e.charCodeAt(t)] = t;
}
/**
* 将字符串编码为 Base62 字符串
* @param {string} src
* @returns {string}
*/
encode(e) {
if (!e || e.length === 0) return "";
const t = new _e(this).encodeV2(e);
return String.fromCharCode(...t);
}
/**
* 将 Base62 字符串解码为原始字符串
* @param {string} src
* @returns {string}
*/
decode(e) {
if (!e || e.length === 0) return "";
const t = new Ae(this).decode(e);
return new TextDecoder().decode(t);
}
}
var z;
class _e {
/**
* @param {Base62} b62
*/
constructor(e) {
/** @type {Base62} */
w(this, z);
/** @type {Uint8Array} */
g(this, "src", new Uint8Array());
/** @type {number} */
g(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 & Se;
}
/**
* @param {string} src
* @returns {number[]}
*/
encodeV2(e) {
this.src = Te(e), this.pos = this.src.length * 8;
const t = [];
for (; this.pos > 0; ) {
let n = 6, i = this.get6bits();
(i & Y) === Y && ((this.pos > 6 || i > le) && (n = 5), i &= le), t.push(s(this, z).encodeTable[i].charCodeAt(0)), this.pos -= n;
}
return t;
}
}
z = new WeakMap();
var V;
class Ae {
/**
* @param {Base62} b62
*/
constructor(e) {
/** @type {Base62} */
w(this, V);
C(this, V, e);
}
/**
* @param {string} src
* @returns {Uint8Array}
*/
decode(e) {
const t = new Uint8Array(Math.ceil(e.length * 6 / 8) + 1);
let n = t.length, i = 0, o = 0;
for (let l = 0; l < e.length; l++) {
const R = e[l].charCodeAt(0), c = s(this, V).decodeMap[R];
if (c === 255)
throw new Error(`CorruptInputError at index ${l}`);
l === e.length - 1 ? (o |= c << i, i += Math.ceil(Math.log2(c + 1))) : (c & Y) === Y ? (o |= c << i, i += 5) : (o |= c << i, i += 6), i >= 8 && (n--, t[n] = o & 255, i %= 8, o >>= 8);
}
return i > 0 && (n--, t[n] = o & 255), t.slice(n);
}
}
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 J, D, te, $, F, K, re, k;
class ie {
/**
* @param {string} [appKey]
* @param {string} [appSecret]
* @param {RequestFn} [reqFn]
*/
constructor(e, t, n) {
/** @type {RequestFn | undefined} */
w(this, J);
/** @type {Base62 | undefined} */
w(this, D);
/** @type {string | undefined} */
w(this, te);
w(this, $, {
/** @type {Map<string, CacheEntry>} */
"#": /* @__PURE__ */ new Map(),
/** @type {Map<string, CacheEntry>} */
$: /* @__PURE__ */ new Map()
});
/** @type {Map<string, Array<[Function, Function] | null>>} */
w(this, F, /* @__PURE__ */ new Map());
/** @type {Set<[string, '#' | '$', RequestOptions & { method: string }, boolean]>} */
w(this, K, /* @__PURE__ */ new Set());
/**
* 初始化请求实例
* @param {string} [appKey]
* @param {string} [appSecret]
* @param {RequestFn} [reqFn]
*/
g(this, "init", (e, t, n) => {
e && C(this, te, e), n && C(this, J, n), t && C(this, D, new xe(t)), s(this, re).call(this);
});
w(this, re, () => {
!s(this, K).size || !s(this, J) || (s(this, K).forEach((e) => s(this, k).call(this, ...e)), s(this, K).clear());
});
/**
* @param {string} hash
* @param {'#' | '$'} flag
* @param {RequestOptions & { method: string }} params
* @param {boolean} [isCacheRequest]
*/
w(this, k, (e, t, n, i = !1) => {
if (!s(this, J))
s(this, K).add([e, t, n, i]);
else {
const { url: o, method: l, ...R } = n || {};
s(this, J).call(this, { url: o, method: l, ...R }).then((c) => {
if (![0, 1].includes(c.code))
throw ne(c.code, c.msg, c.data, o, c == null ? void 0 : c.res);
return [c.code, c.msg, c.data, o, (c == null ? void 0 : c.res) ?? ""];
}).then((c) => {
const T = (
/** @type {CacheEntry} */
c
);
return (t == "#" || l == "GET") && s(this, $)[t].set(e, T), t != "#" && l == "GET" && !i && setTimeout(() => {
s(this, $)[t].delete(e);
}, 300), T;
}).then((c) => {
var T;
return (T = s(this, F).get(e)) == null ? void 0 : T.forEach((M, _, U) => {
M && M[0](c), delete U[_];
});
}).catch((c) => {
var T;
s(this, $)[t].delete(e), (T = s(this, F).get(e)) == null || T.forEach((M, _, U) => {
M && M[1](c instanceof se ? c : ne(-1, c, null, o)), delete U[_];
});
}).finally(() => s(this, F).delete(e));
}
});
/**
* 发起请求,支持缓存与并发合并
* @param {RequestOptions} options
* @param {boolean} [isCacheRequest]
* @returns {any} 返回 Proxy 包裹的 Promise支持链式调用 .then / .catch / .msg / .resp
*/
g(this, "request", ({ url: e = "/", method: t = "GET", ...n }, i = !1) => {
var _, U;
e = Oe(e, "/");
const o = (
/** @type {HttpMethod} */
t.toUpperCase()
), l = Ee(JSON.stringify([e, o, n])), R = (
/** @type {'#' | '$'} */
(_ = e == null ? void 0 : e.includes) != null && _.call(e, "/_/") ? "#" : "$"
), { promise: c, resolve: T, reject: M } = Promise.withResolvers();
return s(this, $)[R].has(l) ? (console.log("cache", e), T(s(this, $)[R].get(l))) : s(this, F).has(l) ? (U = s(this, F).get(l)) == null || U.push([T, M]) : (s(this, F).set(l, [[T, M]]), s(this, k).call(this, l, R, { url: e, method: o, ...n }, i)), new Proxy(c, {
get: (H, u) => (...f) => H.then((h) => (
/** @type {any} */
ne(
.../** @type {[number, string, unknown, string, string]} */
h
)[u](...f)
)).catch((h) => {
if (!(h instanceof se)) throw h;
return typeof /** @type {any} */
h[u] == "function" ? (
/** @type {any} */
h[u](...f)
) : (
/** @type {any} */
h[u]
);
})
});
});
/**
* GET 请求
* @param {string} url
* @param {Record<string, unknown>} [params]
*/
g(this, "get", (e, t = {}) => this.request({ url: e, method: "GET", params: t }));
/**
* POST 请求
* @param {string} url
* @param {unknown} [data]
* @param {Record<string, unknown>} [params]
*/
g(this, "post", (e, t = {}, n = {}) => this.request({ url: e, method: "POST", data: t, params: n }));
/**
* PUT 请求
* @param {string} url
* @param {unknown} [data]
* @param {Record<string, unknown>} [params]
*/
g(this, "put", (e, t = {}, n = {}) => this.request({ url: e, method: "PUT", data: t, params: n }));
/**
* DELETE 请求
* @param {string} url
* @param {unknown} [data]
* @param {Record<string, unknown>} [params]
*/
g(this, "del", (e, t = {}, n = {}) => this.request({ url: e, method: "DELETE", data: t, params: n }));
/**
* 下载(待实现)
* @param {string} url
* @param {Record<string, unknown>} [params]
*/
g(this, "download", (e, t) => {
});
/**
* 永久缓存 GET 请求
* @param {string} url
* @param {Record<string, unknown>} [params]
*/
g(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(
/** @type {Record<string, unknown>} */
t
)}`));
g(this, "getAppInfo", () => {
});
/**
* 清除缓存
* @param {boolean} [isSystem] 是否同时清除系统缓存(`/_/` 路由)
*/
g(this, "refreshCache", (e = !1) => {
e && s(this, $)["#"].clear(), s(this, $).$.clear();
});
/**
* 解码 Base62 字符串为 JSON 对象
* @param {string} [str]
* @param {object} [defaultValue]
* @returns {unknown}
*/
g(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 ce.unpack(n);
} catch {
return console.warn("core.decode", e), t;
}
});
/**
* 将 JSON 对象编码为 Base62 字符串
* @param {Record<string, unknown> | unknown[]} [json]
* @returns {string}
*/
g(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(ce.pack(t));
});
this.init(e, t, n);
}
}
J = new WeakMap(), D = new WeakMap(), te = new WeakMap(), $ = new WeakMap(), F = new WeakMap(), K = new WeakMap(), re = new WeakMap(), k = new WeakMap();
ie.onUnhandledRejection = (r) => {
var e, t, n, i, o, l;
r != null && r.IS_ECHO_MSG ? ((e = r == null ? void 0 : r.$echoMsg) == null || e.call(r), (t = r == null ? void 0 : r.preventDefault) == null || t.call(r)) : (n = r.reason) != null && n.IS_ECHO_MSG && ((o = (i = r.reason) == null ? void 0 : i.$echoMsg) == null || o.call(i), (l = r == null ? void 0 : r.preventDefault) == null || l.call(r));
};
ie.onMsg = (r, e) => [0, 1].includes(r) ? console.log(e) : console.warn(e);
export {
se as HttpResponse,
ne as NewHttpResponse,
ie as default,
Ee as signature,
Te as str2uint8array,
Oe as trim,
Me as uint8array2str
};