@whitesev/utils 2.2.9 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1580,7 +1580,7 @@ var Utils = (function () {
1580
1580
  return uuid;
1581
1581
  }
1582
1582
  else {
1583
- console.warn("HttpxRequestHook.addBeforeRequestCallBack: fn is not a function");
1583
+ console.warn("[Httpx-HttpxRequestHook.addBeforeRequestCallBack] fn is not a function");
1584
1584
  }
1585
1585
  },
1586
1586
  /**
@@ -2059,65 +2059,81 @@ var Utils = (function () {
2059
2059
  */
2060
2060
  onLoad(details, resolve, reject, argumentsList) {
2061
2061
  /* X浏览器会因为设置了responseType导致不返回responseText */
2062
- let Response = argumentsList[0];
2062
+ let originResponse = argumentsList[0];
2063
2063
  /* responseText为空,response不为空的情况 */
2064
- if (utils.isNull(Response["responseText"]) &&
2065
- utils.isNotNull(Response["response"])) {
2066
- if (typeof Response["response"] === "object") {
2064
+ if (utils.isNull(originResponse["responseText"]) &&
2065
+ utils.isNotNull(originResponse["response"])) {
2066
+ if (typeof originResponse["response"] === "object") {
2067
2067
  utils.tryCatch().run(() => {
2068
- Response["responseText"] = JSON.stringify(Response["response"]);
2068
+ originResponse["responseText"] = JSON.stringify(originResponse["response"]);
2069
2069
  });
2070
2070
  }
2071
2071
  else {
2072
- Response["responseText"] = Response["response"];
2072
+ originResponse["responseText"] = originResponse["response"];
2073
2073
  }
2074
2074
  }
2075
2075
  /* response为空,responseText不为空的情况 */
2076
- if (Response["response"] == null &&
2077
- typeof Response["responseText"] === "string" &&
2078
- Response["responseText"].trim() !== "") {
2079
- let newResponse = Response["responseText"];
2076
+ if (originResponse["response"] == null &&
2077
+ typeof originResponse["responseText"] === "string" &&
2078
+ originResponse["responseText"].trim() !== "") {
2079
+ /** 原始的请求text */
2080
+ let httpxResponseText = originResponse.responseText;
2081
+ // 自定义个新的response
2082
+ let httpxResponse = httpxResponseText;
2080
2083
  if (details.responseType === "json") {
2081
- newResponse = utils.toJSON(Response["responseText"]);
2084
+ httpxResponse = utils.toJSON(httpxResponseText);
2082
2085
  }
2083
2086
  else if (details.responseType === "document") {
2084
2087
  let parser = new DOMParser();
2085
- newResponse = parser.parseFromString(Response["responseText"], "text/html");
2088
+ httpxResponse = parser.parseFromString(httpxResponseText, "text/html");
2086
2089
  }
2087
2090
  else if (details.responseType === "arraybuffer") {
2088
2091
  let encoder = new TextEncoder();
2089
- let arrayBuffer = encoder.encode(Response["responseText"]);
2090
- newResponse = arrayBuffer;
2092
+ let arrayBuffer = encoder.encode(httpxResponseText);
2093
+ httpxResponse = arrayBuffer;
2091
2094
  }
2092
2095
  else if (details.responseType === "blob") {
2093
2096
  let encoder = new TextEncoder();
2094
- let arrayBuffer = encoder.encode(Response["responseText"]);
2095
- newResponse = new Blob([arrayBuffer]);
2096
- }
2097
- else {
2098
- newResponse = Response["responseText"];
2097
+ let arrayBuffer = encoder.encode(httpxResponseText);
2098
+ httpxResponse = new Blob([arrayBuffer]);
2099
2099
  }
2100
+ // 尝试覆盖原response
2100
2101
  try {
2101
- Response["response"] = newResponse;
2102
+ let setStatus = Reflect.set(originResponse, "response", httpxResponse);
2103
+ if (!setStatus) {
2104
+ console.warn("[Httpx-HttpxCallBack.oonLoad] 覆盖原始 response 失败,尝试添加新的httpxResponse");
2105
+ try {
2106
+ Reflect.set(originResponse, "httpxResponse", httpxResponse);
2107
+ }
2108
+ catch (error) {
2109
+ console.warn("[Httpx-HttpxCallBack.oonLoad] httpxResponse 无法被覆盖");
2110
+ }
2111
+ }
2102
2112
  }
2103
2113
  catch (error) {
2104
- console.warn("response 无法被覆盖");
2114
+ console.warn("[Httpx-HttpxCallBack.oonLoad] 原始 response 无法被覆盖,尝试添加新的httpxResponse");
2115
+ try {
2116
+ Reflect.set(originResponse, "httpxResponse", httpxResponse);
2117
+ }
2118
+ catch (error) {
2119
+ console.warn("[Httpx-HttpxCallBack.oonLoad] httpxResponse 无法被覆盖");
2120
+ }
2105
2121
  }
2106
2122
  }
2107
2123
  /* Stay扩展中没有finalUrl,对应的是responseURL */
2108
- if (Response["finalUrl"] == null &&
2109
- Response["responseURL"] != null) {
2110
- Response["finalUrl"] = Response["responseURL"];
2124
+ let originResponseURL = Reflect.get(originResponse, "responseURL");
2125
+ if (originResponse["finalUrl"] == null && originResponseURL != null) {
2126
+ Reflect.set(originResponse, "finalUrl", originResponseURL);
2111
2127
  }
2112
2128
  /* 状态码2xx都是成功的 */
2113
- if (Math.floor(Response.status / 100) === 2) {
2114
- if (this.context.HttpxResponseHook.successResponseCallBack(Response, details) == null) {
2129
+ if (Math.floor(originResponse.status / 100) === 2) {
2130
+ if (this.context.HttpxResponseHook.successResponseCallBack(originResponse, details) == null) {
2115
2131
  // reject(new TypeError("response is intercept with onloada"));
2116
2132
  return;
2117
2133
  }
2118
2134
  resolve({
2119
2135
  status: true,
2120
- data: Response,
2136
+ data: originResponse,
2121
2137
  details: details,
2122
2138
  msg: "请求完毕",
2123
2139
  type: "onload",
@@ -2162,7 +2178,7 @@ var Utils = (function () {
2162
2178
  */
2163
2179
  request(details) {
2164
2180
  if (this.context.#LOG_DETAILS) {
2165
- console.log("Httpx请求配置👇", details);
2181
+ console.log("[Httpx-HttpxRequest.request] 请求前的配置👇", details);
2166
2182
  }
2167
2183
  if (typeof this.context.HttpxRequestHook.beforeRequestCallBack ===
2168
2184
  "function") {
@@ -2195,33 +2211,38 @@ var Utils = (function () {
2195
2211
  */
2196
2212
  fetch(details, fetchRequestInit, abortController) {
2197
2213
  fetch(details.url, fetchRequestInit)
2198
- .then(async (resp) => {
2199
- /**
2200
- * @type {HttpxAsyncResultData}
2201
- */
2214
+ .then(async (fetchResponse) => {
2215
+ /** 自定义的response */
2202
2216
  let httpxResponse = {
2203
2217
  isFetch: true,
2204
- finalUrl: resp.url,
2218
+ finalUrl: fetchResponse.url,
2205
2219
  readyState: 4,
2206
- status: resp.status,
2207
- statusText: resp.statusText,
2220
+ // @ts-ignore
2221
+ status: fetchResponse.status,
2222
+ statusText: fetchResponse.statusText,
2208
2223
  response: void 0,
2209
- responseFetchHeaders: resp.headers,
2224
+ responseFetchHeaders: fetchResponse.headers,
2210
2225
  responseHeaders: "",
2226
+ // @ts-ignore
2211
2227
  responseText: void 0,
2212
2228
  responseType: details.responseType,
2213
2229
  responseXML: void 0,
2214
2230
  };
2215
2231
  Object.assign(httpxResponse, details.context || {});
2216
- for (const [key, value] of resp.headers.entries()) {
2232
+ // headers转为字符串
2233
+ for (const [key, value] of fetchResponse.headers.entries()) {
2217
2234
  httpxResponse.responseHeaders += `${key}: ${value}\n`;
2218
2235
  }
2219
- /* 如果是流式传输,直接返回 */
2236
+ /** 请求返回的类型 */
2237
+ const fetchResponseType = fetchResponse.headers.get("Content-Type");
2238
+ /* 如果需要stream,且获取到的是stream,那直接返回 */
2220
2239
  if (details.responseType === "stream" ||
2221
- (resp.headers.has("Content-Type") &&
2222
- resp.headers.get("Content-Type").includes("text/event-stream"))) {
2223
- httpxResponse["isStream"] = true;
2224
- httpxResponse.response = resp.body;
2240
+ (fetchResponse.headers.has("Content-Type") &&
2241
+ fetchResponse.headers
2242
+ .get("Content-Type")
2243
+ .includes("text/event-stream"))) {
2244
+ Reflect.set(httpxResponse, "isStream", true);
2245
+ Reflect.set(httpxResponse, "response", fetchResponse.body);
2225
2246
  Reflect.deleteProperty(httpxResponse, "responseText");
2226
2247
  Reflect.deleteProperty(httpxResponse, "responseXML");
2227
2248
  details.onload(httpxResponse);
@@ -2233,42 +2254,57 @@ var Utils = (function () {
2233
2254
  let responseText = "";
2234
2255
  /** 响应xml文档 */
2235
2256
  let responseXML = "";
2236
- let arrayBuffer = await resp.arrayBuffer();
2257
+ /** 先获取二进制数据 */
2258
+ let arrayBuffer = await fetchResponse.arrayBuffer();
2259
+ /** 数据编码 */
2237
2260
  let encoding = "utf-8";
2238
- if (resp.headers.has("Content-Type")) {
2239
- let charsetMatched = resp.headers
2261
+ if (fetchResponse.headers.has("Content-Type")) {
2262
+ let charsetMatched = fetchResponse.headers
2240
2263
  .get("Content-Type")
2241
2264
  ?.match(/charset=(.+)/);
2242
2265
  if (charsetMatched) {
2243
2266
  encoding = charsetMatched[1];
2267
+ encoding = encoding.toLowerCase();
2244
2268
  }
2245
2269
  }
2270
+ // Failed to construct 'TextDecoder': The encoding label provided ('"UTF-8"') is invalid.
2271
+ // 去除引号
2272
+ encoding = encoding.replace(/('|")/gi, "");
2273
+ // 编码
2246
2274
  let textDecoder = new TextDecoder(encoding);
2247
2275
  responseText = textDecoder.decode(arrayBuffer);
2248
2276
  response = responseText;
2249
2277
  if (details.responseType === "arraybuffer") {
2278
+ // response返回格式是二进制流
2250
2279
  response = arrayBuffer;
2251
2280
  }
2252
2281
  else if (details.responseType === "blob") {
2282
+ // response返回格式是blob
2253
2283
  response = new Blob([arrayBuffer]);
2254
2284
  }
2285
+ else if (details.responseType === "json" ||
2286
+ (typeof fetchResponseType === "string" &&
2287
+ fetchResponseType.includes("application/json"))) {
2288
+ // response返回格式是JSON格式
2289
+ response = utils.toJSON(responseText);
2290
+ }
2255
2291
  else if (details.responseType === "document" ||
2256
2292
  details.responseType == null) {
2293
+ // response返回格式是文档格式
2257
2294
  let parser = new DOMParser();
2258
2295
  response = parser.parseFromString(responseText, "text/html");
2259
2296
  }
2260
- else if (details.responseType === "json") {
2261
- response = utils.toJSON(responseText);
2262
- }
2297
+ // 转为XML结构
2263
2298
  let parser = new DOMParser();
2264
2299
  responseXML = parser.parseFromString(responseText, "text/xml");
2265
- httpxResponse.response = response;
2266
- httpxResponse.responseText = responseText;
2267
- httpxResponse.responseXML = responseXML;
2300
+ Reflect.set(httpxResponse, "response", response);
2301
+ Reflect.set(httpxResponse, "responseText", responseText);
2302
+ Reflect.set(httpxResponse, "responseXML", responseXML);
2303
+ // 执行回调
2268
2304
  details.onload(httpxResponse);
2269
2305
  })
2270
- .catch((err) => {
2271
- if (err.name === "AbortError") {
2306
+ .catch((error) => {
2307
+ if (error.name === "AbortError") {
2272
2308
  return;
2273
2309
  }
2274
2310
  details.onerror({
@@ -2279,7 +2315,7 @@ var Utils = (function () {
2279
2315
  statusText: "",
2280
2316
  responseHeaders: "",
2281
2317
  responseText: "",
2282
- error: err,
2318
+ error: error,
2283
2319
  });
2284
2320
  });
2285
2321
  details.onloadstart({
@@ -2342,7 +2378,7 @@ var Utils = (function () {
2342
2378
  */
2343
2379
  constructor(__xmlHttpRequest__) {
2344
2380
  if (typeof __xmlHttpRequest__ !== "function") {
2345
- console.warn("Httpx未传入GM_xmlhttpRequest函数或传入的GM_xmlhttpRequest不是Function,强制使用window.fetch");
2381
+ console.warn("[Httpx-constructor] 未传入GM_xmlhttpRequest函数或传入的GM_xmlhttpRequest不是Function,将默认使用window.fetch");
2346
2382
  }
2347
2383
  this.interceptors.request.context = this;
2348
2384
  this.interceptors.response.context = this;
@@ -3648,6 +3684,245 @@ var Utils = (function () {
3648
3684
  }
3649
3685
  }
3650
3686
 
3687
+ const VueUtils = {
3688
+ /** 标签 */
3689
+ ReactiveFlags: {
3690
+ IS_REACTIVE: Symbol("isReactive"),
3691
+ },
3692
+ /**
3693
+ * 判断是否是对象
3694
+ * @param value
3695
+ */
3696
+ isObject(value) {
3697
+ return typeof value === "object" && value !== null;
3698
+ },
3699
+ /**
3700
+ * 判断是否是函数
3701
+ * @param val
3702
+ */
3703
+ isFunction(val) {
3704
+ return typeof val === "function";
3705
+ },
3706
+ /**
3707
+ * 处理对象再次代理,可以直接返回
3708
+ * @param value
3709
+ */
3710
+ isReactive(value) {
3711
+ return !!(value && value[VueUtils.ReactiveFlags.IS_REACTIVE]);
3712
+ },
3713
+ /**
3714
+ * 判断是否是数组
3715
+ * @param value
3716
+ */
3717
+ isArray(value) {
3718
+ return Array.isArray(value);
3719
+ },
3720
+ };
3721
+ class ReactiveEffect {
3722
+ deps = [];
3723
+ active = true;
3724
+ fn;
3725
+ // @ts-ignore
3726
+ scheduler;
3727
+ constructor(fn, scheduler) {
3728
+ this.fn = fn;
3729
+ this.scheduler = scheduler;
3730
+ }
3731
+ run(cb) {
3732
+ if (!this.active) {
3733
+ this.fn();
3734
+ }
3735
+ try {
3736
+ if (typeof cb === "function") {
3737
+ cb(this);
3738
+ }
3739
+ return this.fn();
3740
+ }
3741
+ finally {
3742
+ if (typeof cb === "function") {
3743
+ cb(undefined);
3744
+ }
3745
+ }
3746
+ }
3747
+ }
3748
+ class RefImpl {
3749
+ _value;
3750
+ _isRef = true;
3751
+ _rawValue;
3752
+ _vue;
3753
+ constructor(vueIns, rawValue) {
3754
+ this._vue = vueIns;
3755
+ this._rawValue = rawValue;
3756
+ this._value = this._vue.toReactive(rawValue);
3757
+ }
3758
+ get value() {
3759
+ return this._value;
3760
+ }
3761
+ set value(newValue) {
3762
+ if (newValue !== this._rawValue) {
3763
+ this._value = this._vue.toReactive(newValue);
3764
+ this._rawValue = newValue;
3765
+ }
3766
+ }
3767
+ }
3768
+ class ObjectRefImpl {
3769
+ object;
3770
+ key;
3771
+ constructor(object, key) {
3772
+ this.object = object;
3773
+ this.key = key;
3774
+ }
3775
+ get value() {
3776
+ return this.object[this.key];
3777
+ }
3778
+ set value(newValue) {
3779
+ this.object[this.key] = newValue;
3780
+ }
3781
+ }
3782
+ class Vue {
3783
+ reactMap = new WeakMap();
3784
+ targetMap = new WeakMap();
3785
+ activeEffect = undefined;
3786
+ constructor() {
3787
+ // 将数据转化成响应式的数据,只能做对象的代理
3788
+ }
3789
+ /**
3790
+ * 生成一个被代理的对象
3791
+ * @param target 需要代理的对象
3792
+ */
3793
+ reactive(target) {
3794
+ const that = this;
3795
+ if (!(typeof target === "object" && target !== null)) {
3796
+ // @ts-ignore
3797
+ return;
3798
+ }
3799
+ if (VueUtils.isReactive(target)) {
3800
+ return target;
3801
+ }
3802
+ let exisProxy = this.reactMap.get(target);
3803
+ if (exisProxy) {
3804
+ return exisProxy;
3805
+ }
3806
+ const proxy = new Proxy(target, {
3807
+ get(target, key, receiver) {
3808
+ if (key === VueUtils.ReactiveFlags.IS_REACTIVE) {
3809
+ return true;
3810
+ }
3811
+ that.track(target, "get", key);
3812
+ return Reflect.get(target, key, receiver);
3813
+ },
3814
+ set(target, key, value, receiver) {
3815
+ let oldValue = target[key];
3816
+ let result = Reflect.set(target, key, value, receiver);
3817
+ if (oldValue !== value) {
3818
+ that.trigger(target, "set", key, oldValue, value);
3819
+ }
3820
+ return result;
3821
+ },
3822
+ });
3823
+ that.reactMap.set(target, proxy);
3824
+ return proxy;
3825
+ }
3826
+ /**
3827
+ * 观察被reactive的对象值改变
3828
+ * @param source 被观察的对象,这里采用函数返回对象
3829
+ * @param changeCallBack 值改变的回调
3830
+ */
3831
+ watch(source, changeCallBack) {
3832
+ let getter;
3833
+ if (VueUtils.isReactive(source)) {
3834
+ getter = () => this.traversal(source);
3835
+ }
3836
+ else if (VueUtils.isFunction(source)) {
3837
+ getter = source;
3838
+ }
3839
+ else {
3840
+ return;
3841
+ }
3842
+ let oldValue;
3843
+ const job = () => {
3844
+ const newValue = effect.run((activeEffect) => {
3845
+ this.activeEffect = activeEffect;
3846
+ });
3847
+ changeCallBack(newValue, oldValue);
3848
+ oldValue = newValue;
3849
+ };
3850
+ const effect = new ReactiveEffect(getter, job);
3851
+ oldValue = effect.run((activeEffect) => {
3852
+ this.activeEffect = activeEffect;
3853
+ });
3854
+ }
3855
+ toReactive(value) {
3856
+ return VueUtils.isObject(value) ? this.reactive(value) : value;
3857
+ }
3858
+ ref(value) {
3859
+ return new RefImpl(this, value);
3860
+ }
3861
+ toRef(object, key) {
3862
+ return new ObjectRefImpl(object, key);
3863
+ }
3864
+ toRefs(object) {
3865
+ const result = VueUtils.isArray(object) ? new Array(object.length) : {};
3866
+ for (let key in object) {
3867
+ // @ts-ignore
3868
+ result[key] = this.toRef(object, key);
3869
+ }
3870
+ return result;
3871
+ }
3872
+ trigger(target, type, key, oldValue, value) {
3873
+ const depsMap = this.targetMap.get(target);
3874
+ if (!depsMap)
3875
+ return;
3876
+ const effects = depsMap.get(key);
3877
+ this.triggerEffect(effects, "effects");
3878
+ }
3879
+ triggerEffect(effects, name) {
3880
+ effects &&
3881
+ effects.forEach((effect) => {
3882
+ if (effect.scheduler) {
3883
+ effect.scheduler();
3884
+ }
3885
+ else {
3886
+ effect.run();
3887
+ }
3888
+ });
3889
+ }
3890
+ track(target, type, key) {
3891
+ if (!this.activeEffect)
3892
+ return;
3893
+ let depsMap = this.targetMap.get(target);
3894
+ if (!depsMap) {
3895
+ this.targetMap.set(target, (depsMap = new Map()));
3896
+ }
3897
+ let dep = depsMap.get(key);
3898
+ if (!dep) {
3899
+ depsMap.set(key, (dep = new Set()));
3900
+ }
3901
+ this.trackEffect(dep);
3902
+ }
3903
+ trackEffect(dep) {
3904
+ if (this.activeEffect) {
3905
+ let shouldTrack = !dep.has(this.activeEffect);
3906
+ if (shouldTrack) {
3907
+ dep.add(this.activeEffect);
3908
+ this.activeEffect.deps.push(dep);
3909
+ }
3910
+ }
3911
+ }
3912
+ traversal(value, set = new Set()) {
3913
+ if (!VueUtils.isObject(value))
3914
+ return value;
3915
+ if (set.has(value)) {
3916
+ return value;
3917
+ }
3918
+ set.add(value);
3919
+ for (let key in value) {
3920
+ this.traversal(value[key], set);
3921
+ }
3922
+ return value;
3923
+ }
3924
+ }
3925
+
3651
3926
  class Utils {
3652
3927
  windowApi;
3653
3928
  constructor(option) {
@@ -5767,7 +6042,6 @@ var Utils = (function () {
5767
6042
  }
5768
6043
  /**
5769
6044
  * 申请剪贴板权限
5770
- * @returns {Promise<boolean>}
5771
6045
  */
5772
6046
  requestClipboardPermission() {
5773
6047
  return new Promise((resolve, reject) => {
@@ -5780,9 +6054,7 @@ var Utils = (function () {
5780
6054
  .then((permissionStatus) => {
5781
6055
  resolve(true);
5782
6056
  })
5783
- .catch(
5784
- /** @param {TypeError} error */
5785
- (error) => {
6057
+ .catch((error) => {
5786
6058
  console.error([
5787
6059
  "申请剪贴板权限失败,尝试直接写入👉",
5788
6060
  error.message ?? error.name ?? error.stack,
@@ -6715,6 +6987,10 @@ var Utils = (function () {
6715
6987
  * Utils.generateUUID()
6716
6988
  */
6717
6989
  generateUUID = GenerateUUID;
6990
+ /**
6991
+ * 自定义的动态响应对象
6992
+ */
6993
+ Vue = Vue;
6718
6994
  }
6719
6995
  let utils = new Utils();
6720
6996