@whitesev/utils 2.3.0 → 2.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1577,7 +1577,7 @@ class Httpx {
1577
1577
  return uuid;
1578
1578
  }
1579
1579
  else {
1580
- console.warn("HttpxRequestHook.addBeforeRequestCallBack: fn is not a function");
1580
+ console.warn("[Httpx-HttpxRequestHook.addBeforeRequestCallBack] fn is not a function");
1581
1581
  }
1582
1582
  },
1583
1583
  /**
@@ -2056,65 +2056,81 @@ class Httpx {
2056
2056
  */
2057
2057
  onLoad(details, resolve, reject, argumentsList) {
2058
2058
  /* X浏览器会因为设置了responseType导致不返回responseText */
2059
- let Response = argumentsList[0];
2059
+ let originResponse = argumentsList[0];
2060
2060
  /* responseText为空,response不为空的情况 */
2061
- if (utils.isNull(Response["responseText"]) &&
2062
- utils.isNotNull(Response["response"])) {
2063
- if (typeof Response["response"] === "object") {
2061
+ if (utils.isNull(originResponse["responseText"]) &&
2062
+ utils.isNotNull(originResponse["response"])) {
2063
+ if (typeof originResponse["response"] === "object") {
2064
2064
  utils.tryCatch().run(() => {
2065
- Response["responseText"] = JSON.stringify(Response["response"]);
2065
+ originResponse["responseText"] = JSON.stringify(originResponse["response"]);
2066
2066
  });
2067
2067
  }
2068
2068
  else {
2069
- Response["responseText"] = Response["response"];
2069
+ originResponse["responseText"] = originResponse["response"];
2070
2070
  }
2071
2071
  }
2072
2072
  /* response为空,responseText不为空的情况 */
2073
- if (Response["response"] == null &&
2074
- typeof Response["responseText"] === "string" &&
2075
- Response["responseText"].trim() !== "") {
2076
- let newResponse = Response["responseText"];
2073
+ if (originResponse["response"] == null &&
2074
+ typeof originResponse["responseText"] === "string" &&
2075
+ originResponse["responseText"].trim() !== "") {
2076
+ /** 原始的请求text */
2077
+ let httpxResponseText = originResponse.responseText;
2078
+ // 自定义个新的response
2079
+ let httpxResponse = httpxResponseText;
2077
2080
  if (details.responseType === "json") {
2078
- newResponse = utils.toJSON(Response["responseText"]);
2081
+ httpxResponse = utils.toJSON(httpxResponseText);
2079
2082
  }
2080
2083
  else if (details.responseType === "document") {
2081
2084
  let parser = new DOMParser();
2082
- newResponse = parser.parseFromString(Response["responseText"], "text/html");
2085
+ httpxResponse = parser.parseFromString(httpxResponseText, "text/html");
2083
2086
  }
2084
2087
  else if (details.responseType === "arraybuffer") {
2085
2088
  let encoder = new TextEncoder();
2086
- let arrayBuffer = encoder.encode(Response["responseText"]);
2087
- newResponse = arrayBuffer;
2089
+ let arrayBuffer = encoder.encode(httpxResponseText);
2090
+ httpxResponse = arrayBuffer;
2088
2091
  }
2089
2092
  else if (details.responseType === "blob") {
2090
2093
  let encoder = new TextEncoder();
2091
- let arrayBuffer = encoder.encode(Response["responseText"]);
2092
- newResponse = new Blob([arrayBuffer]);
2093
- }
2094
- else {
2095
- newResponse = Response["responseText"];
2094
+ let arrayBuffer = encoder.encode(httpxResponseText);
2095
+ httpxResponse = new Blob([arrayBuffer]);
2096
2096
  }
2097
+ // 尝试覆盖原response
2097
2098
  try {
2098
- Response["response"] = newResponse;
2099
+ let setStatus = Reflect.set(originResponse, "response", httpxResponse);
2100
+ if (!setStatus) {
2101
+ console.warn("[Httpx-HttpxCallBack.oonLoad] 覆盖原始 response 失败,尝试添加新的httpxResponse");
2102
+ try {
2103
+ Reflect.set(originResponse, "httpxResponse", httpxResponse);
2104
+ }
2105
+ catch (error) {
2106
+ console.warn("[Httpx-HttpxCallBack.oonLoad] httpxResponse 无法被覆盖");
2107
+ }
2108
+ }
2099
2109
  }
2100
2110
  catch (error) {
2101
- console.warn("response 无法被覆盖");
2111
+ console.warn("[Httpx-HttpxCallBack.oonLoad] 原始 response 无法被覆盖,尝试添加新的httpxResponse");
2112
+ try {
2113
+ Reflect.set(originResponse, "httpxResponse", httpxResponse);
2114
+ }
2115
+ catch (error) {
2116
+ console.warn("[Httpx-HttpxCallBack.oonLoad] httpxResponse 无法被覆盖");
2117
+ }
2102
2118
  }
2103
2119
  }
2104
2120
  /* Stay扩展中没有finalUrl,对应的是responseURL */
2105
- if (Response["finalUrl"] == null &&
2106
- Response["responseURL"] != null) {
2107
- Response["finalUrl"] = Response["responseURL"];
2121
+ let originResponseURL = Reflect.get(originResponse, "responseURL");
2122
+ if (originResponse["finalUrl"] == null && originResponseURL != null) {
2123
+ Reflect.set(originResponse, "finalUrl", originResponseURL);
2108
2124
  }
2109
2125
  /* 状态码2xx都是成功的 */
2110
- if (Math.floor(Response.status / 100) === 2) {
2111
- if (this.context.HttpxResponseHook.successResponseCallBack(Response, details) == null) {
2126
+ if (Math.floor(originResponse.status / 100) === 2) {
2127
+ if (this.context.HttpxResponseHook.successResponseCallBack(originResponse, details) == null) {
2112
2128
  // reject(new TypeError("response is intercept with onloada"));
2113
2129
  return;
2114
2130
  }
2115
2131
  resolve({
2116
2132
  status: true,
2117
- data: Response,
2133
+ data: originResponse,
2118
2134
  details: details,
2119
2135
  msg: "请求完毕",
2120
2136
  type: "onload",
@@ -2159,7 +2175,7 @@ class Httpx {
2159
2175
  */
2160
2176
  request(details) {
2161
2177
  if (this.context.#LOG_DETAILS) {
2162
- console.log("Httpx请求配置👇", details);
2178
+ console.log("[Httpx-HttpxRequest.request] 请求前的配置👇", details);
2163
2179
  }
2164
2180
  if (typeof this.context.HttpxRequestHook.beforeRequestCallBack ===
2165
2181
  "function") {
@@ -2192,33 +2208,38 @@ class Httpx {
2192
2208
  */
2193
2209
  fetch(details, fetchRequestInit, abortController) {
2194
2210
  fetch(details.url, fetchRequestInit)
2195
- .then(async (resp) => {
2196
- /**
2197
- * @type {HttpxAsyncResultData}
2198
- */
2211
+ .then(async (fetchResponse) => {
2212
+ /** 自定义的response */
2199
2213
  let httpxResponse = {
2200
2214
  isFetch: true,
2201
- finalUrl: resp.url,
2215
+ finalUrl: fetchResponse.url,
2202
2216
  readyState: 4,
2203
- status: resp.status,
2204
- statusText: resp.statusText,
2217
+ // @ts-ignore
2218
+ status: fetchResponse.status,
2219
+ statusText: fetchResponse.statusText,
2205
2220
  response: void 0,
2206
- responseFetchHeaders: resp.headers,
2221
+ responseFetchHeaders: fetchResponse.headers,
2207
2222
  responseHeaders: "",
2223
+ // @ts-ignore
2208
2224
  responseText: void 0,
2209
2225
  responseType: details.responseType,
2210
2226
  responseXML: void 0,
2211
2227
  };
2212
2228
  Object.assign(httpxResponse, details.context || {});
2213
- for (const [key, value] of resp.headers.entries()) {
2229
+ // headers转为字符串
2230
+ for (const [key, value] of fetchResponse.headers.entries()) {
2214
2231
  httpxResponse.responseHeaders += `${key}: ${value}\n`;
2215
2232
  }
2216
- /* 如果是流式传输,直接返回 */
2233
+ /** 请求返回的类型 */
2234
+ const fetchResponseType = fetchResponse.headers.get("Content-Type");
2235
+ /* 如果需要stream,且获取到的是stream,那直接返回 */
2217
2236
  if (details.responseType === "stream" ||
2218
- (resp.headers.has("Content-Type") &&
2219
- resp.headers.get("Content-Type").includes("text/event-stream"))) {
2220
- httpxResponse["isStream"] = true;
2221
- httpxResponse.response = resp.body;
2237
+ (fetchResponse.headers.has("Content-Type") &&
2238
+ fetchResponse.headers
2239
+ .get("Content-Type")
2240
+ .includes("text/event-stream"))) {
2241
+ Reflect.set(httpxResponse, "isStream", true);
2242
+ Reflect.set(httpxResponse, "response", fetchResponse.body);
2222
2243
  Reflect.deleteProperty(httpxResponse, "responseText");
2223
2244
  Reflect.deleteProperty(httpxResponse, "responseXML");
2224
2245
  details.onload(httpxResponse);
@@ -2230,42 +2251,57 @@ class Httpx {
2230
2251
  let responseText = "";
2231
2252
  /** 响应xml文档 */
2232
2253
  let responseXML = "";
2233
- let arrayBuffer = await resp.arrayBuffer();
2254
+ /** 先获取二进制数据 */
2255
+ let arrayBuffer = await fetchResponse.arrayBuffer();
2256
+ /** 数据编码 */
2234
2257
  let encoding = "utf-8";
2235
- if (resp.headers.has("Content-Type")) {
2236
- let charsetMatched = resp.headers
2258
+ if (fetchResponse.headers.has("Content-Type")) {
2259
+ let charsetMatched = fetchResponse.headers
2237
2260
  .get("Content-Type")
2238
2261
  ?.match(/charset=(.+)/);
2239
2262
  if (charsetMatched) {
2240
2263
  encoding = charsetMatched[1];
2264
+ encoding = encoding.toLowerCase();
2241
2265
  }
2242
2266
  }
2267
+ // Failed to construct 'TextDecoder': The encoding label provided ('"UTF-8"') is invalid.
2268
+ // 去除引号
2269
+ encoding = encoding.replace(/('|")/gi, "");
2270
+ // 编码
2243
2271
  let textDecoder = new TextDecoder(encoding);
2244
2272
  responseText = textDecoder.decode(arrayBuffer);
2245
2273
  response = responseText;
2246
2274
  if (details.responseType === "arraybuffer") {
2275
+ // response返回格式是二进制流
2247
2276
  response = arrayBuffer;
2248
2277
  }
2249
2278
  else if (details.responseType === "blob") {
2279
+ // response返回格式是blob
2250
2280
  response = new Blob([arrayBuffer]);
2251
2281
  }
2282
+ else if (details.responseType === "json" ||
2283
+ (typeof fetchResponseType === "string" &&
2284
+ fetchResponseType.includes("application/json"))) {
2285
+ // response返回格式是JSON格式
2286
+ response = utils.toJSON(responseText);
2287
+ }
2252
2288
  else if (details.responseType === "document" ||
2253
2289
  details.responseType == null) {
2290
+ // response返回格式是文档格式
2254
2291
  let parser = new DOMParser();
2255
2292
  response = parser.parseFromString(responseText, "text/html");
2256
2293
  }
2257
- else if (details.responseType === "json") {
2258
- response = utils.toJSON(responseText);
2259
- }
2294
+ // 转为XML结构
2260
2295
  let parser = new DOMParser();
2261
2296
  responseXML = parser.parseFromString(responseText, "text/xml");
2262
- httpxResponse.response = response;
2263
- httpxResponse.responseText = responseText;
2264
- httpxResponse.responseXML = responseXML;
2297
+ Reflect.set(httpxResponse, "response", response);
2298
+ Reflect.set(httpxResponse, "responseText", responseText);
2299
+ Reflect.set(httpxResponse, "responseXML", responseXML);
2300
+ // 执行回调
2265
2301
  details.onload(httpxResponse);
2266
2302
  })
2267
- .catch((err) => {
2268
- if (err.name === "AbortError") {
2303
+ .catch((error) => {
2304
+ if (error.name === "AbortError") {
2269
2305
  return;
2270
2306
  }
2271
2307
  details.onerror({
@@ -2276,7 +2312,7 @@ class Httpx {
2276
2312
  statusText: "",
2277
2313
  responseHeaders: "",
2278
2314
  responseText: "",
2279
- error: err,
2315
+ error: error,
2280
2316
  });
2281
2317
  });
2282
2318
  details.onloadstart({
@@ -2339,7 +2375,7 @@ class Httpx {
2339
2375
  */
2340
2376
  constructor(__xmlHttpRequest__) {
2341
2377
  if (typeof __xmlHttpRequest__ !== "function") {
2342
- console.warn("Httpx未传入GM_xmlhttpRequest函数或传入的GM_xmlhttpRequest不是Function,强制使用window.fetch");
2378
+ console.warn("[Httpx-constructor] 未传入GM_xmlhttpRequest函数或传入的GM_xmlhttpRequest不是Function,将默认使用window.fetch");
2343
2379
  }
2344
2380
  this.interceptors.request.context = this;
2345
2381
  this.interceptors.response.context = this;
@@ -6403,13 +6439,29 @@ class Utils {
6403
6439
  * > ()=>{throw new Error('测试错误')}出现错误
6404
6440
  */
6405
6441
  tryCatch = TryCatch;
6406
- uniqueArray(uniqueArrayData = [], compareArrayData = [], compareFun = (item, item2) => {
6407
- // @ts-ignore
6442
+ uniqueArray(uniqueArrayData = [], compareArrayData, compareFun = (item, item2) => {
6408
6443
  return item === item2;
6409
6444
  }) {
6410
- return Array.from(uniqueArrayData).filter((item) => !Array.from(compareArrayData).some(function (item2) {
6411
- return compareFun(item, item2);
6412
- }));
6445
+ if (typeof compareArrayData === "function") {
6446
+ const compareFn = compareArrayData;
6447
+ const seen = new Set();
6448
+ const result = [];
6449
+ for (const item of uniqueArrayData) {
6450
+ // 使用compareFn函数来获取当前对象的唯一标识
6451
+ const identfier = compareFn(item);
6452
+ // 如果Set中还没有这个标识,则添加到结果数组中,并将其标识存入Set
6453
+ if (!seen.has(identfier)) {
6454
+ seen.add(identfier);
6455
+ result.push(item);
6456
+ }
6457
+ }
6458
+ return result;
6459
+ }
6460
+ else {
6461
+ return Array.from(uniqueArrayData).filter((item) => !Array.from(compareArrayData).some(function (item2) {
6462
+ return compareFun(item, item2);
6463
+ }));
6464
+ }
6413
6465
  }
6414
6466
  waitArrayLoopToEnd(data, handleFunc) {
6415
6467
  let UtilsContext = this;