@whitesev/utils 2.9.4 → 2.9.5

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.amd.js CHANGED
@@ -3,7 +3,7 @@ define((function () { 'use strict';
3
3
  class ColorConversion {
4
4
  /**
5
5
  * 判断是否是16进制颜色
6
- * @param str
6
+ * @param str 十六进制颜色,如`#000000`
7
7
  */
8
8
  isHex(str) {
9
9
  if (typeof str !== "string") {
@@ -18,8 +18,8 @@ define((function () { 'use strict';
18
18
  * 16进制颜色转rgba
19
19
  *
20
20
  * 例如:`#ff0000` 转为 `rgba(123,123,123, 0.4)`
21
- * @param hex
22
- * @param opacity
21
+ * @param hex 十六进制颜色,如`#000000`
22
+ * @param opacity 透明度,0~1
23
23
  */
24
24
  hexToRgba(hex, opacity) {
25
25
  if (!this.isHex(hex)) {
@@ -31,16 +31,16 @@ define((function () { 'use strict';
31
31
  }
32
32
  /**
33
33
  * hex转rgb
34
- * @param str
34
+ * @param hex 十六进制颜色,如`#000000`
35
35
  */
36
- hexToRgb(str) {
37
- if (!this.isHex(str)) {
38
- throw new TypeError(`输入错误的hex:${str}`);
36
+ hexToRgb(hex) {
37
+ if (!this.isHex(hex)) {
38
+ throw new TypeError(`输入错误的hex:${hex}`);
39
39
  }
40
40
  /* replace替换查找的到的字符串 */
41
- str = str.replace("#", "");
41
+ hex = hex.replace("#", "");
42
42
  /* match得到查询数组 */
43
- const hxs = str.match(/../g);
43
+ const hxs = hex.match(/../g);
44
44
  for (let index = 0; index < 3; index++) {
45
45
  const value = parseInt(hxs[index], 16);
46
46
  Reflect.set(hxs, index, value);
@@ -49,9 +49,10 @@ define((function () { 'use strict';
49
49
  }
50
50
  /**
51
51
  * rgb转hex
52
- * @param redValue
53
- * @param greenValue
54
- * @param blueValue
52
+ * @param redValue 红色值
53
+ * @param greenValue 绿色值
54
+ * @param blueValue 蓝色值
55
+ * @returns hex
55
56
  */
56
57
  rgbToHex(redValue, greenValue, blueValue) {
57
58
  /* 验证输入的rgb值是否合法 */
@@ -68,30 +69,36 @@ define((function () { 'use strict';
68
69
  }
69
70
  /**
70
71
  * 获取颜色变暗或亮
71
- * @param color 颜色
72
- * @param level 0~1.0
72
+ * @param color hex颜色,如`#000000`
73
+ * @param level 0~1.0 系数越大,颜色越变暗
73
74
  */
74
75
  getDarkColor(color, level) {
75
76
  if (!this.isHex(color)) {
76
77
  throw new TypeError(`输入错误的hex:${color}`);
77
78
  }
79
+ if (typeof level !== "number") {
80
+ level = Number(level);
81
+ }
78
82
  const rgbc = this.hexToRgb(color);
79
83
  for (let index = 0; index < 3; index++) {
80
84
  const rgbcItemValue = rgbc[index];
81
- const value = Math.floor(Number(rgbcItemValue) * (1 - Number(level)));
85
+ const value = Math.floor(Number(rgbcItemValue) * (1 - level));
82
86
  Reflect.set(rgbc, index, value);
83
87
  }
84
88
  return this.rgbToHex(rgbc[0], rgbc[1], rgbc[2]);
85
89
  }
86
90
  /**
87
91
  * 获取颜色变亮
88
- * @param color 颜色
89
- * @param level 0~1.0
92
+ * @param color hex颜色,如`#000000`
93
+ * @param level 0~1.0 系数越大,颜色越变亮
90
94
  */
91
95
  getLightColor(color, level) {
92
96
  if (!this.isHex(color)) {
93
97
  throw new TypeError(`输入错误的hex:${color}`);
94
98
  }
99
+ if (typeof level !== "number") {
100
+ level = Number(level);
101
+ }
95
102
  const rgbc = this.hexToRgb(color);
96
103
  for (let index = 0; index < 3; index++) {
97
104
  const rgbcItemValue = Number(rgbc[index]);
@@ -713,1001 +720,981 @@ define((function () { 'use strict';
713
720
  }
714
721
  }
715
722
 
716
- /* eslint-disable */
717
- // ==UserScript==
718
- // @name ajaxHooker
719
- // @author cxxjackie
720
- // @version 1.4.8
721
- // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
722
- // @license GNU LGPL-3.0
723
- // ==/UserScript==
724
-
725
- const ajaxHooker = function () {
726
- const version = "1.4.8";
727
- const hookInst = {
728
- hookFns: [],
729
- filters: [],
730
- };
731
- const win = window.unsafeWindow || document.defaultView || window;
732
- let winAh = win.__ajaxHooker;
733
- const resProto = win.Response.prototype;
734
- const xhrResponses = ["response", "responseText", "responseXML"];
735
- const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
736
- const xhrExtraProps = ["responseType", "timeout", "withCredentials"];
737
- const fetchExtraProps = [
738
- "cache",
739
- "credentials",
740
- "integrity",
741
- "keepalive",
742
- "mode",
743
- "priority",
744
- "redirect",
745
- "referrer",
746
- "referrerPolicy",
747
- "signal",
748
- ];
749
- const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
750
- const getType = {}.toString.call.bind({}.toString);
751
- const getDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
752
- const emptyFn = () => {};
753
- const errorFn = (e) => console.error(e);
754
- function isThenable(obj) {
755
- return obj && ["object", "function"].includes(typeof obj) && typeof obj.then === "function";
756
- }
757
- function catchError(fn, ...args) {
758
- try {
759
- const result = fn(...args);
760
- if (isThenable(result)) return result.then(null, errorFn);
761
- return result;
762
- } catch (err) {
763
- console.error(err);
764
- }
765
- }
766
- function defineProp(obj, prop, getter, setter) {
767
- Object.defineProperty(obj, prop, {
768
- configurable: true,
769
- enumerable: true,
770
- get: getter,
771
- set: setter,
772
- });
773
- }
774
- function readonly(obj, prop, value = obj[prop]) {
775
- defineProp(obj, prop, () => value, emptyFn);
776
- }
777
- function writable(obj, prop, value = obj[prop]) {
778
- Object.defineProperty(obj, prop, {
779
- configurable: true,
780
- enumerable: true,
781
- writable: true,
782
- value: value,
783
- });
784
- }
785
- function parseHeaders(obj) {
786
- const headers = {};
787
- switch (getType(obj)) {
788
- case "[object String]":
789
- for (const line of obj.trim().split(/[\r\n]+/)) {
790
- const [header, value] = line.split(/(?<=^[^:]+)\s*:\s*/);
791
- if (!value) continue;
792
- const lheader = header.toLowerCase();
793
- headers[lheader] = lheader in headers ? `${headers[lheader]}, ${value}` : value;
794
- }
795
- break;
796
- case "[object Headers]":
797
- for (const [key, val] of obj) {
798
- headers[key] = val;
799
- }
800
- break;
801
- case "[object Object]":
802
- return { ...obj };
803
- }
804
- return headers;
805
- }
806
- function stopImmediatePropagation() {
807
- this.ajaxHooker_isStopped = true;
808
- }
809
- class SyncThenable {
810
- then(fn) {
811
- fn && fn();
812
- return new SyncThenable();
813
- }
814
- }
815
- class AHRequest {
816
- constructor(request) {
817
- this.request = request;
818
- this.requestClone = { ...this.request };
819
- }
820
- _recoverRequestKey(key) {
821
- if (key in this.requestClone) this.request[key] = this.requestClone[key];
822
- else delete this.request[key];
823
- }
824
- shouldFilter(filters) {
825
- const { type, url, method, async } = this.request;
826
- return (
827
- filters.length &&
828
- !filters.find((obj) => {
829
- switch (true) {
830
- case obj.type && obj.type !== type:
831
- case getType(obj.url) === "[object String]" && !url.includes(obj.url):
832
- case getType(obj.url) === "[object RegExp]" && !obj.url.test(url):
833
- case obj.method && obj.method.toUpperCase() !== method.toUpperCase():
834
- case "async" in obj && obj.async !== async:
835
- return false;
836
- }
837
- return true;
838
- })
839
- );
840
- }
841
- waitForRequestKeys() {
842
- if (!this.request.async) {
843
- win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
844
- if (this.shouldFilter(filters)) return;
845
- hookFns.forEach((fn) => {
846
- if (getType(fn) === "[object Function]") catchError(fn, this.request);
847
- });
848
- for (const key in this.request) {
849
- if (isThenable(this.request[key])) this._recoverRequestKey(key);
850
- }
851
- });
852
- return new SyncThenable();
853
- }
854
- const promises = [];
855
- const ignoreKeys = new Set(["type", "async", "response"]);
856
- win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
857
- if (this.shouldFilter(filters)) return;
858
- promises.push(
859
- Promise.all(hookFns.map((fn) => catchError(fn, this.request))).then(() => {
860
- const requestKeys = [];
861
- for (const key in this.request) !ignoreKeys.has(key) && requestKeys.push(key);
862
- return Promise.all(
863
- requestKeys.map((key) =>
864
- Promise.resolve(this.request[key]).then(
865
- (val) => (this.request[key] = val),
866
- () => this._recoverRequestKey(key)
867
- )
868
- )
869
- );
870
- })
871
- );
872
- });
873
- return Promise.all(promises);
874
- }
875
- waitForResponseKeys(response) {
876
- const responseKeys = this.request.type === "xhr" ? xhrResponses : fetchResponses;
877
- if (!this.request.async) {
878
- if (getType(this.request.response) === "[object Function]") {
879
- catchError(this.request.response, response);
880
- responseKeys.forEach((key) => {
881
- if ("get" in getDescriptor(response, key) || isThenable(response[key])) {
882
- delete response[key];
883
- }
884
- });
885
- }
886
- return new SyncThenable();
887
- }
888
- return Promise.resolve(catchError(this.request.response, response)).then(() =>
889
- Promise.all(
890
- responseKeys.map((key) => {
891
- const descriptor = getDescriptor(response, key);
892
- if (descriptor && "value" in descriptor) {
893
- return Promise.resolve(descriptor.value).then(
894
- (val) => (response[key] = val),
895
- () => delete response[key]
896
- );
897
- } else {
898
- delete response[key];
899
- }
900
- })
901
- )
902
- );
903
- }
904
- }
905
- const proxyHandler = {
906
- get(target, prop) {
907
- const descriptor = getDescriptor(target, prop);
908
- if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.get)
909
- return target[prop];
910
- const ah = target.__ajaxHooker;
911
- if (ah && ah.proxyProps) {
912
- if (prop in ah.proxyProps) {
913
- const pDescriptor = ah.proxyProps[prop];
914
- if ("get" in pDescriptor) return pDescriptor.get();
915
- if (typeof pDescriptor.value === "function") return pDescriptor.value.bind(ah);
916
- return pDescriptor.value;
917
- }
918
- if (typeof target[prop] === "function") return target[prop].bind(target);
919
- }
920
- return target[prop];
921
- },
922
- set(target, prop, value) {
923
- const descriptor = getDescriptor(target, prop);
924
- if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.set) return true;
925
- const ah = target.__ajaxHooker;
926
- if (ah && ah.proxyProps && prop in ah.proxyProps) {
927
- const pDescriptor = ah.proxyProps[prop];
928
- pDescriptor.set ? pDescriptor.set(value) : (pDescriptor.value = value);
929
- } else {
930
- target[prop] = value;
931
- }
932
- return true;
933
- },
934
- };
935
- class XhrHooker {
936
- constructor(xhr) {
937
- const ah = this;
938
- Object.assign(ah, {
939
- originalXhr: xhr,
940
- proxyXhr: new Proxy(xhr, proxyHandler),
941
- resThenable: new SyncThenable(),
942
- proxyProps: {},
943
- proxyEvents: {},
944
- });
945
- xhr.addEventListener("readystatechange", (e) => {
946
- if (ah.proxyXhr.readyState === 4 && ah.request && typeof ah.request.response === "function") {
947
- const response = {
948
- finalUrl: ah.proxyXhr.responseURL,
949
- status: ah.proxyXhr.status,
950
- responseHeaders: parseHeaders(ah.proxyXhr.getAllResponseHeaders()),
951
- };
952
- const tempValues = {};
953
- for (const key of xhrResponses) {
954
- try {
955
- tempValues[key] = ah.originalXhr[key];
956
- } catch (err) {}
957
- defineProp(
958
- response,
959
- key,
960
- () => {
961
- return (response[key] = tempValues[key]);
962
- },
963
- (val) => {
964
- delete response[key];
965
- response[key] = val;
966
- }
967
- );
968
- }
969
- ah.resThenable = new AHRequest(ah.request).waitForResponseKeys(response).then(() => {
970
- for (const key of xhrResponses) {
971
- ah.proxyProps[key] = {
972
- get: () => {
973
- if (!(key in response)) response[key] = tempValues[key];
974
- return response[key];
975
- },
976
- };
977
- }
978
- });
979
- }
980
- ah.dispatchEvent(e);
981
- });
982
- xhr.addEventListener("load", (e) => ah.dispatchEvent(e));
983
- xhr.addEventListener("loadend", (e) => ah.dispatchEvent(e));
984
- for (const evt of xhrAsyncEvents) {
985
- const onEvt = "on" + evt;
986
- ah.proxyProps[onEvt] = {
987
- get: () => ah.proxyEvents[onEvt] || null,
988
- set: (val) => ah.addEvent(onEvt, val),
989
- };
990
- }
991
- for (const method of ["setRequestHeader", "addEventListener", "removeEventListener", "open", "send"]) {
992
- ah.proxyProps[method] = { value: ah[method] };
993
- }
994
- }
995
- toJSON() {} // Converting circular structure to JSON
996
- addEvent(type, event) {
997
- if (type.startsWith("on")) {
998
- this.proxyEvents[type] = typeof event === "function" ? event : null;
999
- } else {
1000
- if (typeof event === "object" && event !== null) event = event.handleEvent;
1001
- if (typeof event !== "function") return;
1002
- this.proxyEvents[type] = this.proxyEvents[type] || new Set();
1003
- this.proxyEvents[type].add(event);
1004
- }
1005
- }
1006
- removeEvent(type, event) {
1007
- if (type.startsWith("on")) {
1008
- this.proxyEvents[type] = null;
1009
- } else {
1010
- if (typeof event === "object" && event !== null) event = event.handleEvent;
1011
- this.proxyEvents[type] && this.proxyEvents[type].delete(event);
1012
- }
1013
- }
1014
- dispatchEvent(e) {
1015
- e.stopImmediatePropagation = stopImmediatePropagation;
1016
- defineProp(e, "target", () => this.proxyXhr);
1017
- defineProp(e, "currentTarget", () => this.proxyXhr);
1018
- defineProp(e, "srcElement", () => this.proxyXhr);
1019
- this.proxyEvents[e.type] &&
1020
- this.proxyEvents[e.type].forEach((fn) => {
1021
- this.resThenable.then(() => !e.ajaxHooker_isStopped && fn.call(this.proxyXhr, e));
1022
- });
1023
- if (e.ajaxHooker_isStopped) return;
1024
- const onEvent = this.proxyEvents["on" + e.type];
1025
- onEvent && this.resThenable.then(onEvent.bind(this.proxyXhr, e));
1026
- }
1027
- setRequestHeader(header, value) {
1028
- this.originalXhr.setRequestHeader(header, value);
1029
- if (!this.request) return;
1030
- const headers = this.request.headers;
1031
- headers[header] = header in headers ? `${headers[header]}, ${value}` : value;
1032
- }
1033
- addEventListener(...args) {
1034
- if (xhrAsyncEvents.includes(args[0])) {
1035
- this.addEvent(args[0], args[1]);
1036
- } else {
1037
- this.originalXhr.addEventListener(...args);
1038
- }
1039
- }
1040
- removeEventListener(...args) {
1041
- if (xhrAsyncEvents.includes(args[0])) {
1042
- this.removeEvent(args[0], args[1]);
1043
- } else {
1044
- this.originalXhr.removeEventListener(...args);
1045
- }
1046
- }
1047
- open(method, url, async = true, ...args) {
1048
- this.request = {
1049
- type: "xhr",
1050
- url: url.toString(),
1051
- method: method.toUpperCase(),
1052
- abort: false,
1053
- headers: {},
1054
- data: null,
1055
- response: null,
1056
- async: !!async,
1057
- };
1058
- this.openArgs = args;
1059
- this.resThenable = new SyncThenable();
1060
- ["responseURL", "readyState", "status", "statusText", ...xhrResponses].forEach((key) => {
1061
- delete this.proxyProps[key];
1062
- });
1063
- return this.originalXhr.open(method, url, async, ...args);
1064
- }
1065
- send(data) {
1066
- const ah = this;
1067
- const xhr = ah.originalXhr;
1068
- const request = ah.request;
1069
- if (!request) return xhr.send(data);
1070
- request.data = data;
1071
- new AHRequest(request).waitForRequestKeys().then(() => {
1072
- if (request.abort) {
1073
- if (typeof request.response === "function") {
1074
- Object.assign(ah.proxyProps, {
1075
- responseURL: { value: request.url },
1076
- readyState: { value: 4 },
1077
- status: { value: 200 },
1078
- statusText: { value: "OK" },
1079
- });
1080
- xhrAsyncEvents.forEach((evt) => xhr.dispatchEvent(new Event(evt)));
1081
- }
1082
- } else {
1083
- xhr.open(request.method, request.url, request.async, ...ah.openArgs);
1084
- for (const header in request.headers) {
1085
- xhr.setRequestHeader(header, request.headers[header]);
1086
- }
1087
- for (const prop of xhrExtraProps) {
1088
- if (prop in request) xhr[prop] = request[prop];
1089
- }
1090
- xhr.send(request.data);
1091
- }
1092
- });
1093
- }
1094
- }
1095
- function fakeXHR() {
1096
- const xhr = new winAh.realXHR();
1097
- if ("__ajaxHooker" in xhr) console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
1098
- xhr.__ajaxHooker = new XhrHooker(xhr);
1099
- return xhr.__ajaxHooker.proxyXhr;
1100
- }
1101
- fakeXHR.prototype = win.XMLHttpRequest.prototype;
1102
- Object.keys(win.XMLHttpRequest).forEach((key) => (fakeXHR[key] = win.XMLHttpRequest[key]));
1103
- function fakeFetch(url, options = {}) {
1104
- if (!url) return winAh.realFetch.call(win, url, options);
1105
- return new Promise(async (resolve, reject) => {
1106
- const init = {};
1107
- if (getType(url) === "[object Request]") {
1108
- init.method = url.method;
1109
- init.headers = url.headers;
1110
- if (url.body) init.body = await url.arrayBuffer();
1111
- for (const prop of fetchExtraProps) init[prop] = url[prop];
1112
- url = url.url;
1113
- }
1114
- url = url.toString();
1115
- Object.assign(init, options);
1116
- init.method = init.method || "GET";
1117
- init.headers = init.headers || {};
1118
- const request = {
1119
- type: "fetch",
1120
- url: url,
1121
- method: init.method.toUpperCase(),
1122
- abort: false,
1123
- headers: parseHeaders(init.headers),
1124
- data: init.body,
1125
- response: null,
1126
- async: true,
1127
- };
1128
- const req = new AHRequest(request);
1129
- await req.waitForRequestKeys();
1130
- if (request.abort) {
1131
- if (typeof request.response === "function") {
1132
- const response = {
1133
- finalUrl: request.url,
1134
- status: 200,
1135
- responseHeaders: {},
1136
- };
1137
- await req.waitForResponseKeys(response);
1138
- const key = fetchResponses.find((k) => k in response);
1139
- let val = response[key];
1140
- if (key === "json" && typeof val === "object") {
1141
- val = catchError(JSON.stringify.bind(JSON), val);
1142
- }
1143
- const res = new Response(val, {
1144
- status: 200,
1145
- statusText: "OK",
1146
- });
1147
- defineProp(res, "type", () => "basic");
1148
- defineProp(res, "url", () => request.url);
1149
- resolve(res);
1150
- } else {
1151
- reject(new DOMException("aborted", "AbortError"));
1152
- }
1153
- return;
1154
- }
1155
- init.method = request.method;
1156
- init.headers = request.headers;
1157
- init.body = request.data;
1158
- for (const prop of fetchExtraProps) {
1159
- if (prop in request) init[prop] = request[prop];
1160
- }
1161
- winAh.realFetch.call(win, request.url, init).then((res) => {
1162
- if (typeof request.response === "function") {
1163
- const response = {
1164
- finalUrl: res.url,
1165
- status: res.status,
1166
- responseHeaders: parseHeaders(res.headers),
1167
- };
1168
- if (res.ok) {
1169
- fetchResponses.forEach(
1170
- (key) =>
1171
- (res[key] = function () {
1172
- if (key in response) return Promise.resolve(response[key]);
1173
- return resProto[key].call(this).then((val) => {
1174
- response[key] = val;
1175
- return req
1176
- .waitForResponseKeys(response)
1177
- .then(() => (key in response ? response[key] : val));
1178
- });
1179
- })
1180
- );
1181
- } else {
1182
- catchError(request.response, response);
1183
- }
1184
- }
1185
- resolve(res);
1186
- }, reject);
1187
- });
1188
- }
1189
- function fakeFetchClone() {
1190
- const descriptors = Object.getOwnPropertyDescriptors(this);
1191
- const res = winAh.realFetchClone.call(this);
1192
- Object.defineProperties(res, descriptors);
1193
- return res;
1194
- }
1195
- winAh = win.__ajaxHooker = winAh || {
1196
- version,
1197
- fakeXHR,
1198
- fakeFetch,
1199
- fakeFetchClone,
1200
- realXHR: win.XMLHttpRequest,
1201
- realFetch: win.fetch,
1202
- realFetchClone: resProto.clone,
1203
- hookInsts: new Set(),
1204
- };
1205
- if (winAh.version !== version) console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
1206
- win.XMLHttpRequest = winAh.fakeXHR;
1207
- win.fetch = winAh.fakeFetch;
1208
- resProto.clone = winAh.fakeFetchClone;
1209
- winAh.hookInsts.add(hookInst);
1210
- // 针对头条、抖音 secsdk.umd.js 的兼容性处理
1211
- class AHFunction extends Function {
1212
- call(thisArg, ...args) {
1213
- if (thisArg && thisArg.__ajaxHooker && thisArg.__ajaxHooker.proxyXhr === thisArg) {
1214
- thisArg = thisArg.__ajaxHooker.originalXhr;
1215
- }
1216
- return Reflect.apply(this, thisArg, args);
1217
- }
1218
- apply(thisArg, args) {
1219
- if (thisArg && thisArg.__ajaxHooker && thisArg.__ajaxHooker.proxyXhr === thisArg) {
1220
- thisArg = thisArg.__ajaxHooker.originalXhr;
1221
- }
1222
- return Reflect.apply(this, thisArg, args || []);
1223
- }
1224
- }
1225
- function hookSecsdk(csrf) {
1226
- Object.setPrototypeOf(csrf.nativeXMLHttpRequestSetRequestHeader, AHFunction.prototype);
1227
- Object.setPrototypeOf(csrf.nativeXMLHttpRequestOpen, AHFunction.prototype);
1228
- Object.setPrototypeOf(csrf.nativeXMLHttpRequestSend, AHFunction.prototype);
1229
- }
1230
- if (win.secsdk) {
1231
- if (win.secsdk.csrf && win.secsdk.csrf.nativeXMLHttpRequestOpen) hookSecsdk(win.secsdk.csrf);
1232
- } else {
1233
- defineProp(win, "secsdk", emptyFn, (secsdk) => {
1234
- delete win.secsdk;
1235
- win.secsdk = secsdk;
1236
- defineProp(secsdk, "csrf", emptyFn, (csrf) => {
1237
- delete secsdk.csrf;
1238
- secsdk.csrf = csrf;
1239
- if (csrf.nativeXMLHttpRequestOpen) hookSecsdk(csrf);
1240
- });
1241
- });
1242
- }
1243
- return {
1244
- hook: (fn) => hookInst.hookFns.push(fn),
1245
- filter: (arr) => {
1246
- if (Array.isArray(arr)) hookInst.filters = arr;
1247
- },
1248
- protect: () => {
1249
- readonly(win, "XMLHttpRequest", winAh.fakeXHR);
1250
- readonly(win, "fetch", winAh.fakeFetch);
1251
- readonly(resProto, "clone", winAh.fakeFetchClone);
1252
- },
1253
- unhook: () => {
1254
- winAh.hookInsts.delete(hookInst);
1255
- if (!winAh.hookInsts.size) {
1256
- writable(win, "XMLHttpRequest", winAh.realXHR);
1257
- writable(win, "fetch", winAh.realFetch);
1258
- writable(resProto, "clone", winAh.realFetchClone);
1259
- delete win.__ajaxHooker;
1260
- }
1261
- },
1262
- };
723
+ /* eslint-disable */
724
+ // ==UserScript==
725
+ // @name ajaxHooker
726
+ // @author cxxjackie
727
+ // @version 1.4.8
728
+ // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
729
+ // @license GNU LGPL-3.0
730
+ // ==/UserScript==
731
+ const ajaxHooker = function () {
732
+ const version = "1.4.8";
733
+ const hookInst = {
734
+ hookFns: [],
735
+ filters: [],
736
+ };
737
+ const win = window.unsafeWindow || document.defaultView || window;
738
+ let winAh = win.__ajaxHooker;
739
+ const resProto = win.Response.prototype;
740
+ const xhrResponses = ["response", "responseText", "responseXML"];
741
+ const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
742
+ const xhrExtraProps = ["responseType", "timeout", "withCredentials"];
743
+ const fetchExtraProps = [
744
+ "cache",
745
+ "credentials",
746
+ "integrity",
747
+ "keepalive",
748
+ "mode",
749
+ "priority",
750
+ "redirect",
751
+ "referrer",
752
+ "referrerPolicy",
753
+ "signal",
754
+ ];
755
+ const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
756
+ const getType = {}.toString.call.bind({}.toString);
757
+ const getDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
758
+ const emptyFn = () => { };
759
+ const errorFn = (e) => console.error(e);
760
+ function isThenable(obj) {
761
+ return obj && ["object", "function"].includes(typeof obj) && typeof obj.then === "function";
762
+ }
763
+ function catchError(fn, ...args) {
764
+ try {
765
+ const result = fn(...args);
766
+ if (isThenable(result))
767
+ return result.then(null, errorFn);
768
+ return result;
769
+ }
770
+ catch (err) {
771
+ console.error(err);
772
+ }
773
+ }
774
+ function defineProp(obj, prop, getter, setter) {
775
+ Object.defineProperty(obj, prop, {
776
+ configurable: true,
777
+ enumerable: true,
778
+ get: getter,
779
+ set: setter,
780
+ });
781
+ }
782
+ function readonly(obj, prop, value = obj[prop]) {
783
+ defineProp(obj, prop, () => value, emptyFn);
784
+ }
785
+ function writable(obj, prop, value = obj[prop]) {
786
+ Object.defineProperty(obj, prop, {
787
+ configurable: true,
788
+ enumerable: true,
789
+ writable: true,
790
+ value: value,
791
+ });
792
+ }
793
+ function parseHeaders(obj) {
794
+ const headers = {};
795
+ switch (getType(obj)) {
796
+ case "[object String]":
797
+ for (const line of obj.trim().split(/[\r\n]+/)) {
798
+ const [header, value] = line.split(/(?<=^[^:]+)\s*:\s*/);
799
+ if (!value)
800
+ continue;
801
+ const lheader = header.toLowerCase();
802
+ headers[lheader] = lheader in headers ? `${headers[lheader]}, ${value}` : value;
803
+ }
804
+ break;
805
+ case "[object Headers]":
806
+ for (const [key, val] of obj) {
807
+ headers[key] = val;
808
+ }
809
+ break;
810
+ case "[object Object]":
811
+ return { ...obj };
812
+ }
813
+ return headers;
814
+ }
815
+ function stopImmediatePropagation() {
816
+ this.ajaxHooker_isStopped = true;
817
+ }
818
+ class SyncThenable {
819
+ then(fn) {
820
+ fn && fn();
821
+ return new SyncThenable();
822
+ }
823
+ }
824
+ class AHRequest {
825
+ constructor(request) {
826
+ this.request = request;
827
+ this.requestClone = { ...this.request };
828
+ }
829
+ _recoverRequestKey(key) {
830
+ if (key in this.requestClone)
831
+ this.request[key] = this.requestClone[key];
832
+ else
833
+ delete this.request[key];
834
+ }
835
+ shouldFilter(filters) {
836
+ const { type, url, method, async } = this.request;
837
+ return (filters.length &&
838
+ !filters.find((obj) => {
839
+ switch (true) {
840
+ case obj.type && obj.type !== type:
841
+ case getType(obj.url) === "[object String]" && !url.includes(obj.url):
842
+ case getType(obj.url) === "[object RegExp]" && !obj.url.test(url):
843
+ case obj.method && obj.method.toUpperCase() !== method.toUpperCase():
844
+ case "async" in obj && obj.async !== async:
845
+ return false;
846
+ }
847
+ return true;
848
+ }));
849
+ }
850
+ waitForRequestKeys() {
851
+ if (!this.request.async) {
852
+ win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
853
+ if (this.shouldFilter(filters))
854
+ return;
855
+ hookFns.forEach((fn) => {
856
+ if (getType(fn) === "[object Function]")
857
+ catchError(fn, this.request);
858
+ });
859
+ for (const key in this.request) {
860
+ if (isThenable(this.request[key]))
861
+ this._recoverRequestKey(key);
862
+ }
863
+ });
864
+ return new SyncThenable();
865
+ }
866
+ const promises = [];
867
+ const ignoreKeys = new Set(["type", "async", "response"]);
868
+ win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
869
+ if (this.shouldFilter(filters))
870
+ return;
871
+ promises.push(Promise.all(hookFns.map((fn) => catchError(fn, this.request))).then(() => {
872
+ const requestKeys = [];
873
+ for (const key in this.request)
874
+ !ignoreKeys.has(key) && requestKeys.push(key);
875
+ return Promise.all(requestKeys.map((key) => Promise.resolve(this.request[key]).then((val) => (this.request[key] = val), () => this._recoverRequestKey(key))));
876
+ }));
877
+ });
878
+ return Promise.all(promises);
879
+ }
880
+ waitForResponseKeys(response) {
881
+ const responseKeys = this.request.type === "xhr" ? xhrResponses : fetchResponses;
882
+ if (!this.request.async) {
883
+ if (getType(this.request.response) === "[object Function]") {
884
+ catchError(this.request.response, response);
885
+ responseKeys.forEach((key) => {
886
+ if ("get" in getDescriptor(response, key) || isThenable(response[key])) {
887
+ delete response[key];
888
+ }
889
+ });
890
+ }
891
+ return new SyncThenable();
892
+ }
893
+ return Promise.resolve(catchError(this.request.response, response)).then(() => Promise.all(responseKeys.map((key) => {
894
+ const descriptor = getDescriptor(response, key);
895
+ if (descriptor && "value" in descriptor) {
896
+ return Promise.resolve(descriptor.value).then((val) => (response[key] = val), () => delete response[key]);
897
+ }
898
+ else {
899
+ delete response[key];
900
+ }
901
+ })));
902
+ }
903
+ }
904
+ const proxyHandler = {
905
+ get(target, prop) {
906
+ const descriptor = getDescriptor(target, prop);
907
+ if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.get)
908
+ return target[prop];
909
+ const ah = target.__ajaxHooker;
910
+ if (ah && ah.proxyProps) {
911
+ if (prop in ah.proxyProps) {
912
+ const pDescriptor = ah.proxyProps[prop];
913
+ if ("get" in pDescriptor)
914
+ return pDescriptor.get();
915
+ if (typeof pDescriptor.value === "function")
916
+ return pDescriptor.value.bind(ah);
917
+ return pDescriptor.value;
918
+ }
919
+ if (typeof target[prop] === "function")
920
+ return target[prop].bind(target);
921
+ }
922
+ return target[prop];
923
+ },
924
+ set(target, prop, value) {
925
+ const descriptor = getDescriptor(target, prop);
926
+ if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.set)
927
+ return true;
928
+ const ah = target.__ajaxHooker;
929
+ if (ah && ah.proxyProps && prop in ah.proxyProps) {
930
+ const pDescriptor = ah.proxyProps[prop];
931
+ pDescriptor.set ? pDescriptor.set(value) : (pDescriptor.value = value);
932
+ }
933
+ else {
934
+ target[prop] = value;
935
+ }
936
+ return true;
937
+ },
938
+ };
939
+ class XhrHooker {
940
+ constructor(xhr) {
941
+ const ah = this;
942
+ Object.assign(ah, {
943
+ originalXhr: xhr,
944
+ proxyXhr: new Proxy(xhr, proxyHandler),
945
+ resThenable: new SyncThenable(),
946
+ proxyProps: {},
947
+ proxyEvents: {},
948
+ });
949
+ xhr.addEventListener("readystatechange", (e) => {
950
+ if (ah.proxyXhr.readyState === 4 && ah.request && typeof ah.request.response === "function") {
951
+ const response = {
952
+ finalUrl: ah.proxyXhr.responseURL,
953
+ status: ah.proxyXhr.status,
954
+ responseHeaders: parseHeaders(ah.proxyXhr.getAllResponseHeaders()),
955
+ };
956
+ const tempValues = {};
957
+ for (const key of xhrResponses) {
958
+ try {
959
+ tempValues[key] = ah.originalXhr[key];
960
+ }
961
+ catch (err) { }
962
+ defineProp(response, key, () => {
963
+ return (response[key] = tempValues[key]);
964
+ }, (val) => {
965
+ delete response[key];
966
+ response[key] = val;
967
+ });
968
+ }
969
+ ah.resThenable = new AHRequest(ah.request).waitForResponseKeys(response).then(() => {
970
+ for (const key of xhrResponses) {
971
+ ah.proxyProps[key] = {
972
+ get: () => {
973
+ if (!(key in response))
974
+ response[key] = tempValues[key];
975
+ return response[key];
976
+ },
977
+ };
978
+ }
979
+ });
980
+ }
981
+ ah.dispatchEvent(e);
982
+ });
983
+ xhr.addEventListener("load", (e) => ah.dispatchEvent(e));
984
+ xhr.addEventListener("loadend", (e) => ah.dispatchEvent(e));
985
+ for (const evt of xhrAsyncEvents) {
986
+ const onEvt = "on" + evt;
987
+ ah.proxyProps[onEvt] = {
988
+ get: () => ah.proxyEvents[onEvt] || null,
989
+ set: (val) => ah.addEvent(onEvt, val),
990
+ };
991
+ }
992
+ for (const method of ["setRequestHeader", "addEventListener", "removeEventListener", "open", "send"]) {
993
+ ah.proxyProps[method] = { value: ah[method] };
994
+ }
995
+ }
996
+ toJSON() { } // Converting circular structure to JSON
997
+ addEvent(type, event) {
998
+ if (type.startsWith("on")) {
999
+ this.proxyEvents[type] = typeof event === "function" ? event : null;
1000
+ }
1001
+ else {
1002
+ if (typeof event === "object" && event !== null)
1003
+ event = event.handleEvent;
1004
+ if (typeof event !== "function")
1005
+ return;
1006
+ this.proxyEvents[type] = this.proxyEvents[type] || new Set();
1007
+ this.proxyEvents[type].add(event);
1008
+ }
1009
+ }
1010
+ removeEvent(type, event) {
1011
+ if (type.startsWith("on")) {
1012
+ this.proxyEvents[type] = null;
1013
+ }
1014
+ else {
1015
+ if (typeof event === "object" && event !== null)
1016
+ event = event.handleEvent;
1017
+ this.proxyEvents[type] && this.proxyEvents[type].delete(event);
1018
+ }
1019
+ }
1020
+ dispatchEvent(e) {
1021
+ e.stopImmediatePropagation = stopImmediatePropagation;
1022
+ defineProp(e, "target", () => this.proxyXhr);
1023
+ defineProp(e, "currentTarget", () => this.proxyXhr);
1024
+ defineProp(e, "srcElement", () => this.proxyXhr);
1025
+ this.proxyEvents[e.type] &&
1026
+ this.proxyEvents[e.type].forEach((fn) => {
1027
+ this.resThenable.then(() => !e.ajaxHooker_isStopped && fn.call(this.proxyXhr, e));
1028
+ });
1029
+ if (e.ajaxHooker_isStopped)
1030
+ return;
1031
+ const onEvent = this.proxyEvents["on" + e.type];
1032
+ onEvent && this.resThenable.then(onEvent.bind(this.proxyXhr, e));
1033
+ }
1034
+ setRequestHeader(header, value) {
1035
+ this.originalXhr.setRequestHeader(header, value);
1036
+ if (!this.request)
1037
+ return;
1038
+ const headers = this.request.headers;
1039
+ headers[header] = header in headers ? `${headers[header]}, ${value}` : value;
1040
+ }
1041
+ addEventListener(...args) {
1042
+ if (xhrAsyncEvents.includes(args[0])) {
1043
+ this.addEvent(args[0], args[1]);
1044
+ }
1045
+ else {
1046
+ this.originalXhr.addEventListener(...args);
1047
+ }
1048
+ }
1049
+ removeEventListener(...args) {
1050
+ if (xhrAsyncEvents.includes(args[0])) {
1051
+ this.removeEvent(args[0], args[1]);
1052
+ }
1053
+ else {
1054
+ this.originalXhr.removeEventListener(...args);
1055
+ }
1056
+ }
1057
+ open(method, url, async = true, ...args) {
1058
+ this.request = {
1059
+ type: "xhr",
1060
+ url: url.toString(),
1061
+ method: method.toUpperCase(),
1062
+ abort: false,
1063
+ headers: {},
1064
+ data: null,
1065
+ response: null,
1066
+ async: !!async,
1067
+ };
1068
+ this.openArgs = args;
1069
+ this.resThenable = new SyncThenable();
1070
+ ["responseURL", "readyState", "status", "statusText", ...xhrResponses].forEach((key) => {
1071
+ delete this.proxyProps[key];
1072
+ });
1073
+ return this.originalXhr.open(method, url, async, ...args);
1074
+ }
1075
+ send(data) {
1076
+ const ah = this;
1077
+ const xhr = ah.originalXhr;
1078
+ const request = ah.request;
1079
+ if (!request)
1080
+ return xhr.send(data);
1081
+ request.data = data;
1082
+ new AHRequest(request).waitForRequestKeys().then(() => {
1083
+ if (request.abort) {
1084
+ if (typeof request.response === "function") {
1085
+ Object.assign(ah.proxyProps, {
1086
+ responseURL: { value: request.url },
1087
+ readyState: { value: 4 },
1088
+ status: { value: 200 },
1089
+ statusText: { value: "OK" },
1090
+ });
1091
+ xhrAsyncEvents.forEach((evt) => xhr.dispatchEvent(new Event(evt)));
1092
+ }
1093
+ }
1094
+ else {
1095
+ xhr.open(request.method, request.url, request.async, ...ah.openArgs);
1096
+ for (const header in request.headers) {
1097
+ xhr.setRequestHeader(header, request.headers[header]);
1098
+ }
1099
+ for (const prop of xhrExtraProps) {
1100
+ if (prop in request)
1101
+ xhr[prop] = request[prop];
1102
+ }
1103
+ xhr.send(request.data);
1104
+ }
1105
+ });
1106
+ }
1107
+ }
1108
+ function fakeXHR() {
1109
+ const xhr = new winAh.realXHR();
1110
+ if ("__ajaxHooker" in xhr)
1111
+ console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
1112
+ xhr.__ajaxHooker = new XhrHooker(xhr);
1113
+ return xhr.__ajaxHooker.proxyXhr;
1114
+ }
1115
+ fakeXHR.prototype = win.XMLHttpRequest.prototype;
1116
+ Object.keys(win.XMLHttpRequest).forEach((key) => (fakeXHR[key] = win.XMLHttpRequest[key]));
1117
+ function fakeFetch(url, options = {}) {
1118
+ if (!url)
1119
+ return winAh.realFetch.call(win, url, options);
1120
+ return new Promise(async (resolve, reject) => {
1121
+ const init = {};
1122
+ if (getType(url) === "[object Request]") {
1123
+ init.method = url.method;
1124
+ init.headers = url.headers;
1125
+ if (url.body)
1126
+ init.body = await url.arrayBuffer();
1127
+ for (const prop of fetchExtraProps)
1128
+ init[prop] = url[prop];
1129
+ url = url.url;
1130
+ }
1131
+ url = url.toString();
1132
+ Object.assign(init, options);
1133
+ init.method = init.method || "GET";
1134
+ init.headers = init.headers || {};
1135
+ const request = {
1136
+ type: "fetch",
1137
+ url: url,
1138
+ method: init.method.toUpperCase(),
1139
+ abort: false,
1140
+ headers: parseHeaders(init.headers),
1141
+ data: init.body,
1142
+ response: null,
1143
+ async: true,
1144
+ };
1145
+ const req = new AHRequest(request);
1146
+ await req.waitForRequestKeys();
1147
+ if (request.abort) {
1148
+ if (typeof request.response === "function") {
1149
+ const response = {
1150
+ finalUrl: request.url,
1151
+ status: 200,
1152
+ responseHeaders: {},
1153
+ };
1154
+ await req.waitForResponseKeys(response);
1155
+ const key = fetchResponses.find((k) => k in response);
1156
+ let val = response[key];
1157
+ if (key === "json" && typeof val === "object") {
1158
+ val = catchError(JSON.stringify.bind(JSON), val);
1159
+ }
1160
+ const res = new Response(val, {
1161
+ status: 200,
1162
+ statusText: "OK",
1163
+ });
1164
+ defineProp(res, "type", () => "basic");
1165
+ defineProp(res, "url", () => request.url);
1166
+ resolve(res);
1167
+ }
1168
+ else {
1169
+ reject(new DOMException("aborted", "AbortError"));
1170
+ }
1171
+ return;
1172
+ }
1173
+ init.method = request.method;
1174
+ init.headers = request.headers;
1175
+ init.body = request.data;
1176
+ for (const prop of fetchExtraProps) {
1177
+ if (prop in request)
1178
+ init[prop] = request[prop];
1179
+ }
1180
+ winAh.realFetch.call(win, request.url, init).then((res) => {
1181
+ if (typeof request.response === "function") {
1182
+ const response = {
1183
+ finalUrl: res.url,
1184
+ status: res.status,
1185
+ responseHeaders: parseHeaders(res.headers),
1186
+ };
1187
+ if (res.ok) {
1188
+ fetchResponses.forEach((key) => (res[key] = function () {
1189
+ if (key in response)
1190
+ return Promise.resolve(response[key]);
1191
+ return resProto[key].call(this).then((val) => {
1192
+ response[key] = val;
1193
+ return req
1194
+ .waitForResponseKeys(response)
1195
+ .then(() => (key in response ? response[key] : val));
1196
+ });
1197
+ }));
1198
+ }
1199
+ else {
1200
+ catchError(request.response, response);
1201
+ }
1202
+ }
1203
+ resolve(res);
1204
+ }, reject);
1205
+ });
1206
+ }
1207
+ function fakeFetchClone() {
1208
+ const descriptors = Object.getOwnPropertyDescriptors(this);
1209
+ const res = winAh.realFetchClone.call(this);
1210
+ Object.defineProperties(res, descriptors);
1211
+ return res;
1212
+ }
1213
+ winAh = win.__ajaxHooker = winAh || {
1214
+ version,
1215
+ fakeXHR,
1216
+ fakeFetch,
1217
+ fakeFetchClone,
1218
+ realXHR: win.XMLHttpRequest,
1219
+ realFetch: win.fetch,
1220
+ realFetchClone: resProto.clone,
1221
+ hookInsts: new Set(),
1222
+ };
1223
+ if (winAh.version !== version)
1224
+ console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
1225
+ win.XMLHttpRequest = winAh.fakeXHR;
1226
+ win.fetch = winAh.fakeFetch;
1227
+ resProto.clone = winAh.fakeFetchClone;
1228
+ winAh.hookInsts.add(hookInst);
1229
+ // 针对头条、抖音 secsdk.umd.js 的兼容性处理
1230
+ class AHFunction extends Function {
1231
+ call(thisArg, ...args) {
1232
+ if (thisArg && thisArg.__ajaxHooker && thisArg.__ajaxHooker.proxyXhr === thisArg) {
1233
+ thisArg = thisArg.__ajaxHooker.originalXhr;
1234
+ }
1235
+ return Reflect.apply(this, thisArg, args);
1236
+ }
1237
+ apply(thisArg, args) {
1238
+ if (thisArg && thisArg.__ajaxHooker && thisArg.__ajaxHooker.proxyXhr === thisArg) {
1239
+ thisArg = thisArg.__ajaxHooker.originalXhr;
1240
+ }
1241
+ return Reflect.apply(this, thisArg, args || []);
1242
+ }
1243
+ }
1244
+ function hookSecsdk(csrf) {
1245
+ Object.setPrototypeOf(csrf.nativeXMLHttpRequestSetRequestHeader, AHFunction.prototype);
1246
+ Object.setPrototypeOf(csrf.nativeXMLHttpRequestOpen, AHFunction.prototype);
1247
+ Object.setPrototypeOf(csrf.nativeXMLHttpRequestSend, AHFunction.prototype);
1248
+ }
1249
+ if (win.secsdk) {
1250
+ if (win.secsdk.csrf && win.secsdk.csrf.nativeXMLHttpRequestOpen)
1251
+ hookSecsdk(win.secsdk.csrf);
1252
+ }
1253
+ else {
1254
+ defineProp(win, "secsdk", emptyFn, (secsdk) => {
1255
+ delete win.secsdk;
1256
+ win.secsdk = secsdk;
1257
+ defineProp(secsdk, "csrf", emptyFn, (csrf) => {
1258
+ delete secsdk.csrf;
1259
+ secsdk.csrf = csrf;
1260
+ if (csrf.nativeXMLHttpRequestOpen)
1261
+ hookSecsdk(csrf);
1262
+ });
1263
+ });
1264
+ }
1265
+ return {
1266
+ hook: (fn) => hookInst.hookFns.push(fn),
1267
+ filter: (arr) => {
1268
+ if (Array.isArray(arr))
1269
+ hookInst.filters = arr;
1270
+ },
1271
+ protect: () => {
1272
+ readonly(win, "XMLHttpRequest", winAh.fakeXHR);
1273
+ readonly(win, "fetch", winAh.fakeFetch);
1274
+ readonly(resProto, "clone", winAh.fakeFetchClone);
1275
+ },
1276
+ unhook: () => {
1277
+ winAh.hookInsts.delete(hookInst);
1278
+ if (!winAh.hookInsts.size) {
1279
+ writable(win, "XMLHttpRequest", winAh.realXHR);
1280
+ writable(win, "fetch", winAh.realFetch);
1281
+ writable(resProto, "clone", winAh.realFetchClone);
1282
+ delete win.__ajaxHooker;
1283
+ }
1284
+ },
1285
+ };
1263
1286
  };
1264
1287
 
1265
- // ==UserScript==
1266
- // @name ajaxHooker
1267
- // @author cxxjackie
1268
- // @version 1.2.4
1269
- // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
1270
- // ==/UserScript==
1271
-
1272
- const AjaxHooker1_2_4 = function () {
1273
- return (function () {
1274
- const win = window.unsafeWindow || document.defaultView || window;
1275
- const hookFns = [];
1276
- const realXhr = win.XMLHttpRequest;
1277
- const resProto = win.Response.prototype;
1278
- const toString = Object.prototype.toString;
1279
- const realFetch = win.fetch;
1280
- const xhrResponses = ["response", "responseText", "responseXML"];
1281
- const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
1282
- const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
1283
- let filter;
1284
- function emptyFn() {}
1285
- function errorFn(err) {
1286
- console.error(err);
1287
- }
1288
- function defineProp(obj, prop, getter, setter) {
1289
- Object.defineProperty(obj, prop, {
1290
- configurable: true,
1291
- enumerable: true,
1292
- get: getter,
1293
- set: setter,
1294
- });
1295
- }
1296
- function readonly(obj, prop, value = obj[prop]) {
1297
- defineProp(obj, prop, () => value, emptyFn);
1298
- }
1299
- function writable(obj, prop, value = obj[prop]) {
1300
- Object.defineProperty(obj, prop, {
1301
- configurable: true,
1302
- enumerable: true,
1303
- writable: true,
1304
- value: value,
1305
- });
1306
- }
1307
- function toFilterObj(obj) {
1308
- return {
1309
- type: obj.type,
1310
- url: obj.url,
1311
- method: obj.method && obj.method.toUpperCase(),
1312
- };
1313
- }
1314
- function shouldFilter(type, url, method) {
1315
- return (
1316
- filter &&
1317
- !filter.find(
1318
- (obj) =>
1319
- (!obj.type || obj.type === type) &&
1320
- (!obj.url ||
1321
- (toString.call(obj.url) === "[object String]"
1322
- ? url.includes(obj.url)
1323
- : obj.url.test(url))) &&
1324
- (!obj.method || obj.method === method.toUpperCase())
1325
- )
1326
- );
1327
- }
1328
- function lookupGetter(obj, prop) {
1329
- let getter;
1330
- let proto = obj;
1331
- while (proto) {
1332
- const descriptor = Object.getOwnPropertyDescriptor(proto, prop);
1333
- getter = descriptor && descriptor.get;
1334
- if (getter) break;
1335
- proto = Object.getPrototypeOf(proto);
1336
- }
1337
- return getter ? getter.bind(obj) : emptyFn;
1338
- }
1339
- function waitForHookFns(request) {
1340
- return Promise.all(
1341
- hookFns.map((fn) => Promise.resolve(fn(request)).then(emptyFn, errorFn))
1342
- );
1343
- }
1344
- function waitForRequestKeys(request, requestClone) {
1345
- return Promise.all(
1346
- ["url", "method", "abort", "headers", "data"].map((key) => {
1347
- return Promise.resolve(request[key]).then(
1348
- (val) => (request[key] = val),
1349
- () => (request[key] = requestClone[key])
1350
- );
1351
- })
1352
- );
1353
- }
1354
- function fakeEventSIP() {
1355
- this.ajaxHooker_stopped = true;
1356
- }
1357
- function xhrDelegateEvent(e) {
1358
- const xhr = e.target;
1359
- e.stopImmediatePropagation = fakeEventSIP;
1360
- xhr.__ajaxHooker.hookedEvents[e.type].forEach(
1361
- (fn) => !e.ajaxHooker_stopped && fn.call(xhr, e)
1362
- );
1363
- const onEvent = xhr.__ajaxHooker.hookedEvents["on" + e.type];
1364
- typeof onEvent === "function" && onEvent.call(xhr, e);
1365
- }
1366
- function xhrReadyStateChange(e) {
1367
- if (e.target.readyState === 4) {
1368
- e.target.dispatchEvent(
1369
- new CustomEvent("ajaxHooker_responseReady", { detail: e })
1370
- );
1371
- } else {
1372
- e.target.__ajaxHooker.delegateEvent(e);
1373
- }
1374
- }
1375
- function xhrLoadAndLoadend(e) {
1376
- e.target.__ajaxHooker.delegateEvent(e);
1377
- }
1378
- function fakeXhrOpen(method, url, ...args) {
1379
- const ah = this.__ajaxHooker;
1380
- ah.url = url.toString();
1381
- ah.method = method.toUpperCase();
1382
- ah.openArgs = args;
1383
- ah.headers = {};
1384
- return ah.originalMethods.open(method, url, ...args);
1385
- }
1386
- function fakeXhr() {
1387
- const xhr = new realXhr();
1388
- let ah = xhr.__ajaxHooker;
1389
- if (!ah) {
1390
- ah = xhr.__ajaxHooker = {
1391
- headers: {},
1392
- hookedEvents: {
1393
- readystatechange: new Set(),
1394
- load: new Set(),
1395
- loadend: new Set(),
1396
- },
1397
- delegateEvent: xhrDelegateEvent,
1398
- originalGetters: {},
1399
- originalMethods: {},
1400
- };
1401
- xhr.addEventListener("readystatechange", xhrReadyStateChange);
1402
- xhr.addEventListener("load", xhrLoadAndLoadend);
1403
- xhr.addEventListener("loadend", xhrLoadAndLoadend);
1404
- for (const key of xhrResponses) {
1405
- ah.originalGetters[key] = lookupGetter(xhr, key);
1406
- }
1407
- for (const method of [
1408
- "open",
1409
- "setRequestHeader",
1410
- "addEventListener",
1411
- "removeEventListener",
1412
- ]) {
1413
- ah.originalMethods[method] = xhr[method].bind(xhr);
1414
- }
1415
- xhr.open = fakeXhrOpen;
1416
- xhr.setRequestHeader = (header, value) => {
1417
- ah.originalMethods.setRequestHeader(header, value);
1418
- if (xhr.readyState === 1) {
1419
- if (ah.headers[header]) {
1420
- ah.headers[header] += ", " + value;
1421
- } else {
1422
- ah.headers[header] = value;
1423
- }
1424
- }
1425
- };
1426
- xhr.addEventListener = function (...args) {
1427
- if (xhrAsyncEvents.includes(args[0])) {
1428
- ah.hookedEvents[args[0]].add(args[1]);
1429
- } else {
1430
- ah.originalMethods.addEventListener(...args);
1431
- }
1432
- };
1433
- xhr.removeEventListener = function (...args) {
1434
- if (xhrAsyncEvents.includes(args[0])) {
1435
- ah.hookedEvents[args[0]].delete(args[1]);
1436
- } else {
1437
- ah.originalMethods.removeEventListener(...args);
1438
- }
1439
- };
1440
- xhrAsyncEvents.forEach((evt) => {
1441
- const onEvt = "on" + evt;
1442
- defineProp(
1443
- xhr,
1444
- onEvt,
1445
- () => {
1446
- return ah.hookedEvents[onEvt] || null;
1447
- },
1448
- (val) => {
1449
- ah.hookedEvents[onEvt] = typeof val === "function" ? val : null;
1450
- }
1451
- );
1452
- });
1453
- }
1454
- const realSend = xhr.send.bind(xhr);
1455
- xhr.send = function (data) {
1456
- if (xhr.readyState !== 1) return realSend(data);
1457
- ah.delegateEvent = xhrDelegateEvent;
1458
- xhrResponses.forEach((prop) => {
1459
- delete xhr[prop]; // delete descriptor
1460
- });
1461
- if (shouldFilter("xhr", ah.url, ah.method)) {
1462
- xhr.addEventListener("ajaxHooker_responseReady", (e) => {
1463
- ah.delegateEvent(e.detail);
1464
- });
1465
- return realSend(data);
1466
- }
1467
- try {
1468
- const request = {
1469
- type: "xhr",
1470
- url: ah.url,
1471
- method: ah.method,
1472
- abort: false,
1473
- headers: ah.headers,
1474
- data: data,
1475
- response: null,
1476
- };
1477
- const requestClone = { ...request };
1478
- waitForHookFns(request).then(() => {
1479
- waitForRequestKeys(request, requestClone).then(() => {
1480
- if (request.abort) return;
1481
- ah.originalMethods.open(
1482
- request.method,
1483
- request.url,
1484
- ...ah.openArgs
1485
- );
1486
- for (const header in request.headers) {
1487
- ah.originalMethods.setRequestHeader(
1488
- header,
1489
- request.headers[header]
1490
- );
1491
- }
1492
- data = request.data;
1493
- xhr.addEventListener("ajaxHooker_responseReady", (e) => {
1494
- try {
1495
- if (typeof request.response === "function") {
1496
- const arg = {
1497
- finalUrl: xhr.responseURL,
1498
- status: xhr.status,
1499
- responseHeaders: {},
1500
- };
1501
- for (const line of xhr
1502
- .getAllResponseHeaders()
1503
- .trim()
1504
- .split(/[\r\n]+/)) {
1505
- const parts = line.split(/:\s*/);
1506
- if (parts.length === 2) {
1507
- const lheader = parts[0].toLowerCase();
1508
- if (arg.responseHeaders[lheader]) {
1509
- arg.responseHeaders[lheader] += ", " + parts[1];
1510
- } else {
1511
- arg.responseHeaders[lheader] = parts[1];
1512
- }
1513
- }
1514
- }
1515
- xhrResponses.forEach((prop) => {
1516
- defineProp(
1517
- arg,
1518
- prop,
1519
- () => {
1520
- return (arg[prop] = ah.originalGetters[prop]());
1521
- },
1522
- (val) => {
1523
- delete arg[prop];
1524
- arg[prop] = val;
1525
- }
1526
- );
1527
- defineProp(xhr, prop, () => {
1528
- const val = ah.originalGetters[prop]();
1529
- xhr.dispatchEvent(
1530
- new CustomEvent("ajaxHooker_readResponse", {
1531
- detail: { prop, val },
1532
- })
1533
- );
1534
- return val;
1535
- });
1536
- });
1537
- xhr.addEventListener("ajaxHooker_readResponse", (e) => {
1538
- arg[e.detail.prop] = e.detail.val;
1539
- });
1540
- const resPromise = Promise.resolve(
1541
- request.response(arg)
1542
- ).then(() => {
1543
- const task = [];
1544
- xhrResponses.forEach((prop) => {
1545
- const descriptor = Object.getOwnPropertyDescriptor(
1546
- arg,
1547
- prop
1548
- );
1549
- if (descriptor && "value" in descriptor) {
1550
- task.push(
1551
- Promise.resolve(descriptor.value).then((val) => {
1552
- arg[prop] = val;
1553
- defineProp(xhr, prop, () => {
1554
- xhr.dispatchEvent(
1555
- new CustomEvent("ajaxHooker_readResponse", {
1556
- detail: { prop, val },
1557
- })
1558
- );
1559
- return val;
1560
- });
1561
- }, emptyFn)
1562
- );
1563
- }
1564
- });
1565
- return Promise.all(task);
1566
- }, errorFn);
1567
- const eventsClone = {};
1568
- xhrAsyncEvents.forEach((type) => {
1569
- eventsClone[type] = new Set([...ah.hookedEvents[type]]);
1570
- eventsClone["on" + type] = ah.hookedEvents["on" + type];
1571
- });
1572
- ah.delegateEvent = (event) =>
1573
- resPromise.then(() => {
1574
- event.stopImmediatePropagation = fakeEventSIP;
1575
- eventsClone[event.type].forEach(
1576
- (fn) =>
1577
- !event.ajaxHooker_stopped && fn.call(xhr, event)
1578
- );
1579
- const onEvent = eventsClone["on" + event.type];
1580
- typeof onEvent === "function" &&
1581
- onEvent.call(xhr, event);
1582
- });
1583
- }
1584
- } catch (err) {
1585
- console.error(err);
1586
- }
1587
- ah.delegateEvent(e.detail);
1588
- });
1589
- realSend(data);
1590
- });
1591
- });
1592
- } catch (err) {
1593
- console.error(err);
1594
- realSend(data);
1595
- }
1596
- };
1597
- return xhr;
1598
- }
1599
- function hookFetchResponse(response, arg, callback) {
1600
- fetchResponses.forEach((prop) => {
1601
- response[prop] = () =>
1602
- new Promise((resolve, reject) => {
1603
- resProto[prop].call(response).then((res) => {
1604
- if (prop in arg) {
1605
- resolve(arg[prop]);
1606
- } else {
1607
- try {
1608
- arg[prop] = res;
1609
- Promise.resolve(callback(arg)).then(() => {
1610
- if (prop in arg) {
1611
- Promise.resolve(arg[prop]).then(
1612
- (val) => resolve((arg[prop] = val)),
1613
- () => resolve(res)
1614
- );
1615
- } else {
1616
- resolve(res);
1617
- }
1618
- }, errorFn);
1619
- } catch (err) {
1620
- console.error(err);
1621
- resolve(res);
1622
- }
1623
- }
1624
- }, reject);
1625
- });
1626
- });
1627
- }
1628
- function fakeFetch(url, init) {
1629
- if (url && typeof url.toString === "function") {
1630
- url = url.toString();
1631
- init = init || {};
1632
- init.method = init.method || "GET";
1633
- init.headers = init.headers || {};
1634
- if (shouldFilter("fetch", url, init.method))
1635
- return realFetch.call(win, url, init);
1636
- const request = {
1637
- type: "fetch",
1638
- url: url,
1639
- method: init.method.toUpperCase(),
1640
- abort: false,
1641
- headers: {},
1642
- data: init.body,
1643
- response: null,
1644
- };
1645
- if (toString.call(init.headers) === "[object Headers]") {
1646
- for (const [key, val] of init.headers) {
1647
- request.headers[key] = val;
1648
- }
1649
- } else {
1650
- request.headers = { ...init.headers };
1651
- }
1652
- const requestClone = { ...request };
1653
- return new Promise((resolve, reject) => {
1654
- try {
1655
- waitForHookFns(request).then(() => {
1656
- waitForRequestKeys(request, requestClone).then(() => {
1657
- if (request.abort) return reject("aborted");
1658
- url = request.url;
1659
- init.method = request.method;
1660
- init.headers = request.headers;
1661
- init.body = request.data;
1662
- realFetch.call(win, url, init).then((response) => {
1663
- if (typeof request.response === "function") {
1664
- const arg = {
1665
- finalUrl: response.url,
1666
- status: response.status,
1667
- responseHeaders: {},
1668
- };
1669
- for (const [key, val] of response.headers) {
1670
- arg.responseHeaders[key] = val;
1671
- }
1672
- hookFetchResponse(response, arg, request.response);
1673
- response.clone = () => {
1674
- const resClone = resProto.clone.call(response);
1675
- hookFetchResponse(resClone, arg, request.response);
1676
- return resClone;
1677
- };
1678
- }
1679
- resolve(response);
1680
- }, reject);
1681
- });
1682
- });
1683
- } catch (err) {
1684
- console.error(err);
1685
- return realFetch.call(win, url, init);
1686
- }
1687
- });
1688
- } else {
1689
- return realFetch.call(win, url, init);
1690
- }
1691
- }
1692
- win.XMLHttpRequest = fakeXhr;
1693
- Object.keys(realXhr).forEach((key) => (fakeXhr[key] = realXhr[key]));
1694
- fakeXhr.prototype = realXhr.prototype;
1695
- win.fetch = fakeFetch;
1696
- return {
1697
- hook: (fn) => hookFns.push(fn),
1698
- filter: (arr) => {
1699
- filter = Array.isArray(arr) && arr.map(toFilterObj);
1700
- },
1701
- protect: () => {
1702
- readonly(win, "XMLHttpRequest", fakeXhr);
1703
- readonly(win, "fetch", fakeFetch);
1704
- },
1705
- unhook: () => {
1706
- writable(win, "XMLHttpRequest", realXhr);
1707
- writable(win, "fetch", realFetch);
1708
- },
1709
- };
1710
- })();
1288
+ // ==UserScript==
1289
+ // @name ajaxHooker
1290
+ // @author cxxjackie
1291
+ // @version 1.2.4
1292
+ // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
1293
+ // ==/UserScript==
1294
+ const AjaxHooker1_2_4 = function () {
1295
+ return (function () {
1296
+ const win = window.unsafeWindow || document.defaultView || window;
1297
+ const hookFns = [];
1298
+ const realXhr = win.XMLHttpRequest;
1299
+ const resProto = win.Response.prototype;
1300
+ const toString = Object.prototype.toString;
1301
+ const realFetch = win.fetch;
1302
+ const xhrResponses = ["response", "responseText", "responseXML"];
1303
+ const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
1304
+ const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
1305
+ let filter;
1306
+ function emptyFn() { }
1307
+ function errorFn(err) {
1308
+ console.error(err);
1309
+ }
1310
+ function defineProp(obj, prop, getter, setter) {
1311
+ Object.defineProperty(obj, prop, {
1312
+ configurable: true,
1313
+ enumerable: true,
1314
+ get: getter,
1315
+ set: setter,
1316
+ });
1317
+ }
1318
+ function readonly(obj, prop, value = obj[prop]) {
1319
+ defineProp(obj, prop, () => value, emptyFn);
1320
+ }
1321
+ function writable(obj, prop, value = obj[prop]) {
1322
+ Object.defineProperty(obj, prop, {
1323
+ configurable: true,
1324
+ enumerable: true,
1325
+ writable: true,
1326
+ value: value,
1327
+ });
1328
+ }
1329
+ function toFilterObj(obj) {
1330
+ return {
1331
+ type: obj.type,
1332
+ url: obj.url,
1333
+ method: obj.method && obj.method.toUpperCase(),
1334
+ };
1335
+ }
1336
+ function shouldFilter(type, url, method) {
1337
+ return (filter &&
1338
+ !filter.find((obj) => (!obj.type || obj.type === type) &&
1339
+ (!obj.url ||
1340
+ (toString.call(obj.url) === "[object String]"
1341
+ ? url.includes(obj.url)
1342
+ : obj.url.test(url))) &&
1343
+ (!obj.method || obj.method === method.toUpperCase())));
1344
+ }
1345
+ function lookupGetter(obj, prop) {
1346
+ let getter;
1347
+ let proto = obj;
1348
+ while (proto) {
1349
+ const descriptor = Object.getOwnPropertyDescriptor(proto, prop);
1350
+ getter = descriptor && descriptor.get;
1351
+ if (getter)
1352
+ break;
1353
+ proto = Object.getPrototypeOf(proto);
1354
+ }
1355
+ return getter ? getter.bind(obj) : emptyFn;
1356
+ }
1357
+ function waitForHookFns(request) {
1358
+ return Promise.all(hookFns.map((fn) => Promise.resolve(fn(request)).then(emptyFn, errorFn)));
1359
+ }
1360
+ function waitForRequestKeys(request, requestClone) {
1361
+ return Promise.all(["url", "method", "abort", "headers", "data"].map((key) => {
1362
+ return Promise.resolve(request[key]).then((val) => (request[key] = val), () => (request[key] = requestClone[key]));
1363
+ }));
1364
+ }
1365
+ function fakeEventSIP() {
1366
+ this.ajaxHooker_stopped = true;
1367
+ }
1368
+ function xhrDelegateEvent(e) {
1369
+ const xhr = e.target;
1370
+ e.stopImmediatePropagation = fakeEventSIP;
1371
+ xhr.__ajaxHooker.hookedEvents[e.type].forEach((fn) => !e.ajaxHooker_stopped && fn.call(xhr, e));
1372
+ const onEvent = xhr.__ajaxHooker.hookedEvents["on" + e.type];
1373
+ typeof onEvent === "function" && onEvent.call(xhr, e);
1374
+ }
1375
+ function xhrReadyStateChange(e) {
1376
+ if (e.target.readyState === 4) {
1377
+ e.target.dispatchEvent(new CustomEvent("ajaxHooker_responseReady", { detail: e }));
1378
+ }
1379
+ else {
1380
+ e.target.__ajaxHooker.delegateEvent(e);
1381
+ }
1382
+ }
1383
+ function xhrLoadAndLoadend(e) {
1384
+ e.target.__ajaxHooker.delegateEvent(e);
1385
+ }
1386
+ function fakeXhrOpen(method, url, ...args) {
1387
+ const ah = this.__ajaxHooker;
1388
+ ah.url = url.toString();
1389
+ ah.method = method.toUpperCase();
1390
+ ah.openArgs = args;
1391
+ ah.headers = {};
1392
+ return ah.originalMethods.open(method, url, ...args);
1393
+ }
1394
+ function fakeXhr() {
1395
+ const xhr = new realXhr();
1396
+ let ah = xhr.__ajaxHooker;
1397
+ if (!ah) {
1398
+ ah = xhr.__ajaxHooker = {
1399
+ headers: {},
1400
+ hookedEvents: {
1401
+ readystatechange: new Set(),
1402
+ load: new Set(),
1403
+ loadend: new Set(),
1404
+ },
1405
+ delegateEvent: xhrDelegateEvent,
1406
+ originalGetters: {},
1407
+ originalMethods: {},
1408
+ };
1409
+ xhr.addEventListener("readystatechange", xhrReadyStateChange);
1410
+ xhr.addEventListener("load", xhrLoadAndLoadend);
1411
+ xhr.addEventListener("loadend", xhrLoadAndLoadend);
1412
+ for (const key of xhrResponses) {
1413
+ ah.originalGetters[key] = lookupGetter(xhr, key);
1414
+ }
1415
+ for (const method of [
1416
+ "open",
1417
+ "setRequestHeader",
1418
+ "addEventListener",
1419
+ "removeEventListener",
1420
+ ]) {
1421
+ ah.originalMethods[method] = xhr[method].bind(xhr);
1422
+ }
1423
+ xhr.open = fakeXhrOpen;
1424
+ xhr.setRequestHeader = (header, value) => {
1425
+ ah.originalMethods.setRequestHeader(header, value);
1426
+ if (xhr.readyState === 1) {
1427
+ if (ah.headers[header]) {
1428
+ ah.headers[header] += ", " + value;
1429
+ }
1430
+ else {
1431
+ ah.headers[header] = value;
1432
+ }
1433
+ }
1434
+ };
1435
+ xhr.addEventListener = function (...args) {
1436
+ if (xhrAsyncEvents.includes(args[0])) {
1437
+ ah.hookedEvents[args[0]].add(args[1]);
1438
+ }
1439
+ else {
1440
+ ah.originalMethods.addEventListener(...args);
1441
+ }
1442
+ };
1443
+ xhr.removeEventListener = function (...args) {
1444
+ if (xhrAsyncEvents.includes(args[0])) {
1445
+ ah.hookedEvents[args[0]].delete(args[1]);
1446
+ }
1447
+ else {
1448
+ ah.originalMethods.removeEventListener(...args);
1449
+ }
1450
+ };
1451
+ xhrAsyncEvents.forEach((evt) => {
1452
+ const onEvt = "on" + evt;
1453
+ defineProp(xhr, onEvt, () => {
1454
+ return ah.hookedEvents[onEvt] || null;
1455
+ }, (val) => {
1456
+ ah.hookedEvents[onEvt] = typeof val === "function" ? val : null;
1457
+ });
1458
+ });
1459
+ }
1460
+ const realSend = xhr.send.bind(xhr);
1461
+ xhr.send = function (data) {
1462
+ if (xhr.readyState !== 1)
1463
+ return realSend(data);
1464
+ ah.delegateEvent = xhrDelegateEvent;
1465
+ xhrResponses.forEach((prop) => {
1466
+ delete xhr[prop]; // delete descriptor
1467
+ });
1468
+ if (shouldFilter("xhr", ah.url, ah.method)) {
1469
+ xhr.addEventListener("ajaxHooker_responseReady", (e) => {
1470
+ ah.delegateEvent(e.detail);
1471
+ });
1472
+ return realSend(data);
1473
+ }
1474
+ try {
1475
+ const request = {
1476
+ type: "xhr",
1477
+ url: ah.url,
1478
+ method: ah.method,
1479
+ abort: false,
1480
+ headers: ah.headers,
1481
+ data: data,
1482
+ response: null,
1483
+ };
1484
+ const requestClone = { ...request };
1485
+ waitForHookFns(request).then(() => {
1486
+ waitForRequestKeys(request, requestClone).then(() => {
1487
+ if (request.abort)
1488
+ return;
1489
+ ah.originalMethods.open(request.method, request.url, ...ah.openArgs);
1490
+ for (const header in request.headers) {
1491
+ ah.originalMethods.setRequestHeader(header, request.headers[header]);
1492
+ }
1493
+ data = request.data;
1494
+ xhr.addEventListener("ajaxHooker_responseReady", (e) => {
1495
+ try {
1496
+ if (typeof request.response === "function") {
1497
+ const arg = {
1498
+ finalUrl: xhr.responseURL,
1499
+ status: xhr.status,
1500
+ responseHeaders: {},
1501
+ };
1502
+ for (const line of xhr
1503
+ .getAllResponseHeaders()
1504
+ .trim()
1505
+ .split(/[\r\n]+/)) {
1506
+ const parts = line.split(/:\s*/);
1507
+ if (parts.length === 2) {
1508
+ const lheader = parts[0].toLowerCase();
1509
+ if (arg.responseHeaders[lheader]) {
1510
+ arg.responseHeaders[lheader] += ", " + parts[1];
1511
+ }
1512
+ else {
1513
+ arg.responseHeaders[lheader] = parts[1];
1514
+ }
1515
+ }
1516
+ }
1517
+ xhrResponses.forEach((prop) => {
1518
+ defineProp(arg, prop, () => {
1519
+ return (arg[prop] = ah.originalGetters[prop]());
1520
+ }, (val) => {
1521
+ delete arg[prop];
1522
+ arg[prop] = val;
1523
+ });
1524
+ defineProp(xhr, prop, () => {
1525
+ const val = ah.originalGetters[prop]();
1526
+ xhr.dispatchEvent(new CustomEvent("ajaxHooker_readResponse", {
1527
+ detail: { prop, val },
1528
+ }));
1529
+ return val;
1530
+ });
1531
+ });
1532
+ xhr.addEventListener("ajaxHooker_readResponse", (e) => {
1533
+ arg[e.detail.prop] = e.detail.val;
1534
+ });
1535
+ const resPromise = Promise.resolve(request.response(arg)).then(() => {
1536
+ const task = [];
1537
+ xhrResponses.forEach((prop) => {
1538
+ const descriptor = Object.getOwnPropertyDescriptor(arg, prop);
1539
+ if (descriptor && "value" in descriptor) {
1540
+ task.push(Promise.resolve(descriptor.value).then((val) => {
1541
+ arg[prop] = val;
1542
+ defineProp(xhr, prop, () => {
1543
+ xhr.dispatchEvent(new CustomEvent("ajaxHooker_readResponse", {
1544
+ detail: { prop, val },
1545
+ }));
1546
+ return val;
1547
+ });
1548
+ }, emptyFn));
1549
+ }
1550
+ });
1551
+ return Promise.all(task);
1552
+ }, errorFn);
1553
+ const eventsClone = {};
1554
+ xhrAsyncEvents.forEach((type) => {
1555
+ eventsClone[type] = new Set([...ah.hookedEvents[type]]);
1556
+ eventsClone["on" + type] = ah.hookedEvents["on" + type];
1557
+ });
1558
+ ah.delegateEvent = (event) => resPromise.then(() => {
1559
+ event.stopImmediatePropagation = fakeEventSIP;
1560
+ eventsClone[event.type].forEach((fn) => !event.ajaxHooker_stopped && fn.call(xhr, event));
1561
+ const onEvent = eventsClone["on" + event.type];
1562
+ typeof onEvent === "function" &&
1563
+ onEvent.call(xhr, event);
1564
+ });
1565
+ }
1566
+ }
1567
+ catch (err) {
1568
+ console.error(err);
1569
+ }
1570
+ ah.delegateEvent(e.detail);
1571
+ });
1572
+ realSend(data);
1573
+ });
1574
+ });
1575
+ }
1576
+ catch (err) {
1577
+ console.error(err);
1578
+ realSend(data);
1579
+ }
1580
+ };
1581
+ return xhr;
1582
+ }
1583
+ function hookFetchResponse(response, arg, callback) {
1584
+ fetchResponses.forEach((prop) => {
1585
+ response[prop] = () => new Promise((resolve, reject) => {
1586
+ resProto[prop].call(response).then((res) => {
1587
+ if (prop in arg) {
1588
+ resolve(arg[prop]);
1589
+ }
1590
+ else {
1591
+ try {
1592
+ arg[prop] = res;
1593
+ Promise.resolve(callback(arg)).then(() => {
1594
+ if (prop in arg) {
1595
+ Promise.resolve(arg[prop]).then((val) => resolve((arg[prop] = val)), () => resolve(res));
1596
+ }
1597
+ else {
1598
+ resolve(res);
1599
+ }
1600
+ }, errorFn);
1601
+ }
1602
+ catch (err) {
1603
+ console.error(err);
1604
+ resolve(res);
1605
+ }
1606
+ }
1607
+ }, reject);
1608
+ });
1609
+ });
1610
+ }
1611
+ function fakeFetch(url, init) {
1612
+ if (url && typeof url.toString === "function") {
1613
+ url = url.toString();
1614
+ init = init || {};
1615
+ init.method = init.method || "GET";
1616
+ init.headers = init.headers || {};
1617
+ if (shouldFilter("fetch", url, init.method))
1618
+ return realFetch.call(win, url, init);
1619
+ const request = {
1620
+ type: "fetch",
1621
+ url: url,
1622
+ method: init.method.toUpperCase(),
1623
+ abort: false,
1624
+ headers: {},
1625
+ data: init.body,
1626
+ response: null,
1627
+ };
1628
+ if (toString.call(init.headers) === "[object Headers]") {
1629
+ for (const [key, val] of init.headers) {
1630
+ request.headers[key] = val;
1631
+ }
1632
+ }
1633
+ else {
1634
+ request.headers = { ...init.headers };
1635
+ }
1636
+ const requestClone = { ...request };
1637
+ return new Promise((resolve, reject) => {
1638
+ try {
1639
+ waitForHookFns(request).then(() => {
1640
+ waitForRequestKeys(request, requestClone).then(() => {
1641
+ if (request.abort)
1642
+ return reject("aborted");
1643
+ url = request.url;
1644
+ init.method = request.method;
1645
+ init.headers = request.headers;
1646
+ init.body = request.data;
1647
+ realFetch.call(win, url, init).then((response) => {
1648
+ if (typeof request.response === "function") {
1649
+ const arg = {
1650
+ finalUrl: response.url,
1651
+ status: response.status,
1652
+ responseHeaders: {},
1653
+ };
1654
+ for (const [key, val] of response.headers) {
1655
+ arg.responseHeaders[key] = val;
1656
+ }
1657
+ hookFetchResponse(response, arg, request.response);
1658
+ response.clone = () => {
1659
+ const resClone = resProto.clone.call(response);
1660
+ hookFetchResponse(resClone, arg, request.response);
1661
+ return resClone;
1662
+ };
1663
+ }
1664
+ resolve(response);
1665
+ }, reject);
1666
+ });
1667
+ });
1668
+ }
1669
+ catch (err) {
1670
+ console.error(err);
1671
+ return realFetch.call(win, url, init);
1672
+ }
1673
+ });
1674
+ }
1675
+ else {
1676
+ return realFetch.call(win, url, init);
1677
+ }
1678
+ }
1679
+ win.XMLHttpRequest = fakeXhr;
1680
+ Object.keys(realXhr).forEach((key) => (fakeXhr[key] = realXhr[key]));
1681
+ fakeXhr.prototype = realXhr.prototype;
1682
+ win.fetch = fakeFetch;
1683
+ return {
1684
+ hook: (fn) => hookFns.push(fn),
1685
+ filter: (arr) => {
1686
+ filter = Array.isArray(arr) && arr.map(toFilterObj);
1687
+ },
1688
+ protect: () => {
1689
+ readonly(win, "XMLHttpRequest", fakeXhr);
1690
+ readonly(win, "fetch", fakeFetch);
1691
+ },
1692
+ unhook: () => {
1693
+ writable(win, "XMLHttpRequest", realXhr);
1694
+ writable(win, "fetch", realFetch);
1695
+ },
1696
+ };
1697
+ })();
1711
1698
  };
1712
1699
 
1713
1700
  class GMMenu {
@@ -4932,403 +4919,401 @@ define((function () { 'use strict';
4932
4919
  const setInterval = (...args) => loadOrReturnBroker().setInterval(...args);
4933
4920
  const setTimeout$1 = (...args) => loadOrReturnBroker().setTimeout(...args);
4934
4921
 
4935
- /* eslint-disable */
4936
- // ==UserScript==
4937
- // @name ModuleRaid.js
4938
- // @namespace http://tampermonkey.net/
4939
- // @version 6.2.0
4940
- // @description 检索调用webpackJsonp模块,可指定检索的window
4941
- // @author empyrealtear
4942
- // @license MIT
4943
- // @original-script https://github.com/pixeldesu/moduleRaid
4944
- // ==/UserScript==
4945
-
4946
-
4947
- /**
4948
- * Main moduleRaid class
4949
- * @link https://scriptcat.org/zh-CN/script-show-page/2628
4950
- */
4951
- class ModuleRaid {
4952
- /**
4953
- * moduleRaid constructor
4954
- *
4955
- * @example
4956
- * Constructing an instance without any arguments:
4957
- * ```ts
4958
- * const mR = new ModuleRaid()
4959
- * ```
4960
- *
4961
- * Constructing an instance with the optional `opts` object:
4962
- * ```ts
4963
- * const mR = new ModuleRaid({ entrypoint: 'webpackChunk_custom_name' })
4964
- * ```
4965
- *
4966
- * @param opts a object containing options to initialize moduleRaid with
4967
- * - **opts:**
4968
- * - _target_: the window object being searched for
4969
- * - _entrypoint_: the Webpack entrypoint present on the global window object
4970
- * - _debug_: whether debug mode is enabled or not
4971
- * - _strict_: whether strict mode is enabled or not
4972
- */
4973
- constructor(opts) {
4974
- /**
4975
- * A random generated module ID we use for injecting into Webpack
4976
- */
4977
- this.moduleID = Math.random().toString(36).substring(7);
4978
- /**
4979
- * An array containing different argument injection methods for
4980
- * Webpack (before version 4), and subsequently pulling out methods and modules
4981
- * @internal
4982
- */
4983
- this.functionArguments = [
4984
- [
4985
- [0],
4986
- [
4987
- (_e, _t, i) => {
4988
- this.modules = i.c;
4989
- this.constructors = i.m;
4990
- this.get = i;
4991
- },
4992
- ],
4993
- ],
4994
- [
4995
- [1e3],
4996
- {
4997
- [this.moduleID]: (_e, _t, i) => {
4998
- this.modules = i.c;
4999
- this.constructors = i.m;
5000
- this.get = i;
5001
- },
5002
- },
5003
- [[this.moduleID]],
5004
- ],
5005
- ];
5006
- /**
5007
- * An array containing different argument injection methods for
5008
- * Webpack (after version 4), and subsequently pulling out methods and modules
5009
- * @internal
5010
- */
5011
- this.arrayArguments = [
5012
- [
5013
- [this.moduleID],
5014
- {},
5015
- (e) => {
5016
- const mCac = e.m;
5017
- Object.keys(mCac).forEach((mod) => {
5018
- try {
5019
- this.modules[mod] = e(mod);
5020
- }
5021
- catch (err) {
5022
- this.log(`[arrayArguments/1] Failed to require(${mod}) with error:\n${err}\n${err.stack}`);
5023
- }
5024
- });
5025
- this.get = e;
5026
- },
5027
- ],
5028
- this.functionArguments[1],
5029
- ];
5030
- /**
5031
- * Storage for the modules we extracted from Webpack
5032
- */
5033
- this.modules = {};
5034
- /**
5035
- * Storage for the constructors we extracted from Webpack
5036
- */
5037
- this.constructors = [];
5038
- let options = {
5039
- target: window,
5040
- entrypoint: 'webpackJsonp',
5041
- debug: false,
5042
- strict: false,
5043
- };
5044
- if (typeof opts === 'object') {
5045
- options = Object.assign(Object.assign({}, options), opts);
5046
- }
5047
- this.target = options.target;
5048
- this.entrypoint = options.entrypoint;
5049
- this.debug = options.debug;
5050
- this.strict = options.strict;
5051
- this.detectEntrypoint();
5052
- this.fillModules();
5053
- this.replaceGet();
5054
- this.setupPushEvent();
5055
- }
5056
- /**
5057
- * Debug logging method, outputs to the console when {@link ModuleRaid.debug} is true
5058
- *
5059
- * @param {*} message The message to be logged
5060
- * @internal
5061
- */
5062
- log(message) {
5063
- if (this.debug) {
5064
- console.warn(`[moduleRaid] ${message}`);
5065
- }
5066
- }
5067
- /**
5068
- * Method to set an alternative getter if we weren't able to extract __webpack_require__
5069
- * from Webpack
5070
- * @internal
5071
- */
5072
- replaceGet() {
5073
- if (this.get === null) {
5074
- this.get = (key) => this.modules[key];
5075
- }
5076
- }
5077
- /**
5078
- * Method that will try to inject a module into Webpack or get modules
5079
- * depending on it's success it might be more or less brute about it
5080
- * @internal
5081
- */
5082
- fillModules() {
5083
- if (typeof this.target[this.entrypoint] === 'function') {
5084
- this.functionArguments.forEach((argument, index) => {
5085
- try {
5086
- if (this.modules && Object.keys(this.modules).length > 0)
5087
- return;
5088
- this.target[this.entrypoint](...argument);
5089
- }
5090
- catch (err) {
5091
- this.log(`moduleRaid.functionArguments[${index}] failed:\n${err}\n${err.stack}`);
5092
- }
5093
- });
5094
- }
5095
- else {
5096
- this.arrayArguments.forEach((argument, index) => {
5097
- try {
5098
- if (this.modules && Object.keys(this.modules).length > 0)
5099
- return;
5100
- this.target[this.entrypoint].push(argument);
5101
- }
5102
- catch (err) {
5103
- this.log(`Pushing moduleRaid.arrayArguments[${index}] into ${this.entrypoint} failed:\n${err}\n${err.stack}`);
5104
- }
5105
- });
5106
- }
5107
- if (this.modules && Object.keys(this.modules).length == 0) {
5108
- let moduleEnd = false;
5109
- let moduleIterator = 0;
5110
- if (typeof this.target[this.entrypoint] != 'function' || !this.target[this.entrypoint]([], [], [moduleIterator])) {
5111
- throw Error('Unknown Webpack structure');
5112
- }
5113
- while (!moduleEnd) {
5114
- try {
5115
- this.modules[moduleIterator] = this.target[this.entrypoint]([], [], [moduleIterator]);
5116
- moduleIterator++;
5117
- }
5118
- catch (err) {
5119
- moduleEnd = true;
5120
- }
5121
- }
5122
- }
5123
- }
5124
- /**
5125
- * Method to hook into `window[this.entrypoint].push` adding a listener for new
5126
- * chunks being pushed into Webpack
5127
- *
5128
- * @example
5129
- * You can listen for newly pushed packages using the `moduleraid:webpack-push` event
5130
- * on `document`
5131
- *
5132
- * ```ts
5133
- * document.addEventListener('moduleraid:webpack-push', (e) => {
5134
- * // e.detail contains the arguments push() was called with
5135
- * console.log(e.detail)
5136
- * })
5137
- * ```
5138
- * @internal
5139
- */
5140
- setupPushEvent() {
5141
- const originalPush = this.target[this.entrypoint].push;
5142
- this.target[this.entrypoint].push = (...args) => {
5143
- const result = Reflect.apply(originalPush, this.target[this.entrypoint], args);
5144
- document.dispatchEvent(new CustomEvent('moduleraid:webpack-push', { detail: args }));
5145
- return result;
5146
- };
5147
- }
5148
- /**
5149
- * Method to try autodetecting a Webpack JSONP entrypoint based on common naming
5150
- *
5151
- * If the default entrypoint, or the entrypoint that's passed to the moduleRaid constructor
5152
- * already matches, the method exits early
5153
- *
5154
- * If `options.strict` has been set in the constructor and the initial entrypoint cannot
5155
- * be found, this method will error, demanding a strictly set entrypoint
5156
- * @internal
5157
- */
5158
- detectEntrypoint() {
5159
- if (this.target[this.entrypoint] != undefined) {
5160
- return;
5161
- }
5162
- if (this.strict) {
5163
- throw Error(`Strict mode is enabled and entrypoint at window.${this.entrypoint} couldn't be found. Please specify the correct one!`);
5164
- }
5165
- let windowObjects = Object.keys(this.target);
5166
- windowObjects = windowObjects
5167
- .filter((object) => object.toLowerCase().includes('chunk') || object.toLowerCase().includes('webpack'))
5168
- .filter((object) => typeof this.target[object] === 'function' || Array.isArray(this.target[object]));
5169
- if (windowObjects.length > 1) {
5170
- throw Error(`Multiple possible endpoints have been detected, please create a new moduleRaid instance with a specific one:\n${windowObjects.join(', ')}`);
5171
- }
5172
- if (windowObjects.length === 0) {
5173
- throw Error('No Webpack JSONP entrypoints could be detected');
5174
- }
5175
- this.log(`Entrypoint has been detected at window.${windowObjects[0]} and set for injection`);
5176
- this.entrypoint = windowObjects[0];
5177
- }
5178
- /**
5179
- * Recursive object-search function for modules
5180
- *
5181
- * @param object the object to search through
5182
- * @param query the query the object keys/values are searched for
5183
- * @returns boolean state of `object` containing `query` somewhere in it
5184
- * @internal
5185
- */
5186
- searchObject(object, query) {
5187
- for (const key in object) {
5188
- const value = object[key];
5189
- const lowerCaseQuery = query.toLowerCase();
5190
- if (typeof value != 'object') {
5191
- const lowerCaseKey = key.toString().toLowerCase();
5192
- if (lowerCaseKey.includes(lowerCaseQuery))
5193
- return true;
5194
- if (typeof value != 'object') {
5195
- const lowerCaseValue = value.toString().toLowerCase();
5196
- if (lowerCaseValue.includes(lowerCaseQuery))
5197
- return true;
5198
- }
5199
- else {
5200
- if (this.searchObject(value, query))
5201
- return true;
5202
- }
5203
- }
5204
- }
5205
- return false;
5206
- }
5207
- /**
5208
- * Method to search through the module object, searching for the fitting content
5209
- * if a string is supplied
5210
- *
5211
- * If query is supplied as a function, everything that returns true when passed
5212
- * to the query function will be returned
5213
- *
5214
- * @example
5215
- * With a string as query argument:
5216
- * ```ts
5217
- * const results = mR.findModule('feature')
5218
- * // => Array of module results
5219
- * ```
5220
- *
5221
- * With a function as query argument:
5222
- * ```ts
5223
- * const results = mR.findModule((module) => { typeof module === 'function' })
5224
- * // => Array of module results
5225
- * ```
5226
- *
5227
- * @param query query to search the module list for
5228
- * @return a list of modules fitting the query
5229
- */
5230
- findModule(query) {
5231
- const results = [];
5232
- const modules = Object.keys(this.modules);
5233
- if (modules.length === 0) {
5234
- throw new Error('There are no modules to search through!');
5235
- }
5236
- modules.forEach((key) => {
5237
- const module = this.modules[key.toString()];
5238
- if (module === undefined)
5239
- return;
5240
- try {
5241
- if (typeof query === 'string') {
5242
- query = query.toLowerCase();
5243
- switch (typeof module) {
5244
- case 'string':
5245
- if (module.toLowerCase().includes(query))
5246
- results.push(module);
5247
- break;
5248
- case 'function':
5249
- if (module.toString().toLowerCase().includes(query))
5250
- results.push(module);
5251
- break;
5252
- case 'object':
5253
- if (this.searchObject(module, query))
5254
- results.push(module);
5255
- break;
5256
- }
5257
- }
5258
- else if (typeof query === 'function') {
5259
- if (query(module))
5260
- results.push(module);
5261
- }
5262
- else {
5263
- throw new TypeError(`findModule can only find via string and function, ${typeof query} was passed`);
5264
- }
5265
- }
5266
- catch (err) {
5267
- this.log(`There was an error while searching through module '${key}':\n${err}\n${err.stack}`);
5268
- }
5269
- });
5270
- return results;
5271
- }
5272
- /**
5273
- * Method to search through the constructor array, searching for the fitting content
5274
- * if a string is supplied
5275
- *
5276
- * If query is supplied as a function, everything that returns true when passed
5277
- * to the query function will be returned
5278
- *
5279
- * @example
5280
- * With a string as query argument:
5281
- * ```ts
5282
- * const results = mR.findConstructor('feature')
5283
- * // => Array of constructor/module tuples
5284
- * ```
5285
- *
5286
- * With a function as query argument:
5287
- * ```ts
5288
- * const results = mR.findConstructor((constructor) => { constructor.prototype.value !== undefined })
5289
- * // => Array of constructor/module tuples
5290
- * ```
5291
- *
5292
- * Accessing the resulting data:
5293
- * ```ts
5294
- * // With array destructuring (ES6)
5295
- * const [constructor, module] = results[0]
5296
- *
5297
- * // ...or...
5298
- *
5299
- * // regular access
5300
- * const constructor = results[0][0]
5301
- * const module = results[0][1]
5302
- * ```
5303
- *
5304
- * @param query query to search the constructor list for
5305
- * @returns a list of constructor/module tuples fitting the query
5306
- */
5307
- findConstructor(query) {
5308
- const results = [];
5309
- const constructors = Object.keys(this.constructors);
5310
- if (constructors.length === 0) {
5311
- throw new Error('There are no constructors to search through!');
5312
- }
5313
- constructors.forEach((key) => {
5314
- const constructor = this.constructors[key];
5315
- try {
5316
- if (typeof query === 'string') {
5317
- query = query.toLowerCase();
5318
- if (constructor.toString().toLowerCase().includes(query))
5319
- results.push([this.constructors[key], this.modules[key]]);
5320
- }
5321
- else if (typeof query === 'function') {
5322
- if (query(constructor))
5323
- results.push([this.constructors[key], this.modules[key]]);
5324
- }
5325
- }
5326
- catch (err) {
5327
- this.log(`There was an error while searching through constructor '${key}':\n${err}\n${err.stack}`);
5328
- }
5329
- });
5330
- return results;
5331
- }
4922
+ /* eslint-disable */
4923
+ // ==UserScript==
4924
+ // @name ModuleRaid.js
4925
+ // @namespace http://tampermonkey.net/
4926
+ // @version 6.2.0
4927
+ // @description 检索调用webpackJsonp模块,可指定检索的window
4928
+ // @author empyrealtear
4929
+ // @license MIT
4930
+ // @original-script https://github.com/pixeldesu/moduleRaid
4931
+ // ==/UserScript==
4932
+ /**
4933
+ * Main moduleRaid class
4934
+ * @link https://scriptcat.org/zh-CN/script-show-page/2628
4935
+ */
4936
+ class ModuleRaid {
4937
+ /**
4938
+ * moduleRaid constructor
4939
+ *
4940
+ * @example
4941
+ * Constructing an instance without any arguments:
4942
+ * ```ts
4943
+ * const mR = new ModuleRaid()
4944
+ * ```
4945
+ *
4946
+ * Constructing an instance with the optional `opts` object:
4947
+ * ```ts
4948
+ * const mR = new ModuleRaid({ entrypoint: 'webpackChunk_custom_name' })
4949
+ * ```
4950
+ *
4951
+ * @param opts a object containing options to initialize moduleRaid with
4952
+ * - **opts:**
4953
+ * - _target_: the window object being searched for
4954
+ * - _entrypoint_: the Webpack entrypoint present on the global window object
4955
+ * - _debug_: whether debug mode is enabled or not
4956
+ * - _strict_: whether strict mode is enabled or not
4957
+ */
4958
+ constructor(opts) {
4959
+ /**
4960
+ * A random generated module ID we use for injecting into Webpack
4961
+ */
4962
+ this.moduleID = Math.random().toString(36).substring(7);
4963
+ /**
4964
+ * An array containing different argument injection methods for
4965
+ * Webpack (before version 4), and subsequently pulling out methods and modules
4966
+ * @internal
4967
+ */
4968
+ this.functionArguments = [
4969
+ [
4970
+ [0],
4971
+ [
4972
+ (_e, _t, i) => {
4973
+ this.modules = i.c;
4974
+ this.constructors = i.m;
4975
+ this.get = i;
4976
+ },
4977
+ ],
4978
+ ],
4979
+ [
4980
+ [1e3],
4981
+ {
4982
+ [this.moduleID]: (_e, _t, i) => {
4983
+ this.modules = i.c;
4984
+ this.constructors = i.m;
4985
+ this.get = i;
4986
+ },
4987
+ },
4988
+ [[this.moduleID]],
4989
+ ],
4990
+ ];
4991
+ /**
4992
+ * An array containing different argument injection methods for
4993
+ * Webpack (after version 4), and subsequently pulling out methods and modules
4994
+ * @internal
4995
+ */
4996
+ this.arrayArguments = [
4997
+ [
4998
+ [this.moduleID],
4999
+ {},
5000
+ (e) => {
5001
+ const mCac = e.m;
5002
+ Object.keys(mCac).forEach((mod) => {
5003
+ try {
5004
+ this.modules[mod] = e(mod);
5005
+ }
5006
+ catch (err) {
5007
+ this.log(`[arrayArguments/1] Failed to require(${mod}) with error:\n${err}\n${err.stack}`);
5008
+ }
5009
+ });
5010
+ this.get = e;
5011
+ },
5012
+ ],
5013
+ this.functionArguments[1],
5014
+ ];
5015
+ /**
5016
+ * Storage for the modules we extracted from Webpack
5017
+ */
5018
+ this.modules = {};
5019
+ /**
5020
+ * Storage for the constructors we extracted from Webpack
5021
+ */
5022
+ this.constructors = [];
5023
+ let options = {
5024
+ target: window,
5025
+ entrypoint: 'webpackJsonp',
5026
+ debug: false,
5027
+ strict: false,
5028
+ };
5029
+ if (typeof opts === 'object') {
5030
+ options = Object.assign(Object.assign({}, options), opts);
5031
+ }
5032
+ this.target = options.target;
5033
+ this.entrypoint = options.entrypoint;
5034
+ this.debug = options.debug;
5035
+ this.strict = options.strict;
5036
+ this.detectEntrypoint();
5037
+ this.fillModules();
5038
+ this.replaceGet();
5039
+ this.setupPushEvent();
5040
+ }
5041
+ /**
5042
+ * Debug logging method, outputs to the console when {@link ModuleRaid.debug} is true
5043
+ *
5044
+ * @param {*} message The message to be logged
5045
+ * @internal
5046
+ */
5047
+ log(message) {
5048
+ if (this.debug) {
5049
+ console.warn(`[moduleRaid] ${message}`);
5050
+ }
5051
+ }
5052
+ /**
5053
+ * Method to set an alternative getter if we weren't able to extract __webpack_require__
5054
+ * from Webpack
5055
+ * @internal
5056
+ */
5057
+ replaceGet() {
5058
+ if (this.get === null) {
5059
+ this.get = (key) => this.modules[key];
5060
+ }
5061
+ }
5062
+ /**
5063
+ * Method that will try to inject a module into Webpack or get modules
5064
+ * depending on it's success it might be more or less brute about it
5065
+ * @internal
5066
+ */
5067
+ fillModules() {
5068
+ if (typeof this.target[this.entrypoint] === 'function') {
5069
+ this.functionArguments.forEach((argument, index) => {
5070
+ try {
5071
+ if (this.modules && Object.keys(this.modules).length > 0)
5072
+ return;
5073
+ this.target[this.entrypoint](...argument);
5074
+ }
5075
+ catch (err) {
5076
+ this.log(`moduleRaid.functionArguments[${index}] failed:\n${err}\n${err.stack}`);
5077
+ }
5078
+ });
5079
+ }
5080
+ else {
5081
+ this.arrayArguments.forEach((argument, index) => {
5082
+ try {
5083
+ if (this.modules && Object.keys(this.modules).length > 0)
5084
+ return;
5085
+ this.target[this.entrypoint].push(argument);
5086
+ }
5087
+ catch (err) {
5088
+ this.log(`Pushing moduleRaid.arrayArguments[${index}] into ${this.entrypoint} failed:\n${err}\n${err.stack}`);
5089
+ }
5090
+ });
5091
+ }
5092
+ if (this.modules && Object.keys(this.modules).length == 0) {
5093
+ let moduleEnd = false;
5094
+ let moduleIterator = 0;
5095
+ if (typeof this.target[this.entrypoint] != 'function' || !this.target[this.entrypoint]([], [], [moduleIterator])) {
5096
+ throw Error('Unknown Webpack structure');
5097
+ }
5098
+ while (!moduleEnd) {
5099
+ try {
5100
+ this.modules[moduleIterator] = this.target[this.entrypoint]([], [], [moduleIterator]);
5101
+ moduleIterator++;
5102
+ }
5103
+ catch (err) {
5104
+ moduleEnd = true;
5105
+ }
5106
+ }
5107
+ }
5108
+ }
5109
+ /**
5110
+ * Method to hook into `window[this.entrypoint].push` adding a listener for new
5111
+ * chunks being pushed into Webpack
5112
+ *
5113
+ * @example
5114
+ * You can listen for newly pushed packages using the `moduleraid:webpack-push` event
5115
+ * on `document`
5116
+ *
5117
+ * ```ts
5118
+ * document.addEventListener('moduleraid:webpack-push', (e) => {
5119
+ * // e.detail contains the arguments push() was called with
5120
+ * console.log(e.detail)
5121
+ * })
5122
+ * ```
5123
+ * @internal
5124
+ */
5125
+ setupPushEvent() {
5126
+ const originalPush = this.target[this.entrypoint].push;
5127
+ this.target[this.entrypoint].push = (...args) => {
5128
+ const result = Reflect.apply(originalPush, this.target[this.entrypoint], args);
5129
+ document.dispatchEvent(new CustomEvent('moduleraid:webpack-push', { detail: args }));
5130
+ return result;
5131
+ };
5132
+ }
5133
+ /**
5134
+ * Method to try autodetecting a Webpack JSONP entrypoint based on common naming
5135
+ *
5136
+ * If the default entrypoint, or the entrypoint that's passed to the moduleRaid constructor
5137
+ * already matches, the method exits early
5138
+ *
5139
+ * If `options.strict` has been set in the constructor and the initial entrypoint cannot
5140
+ * be found, this method will error, demanding a strictly set entrypoint
5141
+ * @internal
5142
+ */
5143
+ detectEntrypoint() {
5144
+ if (this.target[this.entrypoint] != undefined) {
5145
+ return;
5146
+ }
5147
+ if (this.strict) {
5148
+ throw Error(`Strict mode is enabled and entrypoint at window.${this.entrypoint} couldn't be found. Please specify the correct one!`);
5149
+ }
5150
+ let windowObjects = Object.keys(this.target);
5151
+ windowObjects = windowObjects
5152
+ .filter((object) => object.toLowerCase().includes('chunk') || object.toLowerCase().includes('webpack'))
5153
+ .filter((object) => typeof this.target[object] === 'function' || Array.isArray(this.target[object]));
5154
+ if (windowObjects.length > 1) {
5155
+ throw Error(`Multiple possible endpoints have been detected, please create a new moduleRaid instance with a specific one:\n${windowObjects.join(', ')}`);
5156
+ }
5157
+ if (windowObjects.length === 0) {
5158
+ throw Error('No Webpack JSONP entrypoints could be detected');
5159
+ }
5160
+ this.log(`Entrypoint has been detected at window.${windowObjects[0]} and set for injection`);
5161
+ this.entrypoint = windowObjects[0];
5162
+ }
5163
+ /**
5164
+ * Recursive object-search function for modules
5165
+ *
5166
+ * @param object the object to search through
5167
+ * @param query the query the object keys/values are searched for
5168
+ * @returns boolean state of `object` containing `query` somewhere in it
5169
+ * @internal
5170
+ */
5171
+ searchObject(object, query) {
5172
+ for (const key in object) {
5173
+ const value = object[key];
5174
+ const lowerCaseQuery = query.toLowerCase();
5175
+ if (typeof value != 'object') {
5176
+ const lowerCaseKey = key.toString().toLowerCase();
5177
+ if (lowerCaseKey.includes(lowerCaseQuery))
5178
+ return true;
5179
+ if (typeof value != 'object') {
5180
+ const lowerCaseValue = value.toString().toLowerCase();
5181
+ if (lowerCaseValue.includes(lowerCaseQuery))
5182
+ return true;
5183
+ }
5184
+ else {
5185
+ if (this.searchObject(value, query))
5186
+ return true;
5187
+ }
5188
+ }
5189
+ }
5190
+ return false;
5191
+ }
5192
+ /**
5193
+ * Method to search through the module object, searching for the fitting content
5194
+ * if a string is supplied
5195
+ *
5196
+ * If query is supplied as a function, everything that returns true when passed
5197
+ * to the query function will be returned
5198
+ *
5199
+ * @example
5200
+ * With a string as query argument:
5201
+ * ```ts
5202
+ * const results = mR.findModule('feature')
5203
+ * // => Array of module results
5204
+ * ```
5205
+ *
5206
+ * With a function as query argument:
5207
+ * ```ts
5208
+ * const results = mR.findModule((module) => { typeof module === 'function' })
5209
+ * // => Array of module results
5210
+ * ```
5211
+ *
5212
+ * @param query query to search the module list for
5213
+ * @return a list of modules fitting the query
5214
+ */
5215
+ findModule(query) {
5216
+ const results = [];
5217
+ const modules = Object.keys(this.modules);
5218
+ if (modules.length === 0) {
5219
+ throw new Error('There are no modules to search through!');
5220
+ }
5221
+ modules.forEach((key) => {
5222
+ const module = this.modules[key.toString()];
5223
+ if (module === undefined)
5224
+ return;
5225
+ try {
5226
+ if (typeof query === 'string') {
5227
+ query = query.toLowerCase();
5228
+ switch (typeof module) {
5229
+ case 'string':
5230
+ if (module.toLowerCase().includes(query))
5231
+ results.push(module);
5232
+ break;
5233
+ case 'function':
5234
+ if (module.toString().toLowerCase().includes(query))
5235
+ results.push(module);
5236
+ break;
5237
+ case 'object':
5238
+ if (this.searchObject(module, query))
5239
+ results.push(module);
5240
+ break;
5241
+ }
5242
+ }
5243
+ else if (typeof query === 'function') {
5244
+ if (query(module))
5245
+ results.push(module);
5246
+ }
5247
+ else {
5248
+ throw new TypeError(`findModule can only find via string and function, ${typeof query} was passed`);
5249
+ }
5250
+ }
5251
+ catch (err) {
5252
+ this.log(`There was an error while searching through module '${key}':\n${err}\n${err.stack}`);
5253
+ }
5254
+ });
5255
+ return results;
5256
+ }
5257
+ /**
5258
+ * Method to search through the constructor array, searching for the fitting content
5259
+ * if a string is supplied
5260
+ *
5261
+ * If query is supplied as a function, everything that returns true when passed
5262
+ * to the query function will be returned
5263
+ *
5264
+ * @example
5265
+ * With a string as query argument:
5266
+ * ```ts
5267
+ * const results = mR.findConstructor('feature')
5268
+ * // => Array of constructor/module tuples
5269
+ * ```
5270
+ *
5271
+ * With a function as query argument:
5272
+ * ```ts
5273
+ * const results = mR.findConstructor((constructor) => { constructor.prototype.value !== undefined })
5274
+ * // => Array of constructor/module tuples
5275
+ * ```
5276
+ *
5277
+ * Accessing the resulting data:
5278
+ * ```ts
5279
+ * // With array destructuring (ES6)
5280
+ * const [constructor, module] = results[0]
5281
+ *
5282
+ * // ...or...
5283
+ *
5284
+ * // regular access
5285
+ * const constructor = results[0][0]
5286
+ * const module = results[0][1]
5287
+ * ```
5288
+ *
5289
+ * @param query query to search the constructor list for
5290
+ * @returns a list of constructor/module tuples fitting the query
5291
+ */
5292
+ findConstructor(query) {
5293
+ const results = [];
5294
+ const constructors = Object.keys(this.constructors);
5295
+ if (constructors.length === 0) {
5296
+ throw new Error('There are no constructors to search through!');
5297
+ }
5298
+ constructors.forEach((key) => {
5299
+ const constructor = this.constructors[key];
5300
+ try {
5301
+ if (typeof query === 'string') {
5302
+ query = query.toLowerCase();
5303
+ if (constructor.toString().toLowerCase().includes(query))
5304
+ results.push([this.constructors[key], this.modules[key]]);
5305
+ }
5306
+ else if (typeof query === 'function') {
5307
+ if (query(constructor))
5308
+ results.push([this.constructors[key], this.modules[key]]);
5309
+ }
5310
+ }
5311
+ catch (err) {
5312
+ this.log(`There was an error while searching through constructor '${key}':\n${err}\n${err.stack}`);
5313
+ }
5314
+ });
5315
+ return results;
5316
+ }
5332
5317
  }
5333
5318
 
5334
5319
  class DOMUtils {
@@ -5500,7 +5485,7 @@ define((function () { 'use strict';
5500
5485
  }
5501
5486
  const domUtils = new DOMUtils();
5502
5487
 
5503
- const version = "2.9.4";
5488
+ const version = "2.9.5";
5504
5489
 
5505
5490
  class Utils {
5506
5491
  windowApi;