diff --git a/ff-request.js b/ff-request.js index 503cb84..7fa829c 100644 --- a/ff-request.js +++ b/ff-request.js @@ -22,7 +22,7 @@ var ue = {}; floats: [] }; u && console.log("Creating the AST"); - var p = function O(o) { + var p = function S(o) { u && console.log("Calling recursiveAstBuilder with " + this.JSON.stringify(o)); var y = typeof o; if (o === null) @@ -36,16 +36,16 @@ var ue = {}; index: f }; if (o instanceof Array) { - var S = ["@"]; + var O = ["@"]; for (var b in o) - o.hasOwnProperty(b) && S.push(O(o[b])); - return S; + o.hasOwnProperty(b) && O.push(S(o[b])); + return O; } if (y === "object") { - var S = ["$"]; + var O = ["$"]; for (var N in o) - o.hasOwnProperty(N) && (S.push(O(N)), S.push(O(o[N]))); - return S; + o.hasOwnProperty(N) && (O.push(S(N)), O.push(S(o[N]))); + return O; } if (o === "") return { @@ -53,21 +53,21 @@ var ue = {}; index: c }; if (y === "string") { - var P = H.call(g.strings, o); + var P = q.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(g.integers, o); + var P = q.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(g.floats, o); + var P = q.call(g.floats, o); return P == -1 && (g.floats.push(o), P = g.floats.length - 1), { type: "floats", index: P @@ -82,11 +82,11 @@ var ue = {}; }(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) { + return M += "^" + g.integers.join("|"), M += "^" + g.floats.join("|"), u && console.log("Parsing the structure"), M += "^" + function S(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]) + "|"); + for (var O in o) + o.hasOwnProperty(O) && (y += S(o[O]) + "|"); return (y[y.length - 1] === "|" ? y.slice(0, -1) : y) + "]"; } var b = o.type, N = o.index; @@ -131,16 +131,16 @@ var ue = {}; g.push(parseFloat(p[E])); } p = null, d.verbose && console.log("Tokenizing the structure"); - for (var M = "", O = [], o = u[3].length, E = 0; E < o; E++) { + for (var M = "", S = [], 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; + y === "|" || y === "$" || y === "@" || y === "]" ? (M && (S.push(I(M)), M = ""), y !== "|" && S.push(y)) : M += y; } - var S = O.length, b = 0; + var O = S.length, b = 0; return d.verbose && console.log("Starting recursive parser"), function N() { - var P = O[b++]; + var P = S[b++]; if (d.verbose && console.log("Reading collection type " + (P === "$" ? "object" : "Array")), P === "@") { - for (var v = []; b < S; b++) { - var A = O[b]; + for (var v = []; b < O; b++) { + var A = S[b]; if (d.verbose && console.log("Read " + A + " symbol"), A === "]") return v; if (A === "@" || A === "$") @@ -169,12 +169,12 @@ var ue = {}; return d.verbose && console.log("Parsed " + this.JSON.stringify(v)), v; } if (P === "$") { - for (var v = {}; b < S; b++) { - var x = O[b]; + for (var v = {}; b < O; b++) { + var x = S[b]; if (x === "]") return v; x === c ? x = "" : x = g[x]; - var A = O[++b]; + var A = S[++b]; if (A === "@" || A === "$") v[x] = N(); else @@ -226,7 +226,7 @@ var ue = {}; return Number.prototype.toString.call(h, 36).toUpperCase(); }, I = function(h) { return parseInt(h, 36); - }, H = Array.prototype.indexOf || function(h, d) { + }, q = Array.prototype.indexOf || function(h, d) { for (var u = d || 0, g = this.length; u < g; u++) if (this[u] === h) return u; @@ -245,7 +245,7 @@ var ue = {}; }); })(ue); const ce = /* @__PURE__ */ pe(ue); -var $, q, j, B, W, k, X, Z, ee; +var $, H, j, B, W, k, X, Z, ee; const ie = class ie { /** * @param {number} code @@ -276,7 +276,7 @@ const ie = class ie { * * @type {boolean} */ - w(this, q, !0); + w(this, H, !0); /** * 是否已经显示消息 * @@ -313,7 +313,7 @@ const ie = class ie { /** * @returns {HttpResponse | unknown} */ - getPrototypeOf: () => s(this, q) ? this : this.data, + getPrototypeOf: () => s(this, H) ? this : this.data, /** * @returns {PropertyDescriptor} */ @@ -354,7 +354,7 @@ const ie = class ie { * fn 内部抛出的异常会变成 reject,而不是同步抛出。 */ l(this, "msg", (e = (n) => n, t = !1) => { - s(this, k).call(this), C(this, q, t); + s(this, k).call(this), C(this, H, t); try { return Promise.resolve( e == null ? void 0 : e(s(this, B).getPrototypeOf()) @@ -445,7 +445,7 @@ const ie = class ie { 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(), k = new WeakMap(), X = new WeakMap(), Z = new WeakMap(), ee = new WeakMap(); +$ = new WeakMap(), H = 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} */ @@ -507,7 +507,7 @@ function Te(r) { function _e(r) { return be.decode(new DataView(r), {}); } -const Oe = 62, Q = 30, he = 31, Se = 63; +const Se = 62, Q = 30, he = 31, Oe = 63; class xe { /** * @param {string} alphabet 62 位编码字母表 @@ -517,7 +517,7 @@ class xe { l(this, "encodeTable", []); /** @type {Uint8Array} */ l(this, "decodeMap", new Uint8Array(256).fill(255)); - if (e.length !== Oe) + if (e.length !== Se) throw new Error("Encoding alphabet must be 62 characters long"); if (e.includes(` `) || e.includes("\r")) @@ -566,7 +566,7 @@ class me { 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; + return e < 6 && t > 0 && (n |= this.src[t - 1] << e), n & Oe; } /** * @param {string} src @@ -692,7 +692,7 @@ class se { * 发起请求,支持缓存与并发合并 * @param {RequestOptions} options * @param {boolean} [isCacheRequest] - * @returns {any} 返回 Proxy 包裹的 Promise,支持链式调用 .then / .catch / .msg / .resp + * @returns {HttpResponseChainable} 返回 Proxy 包裹的 Promise,支持链式调用 .then / .catch / .msg / .resp */ l(this, "request", ({ url: e = "/", method: t = "GET", ...n }, i = !1) => { var m, I; @@ -704,9 +704,11 @@ class se { /** @type {'#' | '$'} */ (m = e == null ? void 0 : e.includes) != null && m.call(e, "/_/") ? "#" : "$" ), { 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, { + 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)), /** @type {HttpResponseChainable} */ + /** @type {unknown} */ + new Proxy(a, { // Symbol.for('HttpResponse') 是标记,用于外部 instanceof 识别此 Proxy 为 HttpResponse 类型 - get: (H, h) => h === Symbol.for("HttpResponse") ? !0 : (...d) => H.then((u) => ( + get: (q, h) => h === Symbol.for("HttpResponse") ? !0 : (...d) => q.then((u) => ( /** @type {any} */ ne( .../** @type {[number, string, unknown, string, string]} */ @@ -722,7 +724,13 @@ class se { /** @type {any} */ u[h] ); - }) + }), + // 这个 Proxy 只用来转发调用 then/catch/finally/msg/resp,不代表任何数据,禁止赋值 + set: (q, h) => { + throw new TypeError( + `request() 返回值是只读的,不能设置属性 "${String(h)}"` + ); + } }); }); /** diff --git a/ff-request.umd.cjs b/ff-request.umd.cjs index 924b080..82665a4 100644 --- a/ff-request.umd.cjs +++ b/ff-request.umd.cjs @@ -1,2 +1,2 @@ -(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"}})}); +(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 Ae=Object.defineProperty;var ve=o=>{throw TypeError(o)};var Ce=(o,d,P)=>d in o?Ae(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,V)=>(ye(o,d,"write to private field"),V?V.call(o,P):d.set(o,P),P);var R,Y,G,H,ne,Q,se,ie,oe,W,X,q,K,ae,$,F,L,ce,Z;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 _=["@"];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 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 _ 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(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,Y)?this:this.data,getOwnPropertyDescriptor:()=>({configurable:!0,enumerable:!0,writable:!0,value:n(this,H).getPrototypeOf()})});b(this,ne,e=>e==="$echoMsg"?n(this,Q):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,Q).call(this),N(this,Y,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,Q,()=>{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,Y=new WeakMap,G=new WeakMap,H=new WeakMap,ne=new WeakMap,Q=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,W).encodeTable[i].charCodeAt(0)),this.pos-=r}return t}}W=new WeakMap;class _e{constructor(e){b(this,X);N(this,X,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)}}X=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,q);b(this,K);b(this,ae);b(this,$,{"#":new Map,$:new Map});b(this,F,new Map);b(this,L,new Set);f(this,"init",(e,t,r)=>{e&&N(this,ae,e),r&&N(this,q,r),t&&N(this,K,new me(t)),n(this,ce).call(this)});b(this,ce,()=>{!n(this,L).size||!n(this,q)||(n(this,L).forEach(e=>n(this,Z).call(this,...e)),n(this,L).clear())});b(this,Z,(e,t,r,i=!1)=>{if(!n(this,q))n(this,L).add([e,t,r,i]);else{const{url:u,method:g,...B}=r||{};n(this,q).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,Z).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]}),set:(z,h)=>{throw new TypeError(`request() 返回值是只读的,不能设置属性 "${String(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 V.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(V.pack(t))});this.init(e,t,r)}}q=new WeakMap,K=new WeakMap,ae=new WeakMap,$=new WeakMap,F=new WeakMap,L=new WeakMap,ce=new WeakMap,Z=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 5fc276b..55cf946 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ff-request", - "version": "0.12.1", + "version": "0.12.2", "type": "module", "main": "./ff-request.umd.cjs", "module": "./ff-request.js", diff --git a/types/httpRequest.d.ts b/types/httpRequest.d.ts index aa85597..87c6f2a 100644 --- a/types/httpRequest.d.ts +++ b/types/httpRequest.d.ts @@ -1,4 +1,5 @@ import { RequestFn, RequestOptions, Base62Param } from './types/httpRequest'; +import { HttpResponseChainable } from './types/httpResponse'; export default HttpRequest; declare class HttpRequest { /** @@ -18,36 +19,36 @@ declare class HttpRequest { * 发起请求,支持缓存与并发合并 * @param {RequestOptions} options * @param {boolean} [isCacheRequest] - * @returns {any} 返回 Proxy 包裹的 Promise,支持链式调用 .then / .catch / .msg / .resp + * @returns {HttpResponseChainable} 返回 Proxy 包裹的 Promise,支持链式调用 .then / .catch / .msg / .resp */ - request: ({ url, method, ...params }: RequestOptions, isCacheRequest?: boolean) => any; + request: ({ url, method, ...params }: RequestOptions, isCacheRequest?: boolean) => HttpResponseChainable; /** * GET 请求 * @param {string} url * @param {Record} [params] */ - get: (url: string, params?: Record) => any; + get: (url: string, params?: Record) => HttpResponseChainable; /** * POST 请求 * @param {string} url * @param {unknown} [data] * @param {Record} [params] */ - post: (url: string, data?: unknown, params?: Record) => any; + post: (url: string, data?: unknown, params?: Record) => HttpResponseChainable; /** * PUT 请求 * @param {string} url * @param {unknown} [data] * @param {Record} [params] */ - put: (url: string, data?: unknown, params?: Record) => any; + put: (url: string, data?: unknown, params?: Record) => HttpResponseChainable; /** * DELETE 请求 * @param {string} url * @param {unknown} [data] * @param {Record} [params] */ - del: (url: string, data?: unknown, params?: Record) => any; + del: (url: string, data?: unknown, params?: Record) => HttpResponseChainable; /** * 下载(待实现) * @param {string} url @@ -59,13 +60,13 @@ declare class HttpRequest { * @param {string} url * @param {Record} [params] */ - cache: (url: string, params?: Record) => any; + cache: (url: string, params?: Record) => HttpResponseChainable; /** * 通过 Base62 编码参数请求列表接口 * @param {string} code * @param {Base62Param} [base62param] */ - list: (code: string, base62param?: Base62Param) => any; + list: (code: string, base62param?: Base62Param) => HttpResponseChainable; getAppInfo: () => void; /** * 清除缓存 diff --git a/types/types/httpResponse.d.ts b/types/types/httpResponse.d.ts index d5fcd16..7269222 100644 --- a/types/types/httpResponse.d.ts +++ b/types/types/httpResponse.d.ts @@ -25,6 +25,16 @@ export type HttpResponseProxyAPI = { finally: (fn?: () => void) => Promise } +/** + * HttpResponse 上所有"可链式调用"的方法(then/catch/finally 来自 Proxy,msg/resp 来自 + * HttpResponse 本身——用 Pick 直接引用类上的定义,避免和 @overload 的类型重复维护)。 + * + * request() 返回的是一个包裹着 pending Promise 的 Proxy:对任意 key 的访问都会返回一个 + * "等 Promise resolve 后再转发调用"的函数,并不提供 code/data 这类同步属性, + * 所以它的类型应该是这个(不能直接用 HttpResponseProxy,那个类型意味着同步属性也存在)。 + */ +export type HttpResponseChainable = HttpResponseProxyAPI & Pick + /** * HttpResponse 最终对外类型 *