@whitesev/utils 2.9.4 → 2.9.6

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