WhiteSevsUtils

一个好用的工具类

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/455186/1559518/WhiteSevsUtils.js

  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Utils = factory());
  5. })(this, (function () { 'use strict';
  6.  
  7. class ColorConversion {
  8. /**
  9. * 判断是否是16进制颜色
  10. * @param str
  11. */
  12. isHex(str) {
  13. if (typeof str !== "string") {
  14. return false;
  15. }
  16. if (!str.match(/^(\#|)[0-9a-fA-F]{6}$/)) {
  17. return false;
  18. }
  19. return true;
  20. }
  21. /**
  22. * 16进制颜色转rgba
  23. *
  24. * #ff0000 转 rgba(123,123,123, 0.4)
  25. * @param hex
  26. * @param opacity
  27. */
  28. hexToRgba(hex, opacity) {
  29. if (!this.isHex(hex)) {
  30. // @ts-ignore
  31. throw new TypeError("输入错误的hex", hex);
  32. }
  33. return hex && hex.replace(/\s+/g, "").length === 7
  34. ? "rgba(" +
  35. parseInt("0x" + hex.slice(1, 3)) +
  36. "," +
  37. parseInt("0x" + hex.slice(3, 5)) +
  38. "," +
  39. parseInt("0x" + hex.slice(5, 7)) +
  40. "," +
  41. opacity +
  42. ")"
  43. : "";
  44. }
  45. /**
  46. * hex转rgb
  47. * @param str
  48. * @returns
  49. */
  50. hexToRgb(str) {
  51. if (!this.isHex(str)) {
  52. // @ts-ignore
  53. throw new TypeError("输入错误的hex", str);
  54. }
  55. /* replace替换查找的到的字符串 */
  56. str = str.replace("#", "");
  57. /* match得到查询数组 */
  58. let hxs = str.match(/../g);
  59. for (let index = 0; index < 3; index++) {
  60. // @ts-ignore
  61. hxs[index] = parseInt(hxs[index], 16);
  62. }
  63. return hxs;
  64. }
  65. /**
  66. * rgb转hex
  67. * @param redValue
  68. * @param greenValue
  69. * @param blueValue
  70. * @returns
  71. */
  72. rgbToHex(redValue, greenValue, blueValue) {
  73. /* 验证输入的rgb值是否合法 */
  74. let validPattern = /^\d{1,3}$/;
  75. if (!validPattern.test(redValue.toString()) ||
  76. !validPattern.test(greenValue.toString()) ||
  77. !validPattern.test(blueValue.toString()))
  78. throw new TypeError("输入错误的rgb颜色值");
  79. let hexs = [
  80. redValue.toString(16),
  81. greenValue.toString(16),
  82. blueValue.toString(16),
  83. ];
  84. for (let index = 0; index < 3; index++)
  85. if (hexs[index].length == 1)
  86. hexs[index] = "0" + hexs[index];
  87. return "#" + hexs.join("");
  88. }
  89. /**
  90. * 获取颜色变暗或亮
  91. * @param color 颜色
  92. * @param level 0~1.0
  93. * @returns
  94. */
  95. getDarkColor(color, level) {
  96. if (!this.isHex(color)) {
  97. // @ts-ignore
  98. throw new TypeError("输入错误的hex", color);
  99. }
  100. let rgbc = this.hexToRgb(color);
  101. for (let index = 0; index < 3; index++) {
  102. // @ts-ignore
  103. rgbc[index] = Math.floor(rgbc[index] * (1 - level));
  104. }
  105. // @ts-ignore
  106. return this.rgbToHex(rgbc[0], rgbc[1], rgbc[2]);
  107. }
  108. /**
  109. * 获取颜色变亮
  110. * @param color 颜色
  111. * @param level 0~1.0
  112. * @returns
  113. */
  114. getLightColor(color, level) {
  115. if (!this.isHex(color)) {
  116. // @ts-ignore
  117. throw new TypeError("输入错误的hex", color);
  118. }
  119. let rgbc = this.hexToRgb(color);
  120. for (let index = 0; index < 3; index++) {
  121. // @ts-ignore
  122. rgbc[index] = Math.floor((255 - rgbc[index]) * level + rgbc[index]);
  123. }
  124. // @ts-ignore
  125. return this.rgbToHex(rgbc[0], rgbc[1], rgbc[2]);
  126. }
  127. }
  128.  
  129. class GBKEncoder {
  130. #data = [];
  131. #U2Ghash = {};
  132. #G2Uhash = {};
  133. constructor() {
  134. let dataText = this.handleText("4e:020405060f12171f20212326292e2f313335373c40414244464a5155575a5b6263646567686a6b6c6d6e6f727475767778797a7b7c7d7f808182838485878a#909697999c9d9ea3aaafb0b1b4b6b7b8b9bcbdbec8cccfd0d2dadbdce0e2e6e7e9edeeeff1f4f8f9fafcfe,4f:00020304050607080b0c12131415161c1d212328292c2d2e31333537393b3e3f40414244454748494a4b4c525456616266686a6b6d6e7172757778797a7d8081828586878a8c8e909293959698999a9c9e9fa1a2a4abadb0b1b2b3b4b6b7b8b9babbbcbdbec0c1c2c6c7c8c9cbcccdd2d3d4d5d6d9dbe0e2e4e5e7ebecf0f2f4f5f6f7f9fbfcfdff,50:000102030405060708090a#0b0e1011131516171b1d1e20222324272b2f303132333435363738393b3d3f404142444546494a4b4d5051525354565758595b5d5e5f6061626364666768696a6b6d6e6f70717273747578797a7c7d818283848687898a8b8c8e8f909192939495969798999a9b9c9d9e9fa0a1a2a4a6aaabadaeafb0b1b3b4b5b6b7b8b9bcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdced0d1d2d3d4d5d7d8d9dbdcdddedfe0e1e2e3e4e5e8e9eaebeff0f1f2f4f6f7f8f9fafcfdfeff,51:00010203040508#090a0c0d0e0f1011131415161718191a1b1c1d1e1f2022232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e42474a4c4e4f5052535758595b5d5e5f606163646667696a6f727a7e7f838486878a8b8e8f90919394989a9d9e9fa1a3a6a7a8a9aaadaeb4b8b9babebfc1c2c3c5c8cacdced0d2d3d4d5d6d7d8d9dadcdedfe2e3e5e6e7e8e9eaeceef1f2f4f7fe,52:0405090b0c0f101314151c1e1f2122232526272a2c2f313234353c3e4445464748494b4e4f5253555758#595a5b5d5f6062636466686b6c6d6e7071737475767778797a7b7c7e808384858687898a8b8c8d8e8f91929495969798999a9ca4a5a6a7aeafb0b4b5b6b7b8b9babbbcbdc0c1c2c4c5c6c8cacccdcecfd1d3d4d5d7d9dadbdcdddee0e1e2e3e5e6e7e8e9eaebecedeeeff1f2f3f4f5f6f7f8fbfcfd,53:0102030407090a0b0c0e11121314181b1c1e1f2224252728292b2c2d2f3031323334353637383c3d404244464b4c4d505458595b5d65686a6c6d7276797b7c7d7e80818387888a8e8f#90919293949697999b9c9ea0a1a4a7aaabacadafb0b1b2b3b4b5b7b8b9babcbdbec0c3c4c5c6c7cecfd0d2d3d5dadcdddee1e2e7f4fafeff,54:000205070b1418191a1c2224252a303336373a3d3f4142444547494c4d4e4f515a5d5e5f6061636567696a6b6c6d6e6f7074797a7e7f8183858788898a8d919397989c9e9fa0a1a2a5aeb0b2b5b6b7b9babcbec3c5cacbd6d8dbe0e1e2e3e4ebeceff0f1f4f5f6f7f8f9fbfe,55:0002030405080a0b0c0d0e121315161718191a1c1d1e1f212526#28292b2d3234353638393a3b3d40424547484b4c4d4e4f515253545758595a5b5d5e5f60626368696b6f7071727374797a7d7f85868c8d8e9092939596979a9b9ea0a1a2a3a4a5a6a8a9aaabacadaeafb0b2b4b6b8babcbfc0c1c2c3c6c7c8cacbcecfd0d5d7d8d9dadbdee0e2e7e9edeef0f1f4f6f8f9fafbfcff,56:0203040506070a0b0d1011121314151617191a1c1d202122252628292a2b2e2f30333537383a3c3d3e404142434445464748494a4b4f5051525355565a5b5d5e5f6061#636566676d6e6f70727374757778797a7d7e7f80818283848788898a8b8c8d9091929495969798999a9b9c9d9e9fa0a1a2a4a5a6a7a8a9aaabacadaeb0b1b2b3b4b5b6b8b9babbbdbebfc0c1c2c3c4c5c6c7c8c9cbcccdcecfd0d1d2d3d5d6d8d9dce3e5e6e7e8e9eaeceeeff2f3f6f7f8fbfc,57:00010205070b0c0d0e0f101112131415161718191a1b1d1e202122242526272b313234353637383c3d3f414344454648494b52535455565859626365676c6e707172747578797a7d7e7f80#818788898a8d8e8f90919495969798999a9c9d9e9fa5a8aaacafb0b1b3b5b6b7b9babbbcbdbebfc0c1c4c5c6c7c8c9cacccdd0d1d3d6d7dbdcdee1e2e3e5e6e7e8e9eaebeceef0f1f2f3f5f6f7fbfcfeff,58:0103040508090a0c0e0f101213141617181a1b1c1d1f222325262728292b2c2d2e2f31323334363738393a3b3c3d3e3f4041424345464748494a4b4e4f505253555657595a5b5c5d5f6061626364666768696a6d6e6f707172737475767778797a7b7c7d7f82848687888a8b8c#8d8e8f909194959697989b9c9da0a1a2a3a4a5a6a7aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbdbebfc0c2c3c4c6c7c8c9cacbcccdcecfd0d2d3d4d6d7d8d9dadbdcdddedfe0e1e2e3e5e6e7e8e9eaedeff1f2f4f5f7f8fafbfcfdfeff,59:000103050608090a0b0c0e1011121317181b1d1e2021222326282c30323335363b3d3e3f404345464a4c4d505253595b5c5d5e5f616364666768696a6b6c6d6e6f70717275777a7b7c7e7f8085898b8c8e8f90919495989a9b9c9d9fa0a1a2a6#a7acadb0b1b3b4b5b6b7b8babcbdbfc0c1c2c3c4c5c7c8c9cccdcecfd5d6d9dbdedfe0e1e2e4e6e7e9eaebedeeeff0f1f2f3f4f5f6f7f8fafcfdfe,5a:00020a0b0d0e0f101214151617191a1b1d1e2122242627282a2b2c2d2e2f3033353738393a3b3d3e3f414243444547484b4c4d4e4f5051525354565758595b5c5d5e5f60616364656668696b6c6d6e6f7071727378797b7c7d7e808182838485868788898a8b8c8d8e8f9091939495969798999c9d9e9fa0a1a2a3a4a5a6a7a8a9abac#adaeafb0b1b4b6b7b9babbbcbdbfc0c3c4c5c6c7c8cacbcdcecfd0d1d3d5d7d9dadbdddedfe2e4e5e7e8eaecedeeeff0f2f3f4f5f6f7f8f9fafbfcfdfeff,5b:0001020304050607080a0b0c0d0e0f10111213141518191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303133353638393a3b3c3d3e3f4142434445464748494a4b4c4d4e4f52565e606167686b6d6e6f7274767778797b7c7e7f82868a8d8e90919294969fa7a8a9acadaeafb1b2b7babbbcc0c1c3c8c9cacbcdcecf#d1d4d5d6d7d8d9dadbdce0e2e3e6e7e9eaebecedeff1f2f3f4f5f6f7fdfe,5c:0002030507080b0c0d0e10121317191b1e1f2021232628292a2b2d2e2f303233353637434446474c4d5253545657585a5b5c5d5f62646768696a6b6c6d70727374757677787b7c7d7e808384858687898a8b8e8f9293959d9e9fa0a1a4a5a6a7a8aaaeafb0b2b4b6b9babbbcbec0c2c3c5c6c7c8c9cacccdcecfd0d1d3d4d5d6d7d8dadbdcdddedfe0e2e3e7e9ebeceeeff1f2f3f4f5f6f7f8f9fafcfdfeff,5d:00#01040508090a0b0c0d0f10111213151718191a1c1d1f2021222325282a2b2c2f3031323335363738393a3b3c3f4041424344454648494d4e4f5051525354555657595a5c5e5f6061626364656667686a6d6e7071727375767778797a7b7c7d7e7f8081838485868788898a8b8c8d8e8f9091929394959697989a9b9c9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b8b9babbbcbdbebfc0c1c2c3c4c6c7c8c9cacbcccecfd0d1d2d3d4d5d6d7d8d9dadcdfe0e3e4eaeced#f0f5f6f8f9fafbfcff,5e:000407090a0b0d0e1213171e1f20212223242528292a2b2c2f303233343536393a3e3f404143464748494a4b4d4e4f50515253565758595a5c5d5f60636465666768696a6b6c6d6e6f70717577797e8182838588898c8d8e92989b9da1a2a3a4a8a9aaabacaeafb0b1b2b4babbbcbdbfc0c1c2c3c4c5c6c7c8cbcccdcecfd0d4d5d7d8d9dadcdddedfe0e1e2e3e4e5e6e7e9ebecedeeeff0f1f2f3f5f8f9fbfcfd,5f:050607090c0d0e10121416191a1c1d1e21222324#282b2c2e30323334353637383b3d3e3f4142434445464748494a4b4c4d4e4f5154595a5b5c5e5f60636567686b6e6f72747576787a7d7e7f83868d8e8f919394969a9b9d9e9fa0a2a3a4a5a6a7a9abacafb0b1b2b3b4b6b8b9babbbebfc0c1c2c7c8cacbced3d4d5dadbdcdedfe2e3e5e6e8e9eceff0f2f3f4f6f7f9fafc,60:0708090b0c10111317181a1e1f2223242c2d2e3031323334363738393a3d3e404445464748494a4c4e4f5153545657585b5c5e5f606165666e71727475777e80#8182858687888a8b8e8f909193959798999c9ea1a2a4a5a7a9aaaeb0b3b5b6b7b9babdbebfc0c1c2c3c4c7c8c9cccdcecfd0d2d3d4d6d7d9dbdee1e2e3e4e5eaf1f2f5f7f8fbfcfdfeff,61:02030405070a0b0c1011121314161718191b1c1d1e21222528292a2c2d2e2f303132333435363738393a3b3c3d3e4041424344454647494b4d4f50525354565758595a5b5c5e5f606163646566696a6b6c6d6e6f717273747678797a7b7c7d7e7f808182838485868788898a8c8d8f9091929395#969798999a9b9c9e9fa0a1a2a3a4a5a6aaabadaeafb0b1b2b3b4b5b6b8b9babbbcbdbfc0c1c3c4c5c6c7c9cccdcecfd0d3d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e7e8e9eaebecedeeeff0f1f2f3f4f6f7f8f9fafbfcfdfe,62:00010203040507091314191c1d1e2023262728292b2d2f303132353638393a3b3c424445464a4f50555657595a5c5d5e5f6061626465687172747577787a7b7d818283858687888b8c8d8e8f9094999c9d9ea3a6a7a9aaadaeafb0b2b3b4b6b7b8babec0c1#c3cbcfd1d5dddee0e1e4eaebf0f2f5f8f9fafb,63:00030405060a0b0c0d0f10121314151718191c2627292c2d2e30313334353637383b3c3e3f40414447484a51525354565758595a5b5c5d60646566686a6b6c6f707273747578797c7d7e7f81838485868b8d9193949597999a9b9c9d9e9fa1a4a6abafb1b2b5b6b9bbbdbfc0c1c2c3c5c7c8cacbccd1d3d4d5d7d8d9dadbdcdddfe2e4e5e6e7e8ebeceeeff0f1f3f5f7f9fafbfcfe,64:0304060708090a0d0e111215161718191a1d1f222324#252728292b2e2f3031323335363738393b3c3e404243494b4c4d4e4f505153555657595a5b5c5d5f60616263646566686a6b6c6e6f70717273747576777b7c7d7e7f8081838688898a8b8c8d8e8f90939497989a9b9c9d9fa0a1a2a3a5a6a7a8aaabafb1b2b3b4b6b9bbbdbebfc1c3c4c6c7c8c9cacbcccfd1d3d4d5d6d9dadbdcdddfe0e1e3e5e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,65:01020304050607080a0b0c0d0e0f10111314151617191a1b1c1d1e1f2021#222324262728292a2c2d30313233373a3c3d404142434446474a4b4d4e5052535457585a5c5f606164656768696a6d6e6f7173757678797a7b7c7d7e7f8081828384858688898a8d8e8f92949596989a9d9ea0a2a3a6a8aaacaeb1b2b3b4b5b6b7b8babbbebfc0c2c7c8c9cacdd0d1d3d4d5d8d9dadbdcdddedfe1e3e4eaebf2f3f4f5f8f9fbfcfdfeff,66:0104050708090b0d1011121617181a1b1c1e2122232426292a2b2c2e3032333738393a3b3d3f40424445464748494a4d4e505158#595b5c5d5e6062636567696a6b6c6d7172737578797b7c7d7f808183858688898a8b8d8e8f909293949598999a9b9c9e9fa0a1a2a3a4a5a6a9aaabacadafb0b1b2b3b5b6b7b8babbbcbdbfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8dadedfe0e1e2e3e4e5e7e8eaebecedeeeff1f5f6f8fafbfd,67:010203040506070c0e0f1112131618191a1c1e20212223242527292e303233363738393b3c3e3f414445474a4b4d5254555758595a5b5d62636466676b6c6e717476#78797a7b7d8082838586888a8c8d8e8f9192939496999b9fa0a1a4a6a9acaeb1b2b4b9babbbcbdbebfc0c2c5c6c7c8c9cacbcccdced5d6d7dbdfe1e3e4e6e7e8eaebedeef2f5f6f7f8f9fafbfcfe,68:01020304060d1012141518191a1b1c1e1f20222324252627282b2c2d2e2f30313435363a3b3f474b4d4f52565758595a5b5c5d5e5f6a6c6d6e6f707172737578797a7b7c7d7e7f8082848788898a8b8c8d8e90919294959698999a9b9c9d9e9fa0a1a3a4a5a9aaabacaeb1b2b4b6b7b8#b9babbbcbdbebfc1c3c4c5c6c7c8cacccecfd0d1d3d4d6d7d9dbdcdddedfe1e2e4e5e6e7e8e9eaebecedeff2f3f4f6f7f8fbfdfeff,69:00020304060708090a0c0f11131415161718191a1b1c1d1e21222325262728292a2b2c2e2f313233353637383a3b3c3e4041434445464748494a4b4c4d4e4f50515253555658595b5c5f616264656768696a6c6d6f7072737475767a7b7d7e7f8183858a8b8c8e8f909192939697999a9d9e9fa0a1a2a3a4a5a6a9aaacaeafb0b2b3b5b6b8b9babcbd#bebfc0c2c3c4c5c6c7c8c9cbcdcfd1d2d3d5d6d7d8d9dadcdddee1e2e3e4e5e6e7e8e9eaebeceeeff0f1f3f4f5f6f7f8f9fafbfcfe,6a:000102030405060708090b0c0d0e0f10111213141516191a1b1c1d1e20222324252627292b2c2d2e30323334363738393a3b3c3f40414243454648494a4b4c4d4e4f515253545556575a5c5d5e5f60626364666768696a6b6c6d6e6f70727374757677787a7b7d7e7f81828385868788898a8b8c8d8f929394959698999a9b9c9d9e9fa1a2a3a4a5a6#a7a8aaadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,6b:000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f252628292a2b2c2d2e2f303133343536383b3c3d3f4041424445484a4b4d4e4f5051525354555657585a5b5c5d5e5f606168696b6c6d6e6f7071727374757677787a7d7e7f808588#8c8e8f909194959798999c9d9e9fa0a2a3a4a5a6a7a8a9abacadaeafb0b1b2b6b8b9babbbcbdbec0c3c4c6c7c8c9caccced0d1d8dadcdddedfe0e2e3e4e5e6e7e8e9ecedeef0f1f2f4f6f7f8fafbfcfeff,6c:000102030408090a0b0c0e12171c1d1e2023252b2c2d31333637393a3b3c3e3f434445484b4c4d4e4f5152535658595a62636566676b6c6d6e6f71737577787a7b7c7f8084878a8b8d8e9192959697989a9c9d9ea0a2a8acafb0b4b5b6b7bac0c1c2c3c6c7c8cbcdcecfd1d2d8#d9dadcdddfe4e6e7e9ecedf2f4f9ff,6d:000203050608090a0d0f101113141516181c1d1f20212223242628292c2d2f30343637383a3f404244494c50555657585b5d5f6162646567686b6c6d707172737576797a7b7d7e7f8081838486878a8b8d8f9092969798999a9ca2a5acadb0b1b3b4b6b7b9babbbcbdbec1c2c3c8c9cacdcecfd0d2d3d4d5d7dadbdcdfe2e3e5e7e8e9eaedeff0f2f4f5f6f8fafdfeff,6e:0001020304060708090b0f12131518191b1c1e1f222627282a2c2e30313335#3637393b3c3d3e3f40414245464748494a4b4c4f5051525557595a5c5d5e606162636465666768696a6c6d6f707172737475767778797a7b7c7d8081828487888a8b8c8d8e91929394959697999a9b9d9ea0a1a3a4a6a8a9abacadaeb0b3b5b8b9bcbebfc0c3c4c5c6c8c9cacccdced0d2d6d8d9dbdcdde3e7eaebecedeeeff0f1f2f3f5f6f7f8fafbfcfdfeff,6f:000103040507080a0b0c0d0e101112161718191a1b1c1d1e1f212223252627282c2e303234353738393a3b3c3d3f404142#43444548494a4c4e4f5051525354555657595a5b5d5f60616364656768696a6b6c6f707173757677797b7d7e7f808182838586878a8b8f909192939495969798999a9b9d9e9fa0a2a3a4a5a6a8a9aaabacadaeafb0b1b2b4b5b7b8babbbcbdbebfc1c3c4c5c6c7c8cacbcccdcecfd0d3d4d5d6d7d8d9dadbdcdddfe2e3e4e5e6e7e8e9eaebecedf0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,70:000102030405060708090a0b0c0d0e0f1012131415161718191c1d1e1f2021222425262728292a#2b2c2d2e2f30313233343637383a3b3c3d3e3f404142434445464748494a4b4d4e505152535455565758595a5b5c5d5f606162636465666768696a6e7172737477797a7b7d818283848687888b8c8d8f90919397989a9b9e9fa0a1a2a3a4a5a6a7a8a9aab0b2b4b5b6babebfc4c5c6c7c9cbcccdcecfd0d1d2d3d4d5d6d7dadcdddee0e1e2e3e5eaeef0f1f2f3f4f5f6f8fafbfcfeff,71:0001020304050607080b0c0d0e0f111214171b1c1d1e1f2021222324252728292a2b2c2d2e323334#353738393a3b3c3d3e3f4041424344464748494b4d4f505152535455565758595a5b5d5f6061626365696a6b6c6d6f707174757677797b7c7e7f8081828385868788898b8c8d8e909192939596979a9b9c9d9ea1a2a3a4a5a6a7a9aaabadaeafb0b1b2b4b6b7b8babbbcbdbebfc0c1c2c4c5c6c7c8c9cacbcccdcfd0d1d2d3d6d7d8d9dadbdcdddedfe1e2e3e4e6e8e9eaebecedeff0f1f2f3f4f5f6f7f8fafbfcfdfeff,72:0001020304050708090a0b0c0d0e0f101112131415161718191a#1b1c1e1f2021222324252627292b2d2e2f3233343a3c3e40414243444546494a4b4e4f505153545557585a5c5e60636465686a6b6c6d707173747677787b7c7d828385868788898c8e9091939495969798999a9b9c9d9ea0a1a2a3a4a5a6a7a8a9aaabaeb1b2b3b5babbbcbdbebfc0c5c6c7c9cacbcccfd1d3d4d5d6d8dadb#95$,30:000102,00b702:c9c7,00a830:0305,2014ff5e20:162618191c1d,30:141508090a0b0c0d0e0f16171011,00:b1d7f7,22:362728110f2a2908371aa52520,231222:992b2e614c483d1d606e6f64651e3534,26:4240,00b020:3233,2103ff0400a4ff:e0e1,203000a7211626:0605,25:cbcfcec7c6a1a0b3b2,203b21:92909193,30:13#95$,21:70717273747576777879#4$,24:88898a8b8c8d8e8f909192939495969798999a9b7475767778797a7b7c7d7e7f808182838485868760616263646566676869##,32:20212223242526272829##,21:606162636465666768696a6b#97$,ff:010203e505060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5de3#95$,30:4142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f90919293#106$a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6#103$,03:9192939495969798999a9b9c9d9e9fa0a1a3a4a5a6a7a8a9#6$b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c3c4c5c6c7c8c9#5$,fe:3536393a3f403d3e41424344##3b3c373831#3334#104$,04:10111213141501161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f#13$30313233343551363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f#11$,02:cacbd9,20:13152535,21:050996979899,22:151f23526667bf,25:505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f7071727381828384858687#88898a8b8c8d8e8f939495bcbde2e3e4e5,2609229530:121d1e#9$,010100e101ce00e0011300e9011b00e8012b00ed01d000ec014d00f301d200f2016b00fa01d400f901:d6d8dadc,00:fcea,0251e7c701:4448,e7c802:61#2$,31:05060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20212223242526272829#19$,30:212223242526272829,32a333:8e8f9c9d9ea1c4ced1d2d5,fe30ff:e2e4#,212132:31#,20:10#1$,30:fc9b9cfdfe069d9e,fe:494a4b4c4d4e4f50515254555657595a5b5c5d5e5f6061#626364656668696a6b,e7:e7e8e9eaebecedeeeff0f1f2f3,30:07#11$,25:000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b#13$,72:dcdddfe2e3e4e5e6e7eaebf5f6f9fdfeff,73:00020405060708090b0c0d0f1011121418191a1f2023242627282d2f30323335363a3b3c3d404142434445464748#494a4b4c4e4f515354555658595a5b5c5d5e5f6162636465666768696a6b6e7071#92$72737475767778797a7b7c7d7f808182838586888a8c8d8f90929394959798999a9c9d9ea0a1a3a4a5a6a7a8aaacadb1b4b5b6b8b9bcbdbebfc1c3c4c5c6c7#cbccced2d3d4d5d6d7d8dadbdcdddfe1e2e3e4e6e8eaebeceeeff0f1f3f4f5f6f7#92$f8f9fafbfcfdfeff,74:0001020407080b0c0d0e1112131415161718191c1d1e1f2021232427292b2d2f31323738393a3b3d3e3f4042434445464748494a4b4c4d#4e4f505152535456585d606162636465666768696a6b6c6e6f717273747578797a#92$7b7c7d7f8284858688898a8c8d8f9192939495969798999a9b9d9fa0a1a2a3a4a5a6aaabacadaeafb0b1b2b3b4b5b6b7b8b9bbbcbdbebfc0c1c2c3c4c5c6c7#c8c9cacbcccdcecfd0d1d3d4d5d6d7d8d9dadbdddfe1e5e7e8e9eaebecedf0f1f2#92$f3f5f8f9fafbfcfdfe,75:0001020305060708090a0b0c0e1012141516171b1d1e202122232426272a2e3436393c3d3f414243444647494a4d5051525355565758#5d5e5f60616263646768696b6c6d6e6f7071737576777a7b7c7d7e808182848587#92$88898a8c8d8e909395989b9c9ea2a6a7a8a9aaadb6b7babbbfc0c1c6cbcccecfd0d1d3d7d9dadcdddfe0e1e5e9ecedeeeff2f3f5f6f7f8fafbfdfe,76:02040607#08090b0d0e0f11121314161a1c1d1e212327282c2e2f31323637393a3b3d414244#92$45464748494a4b4e4f50515253555758595a5b5d5f6061626465666768696a6c6d6e7071727374757677797a7c7f80818385898a8c8d8f9092949597989a9b#9c9d9e9fa0a1a2a3a5a6a7a8a9aaabacadafb0b3b5b6b7b8b9babbbcbdbec0c1c3,554a963f57c3632854ce550954c076:914c,853c77ee827e788d72319698978d6c285b894ffa630966975cb880fa684880ae660276ce51f9655671ac7ff1888450b2596561ca6fb382ad634c625253ed54277b06516b75a45df462d48dcb9776628a8019575d97387f627238767d67cf767e64464f708d2562dc7a17659173ed642c6273822c9881677f724862:6ecc,4f3474e3534a529e7eca90a65e2e6886699c81807ed168d278c5868c9551508d8c2482de80de53058912526576:c4c7c9cbccd3d5d9dadcdddee0e1e2e3e4e6e7e8e9eaebecedf0f3f5f6f7fafbfdff,77:00020305060a0c0e0f1011121314151617181b1c1d1e21232425272a2b#2c2e3031323334393b3d3e3f4244454648494a4b4c4d4e4f52535455565758595c,858496f94fdd582199715b9d62:b1a5,66b48c799c8d7206676f789160b253:5117,8f8880cc8d1d94a1500d72c8590760eb711988ab595482ef672c7b285d297ef7752d6cf58e668ff8903c9f3b6bd491197b145f7c78a784d6853d6b:d5d9d6,5e:0187,75f995ed655d5f:0ac5,8f9f58c181c2907f965b97ad8fb97f168d2c62414fbf53:d85e,8f:a8a9ab,904d68075f6a819888689cd6618b522b762a5f6c658c6fd26ee85bbe644851:75b0,67c44e1979c9997c70b377:5d5e5f606467696a6d6e6f7071727374757677787a7b7c818283868788898a8b8f90939495969798999a9b9c9d9ea1a3a4a6a8abadaeafb1b2b4b6b7b8b9ba#bcbec0c1c2c3c4c5c6c7c8c9cacbcccecfd0d1d2d3d4d5d6d8d9dadddedfe0e1e4,75c55e7673bb83e064ad62e894b56ce2535a52c3640f94c27b944f2f5e1b823681:168a,6e246cca9a736355535c54fa886557e04e0d5e036b657c3f90e8601664e6731c88c16750624d8d22776c8e2991c75f6983dc8521991053c286956b8b60:ede8,707f82:cd31,4ed36ca785cf64cd7cd969fd66f9834953957b564fa7518c6d4b5c428e6d63d253c983:2c36,67e578b4643d5bdf5c945dee8be762c667f48c7a640063ba8749998b8c177f2094f24ea7961098a4660c731677:e6e8eaeff0f1f2f4f5f7f9fafbfc,78:0304050607080a0b0e0f101315191b1e20212224282a2b2e2f31323335363d3f414243444648494a4b4d4f51535458595a#5b5c5e5f606162636465666768696f7071727374757678797a7b7d7e7f80818283,573a5c1d5e38957f507f80a05382655e7545553150218d856284949e671d56326f6e5de2543570928f66626f64a463a35f7b6f8890f481e38fb05c1866685ff16c8996488d81886c649179f057ce6a59621054484e587a0b60e96f848bda627f901e9a8b79e4540375f4630153196c608fdf5f1b9a70803b9f7f4f885c3a8d647fc565a570bd51:45b2,866b5d075ba062bd916c75748e0c7a2061017b794ec77ef877854e1181ed521d51fa6a7153a88e87950496cf6ec19664695a78:848586888a8b8f9092949596999d9ea0a2a4a6a8a9aaabacadaeafb5b6b7b8babbbcbdbfc0c2c3c4c6c7c8cccdcecfd1d2d3d6d7d8dadbdcdddedfe0e1e2e3#e4e5e6e7e9eaebedeeeff0f1f3f5f6f8f9fbfcfdfeff,79:00020304060708090a0b0c,784050a877d7641089e6590463e35ddd7a7f693d4f20823955984e3275ae7a975e:628a,95ef521b5439708a6376952457826625693f918755076df37eaf882262337ef075b5832878c196cc8f9e614874f78bcd6b64523a8d506b21806a847156f153064e:ce1b,51d17c97918b7c074fc38e7f7be17a9c64675d1450ac810676017cb96dec7fe067515b:58f8,78cb64:ae13,63:aa2b,9519642d8fbe7b5476296253592754466b7950a362345e266b864ee38d37888b5f85902e79:0d0e0f1011121415161718191a1b1c1d1f2021222325262728292a2b2c2d2e2f3031323335363738393d3f42434445474a4b4c4d4e4f505152545558596163#6466696a6b6c6e70717273747576797b7c7d7e7f8283868788898b8c8d8e909192,6020803d62c54e39535590f863b880c665e66c2e4f4660ee6de18bde5f3986cb5f536321515a83616863520063638e4850125c9b79775bfc52307a3b60bc905376d75f:b797,76848e6c706f767b7b4977aa51f3909358244f4e6ef48fea654c7b1b72c46da47fdf5ae162b55e95573084827b2c5e1d5f1f90127f1498a063826ec7789870b95178975b57ab75354f4375385e9760e659606dc06bbf788953fc96d551cb52016389540a94938c038dcc7239789f87768fed8c0d53e079:939495969798999b9c9d9e9fa0a1a2a3a4a5a6a8a9aaabacadaeafb0b1b2b4b5b6b7b8bcbfc2c4c5c7c8cacccecfd0d3d4d6d7d9dadbdcdddee0e1e2e5e8ea#eceef1f2f3f4f5f6f7f9fafcfeff,7a:0104050708090a0c0f10111213151618191b1c,4e0176ef53ee948998769f0e952d5b9a8ba24e:221c,51ac846361c252a8680b4f97606b51bb6d1e515c6296659796618c46901775d890fd77636bd272:8aec,8bfb583577798d4c675c9540809a5ea66e2159927aef77ed953b6bb565ad7f0e58065151961f5bf958a954288e726566987f56e4949d76fe9041638754c659:1a3a,579b8eb267358dfa8235524160f0581586fe5ce89e454fc4989d8bb95a2560765384627c904f9102997f6069800c513f80335c1499756d314e8c7a:1d1f21222425262728292a2b2c2d2e2f303132343536383a3e4041424344454748494a4b4c4d4e4f50525354555658595a5b5c5d5e5f606162636465666768#696a6b6c6d6e6f717273757b7c7d7e828587898a8b8c8e8f909394999a9b9ea1a2,8d3053d17f5a7b4f4f104e4f96006cd573d085e95e06756a7ffb6a0a77fe94927e4151e170e653cd8fd483038d2972af996d6cdb574a82b365b980aa623f963259a84eff8bbf7eba653e83f2975e556198de80a5532a8bfd542080ba5e9f6cb88d3982ac915a54296c1b52067eb7575f711a6c7e7c89594b4efd5fff61247caa4e305c0167ab87025cf0950b98ce75af70fd902251af7f1d8bbd594951e44f5b5426592b657780a45b7562:76c2,8f905e456c1f7b264f:0fd8,670d7a:a3a4a7a9aaabaeafb0b1b2b4b5b6b7b8b9babbbcbdbec0c1c2c3c4c5c6c7c8c9cacccdcecfd0d1d2d3d4d5d7d8dadbdcdde1e2e4e7e8e9eaebeceef0f1f2f3#f4f5f6f7f8fbfcfe,7b:0001020507090c0d0e1012131617181a1c1d1f21222327292d,6d:6eaa,798f88b15f17752b629a8f854fef91dc65a781:2f51,5e9c81508d74526f89868d4b590d50854ed8961c723681798d1f5bcc8ba3964459877f1a549056:760e,8be565396982949976d66e895e72751867:46d1,7aff809d8d76611f79c665628d635188521a94a27f38809b7eb25c976e2f67607bd9768b9ad8818f7f947cd5641e95507a3f54:4ae5,6b4c640162089e3d80f3759952729769845b683c86e496:0194,94ec4e2a54047ed968398ddf801566f45e9a7fb97b:2f303234353637393b3d3f404142434446484a4d4e535557595c5e5f61636465666768696a6b6c6d6f70737476787a7c7d7f81828384868788898a8b8c8e8f#9192939698999a9b9e9fa0a3a4a5aeafb0b2b3b5b6b7b9babbbcbdbebfc0c2c3c4,57c2803f68975de5653b529f606d9f9a4f9b8eac516c5bab5f135de96c5e62f18d21517194a952fe6c9f82df72d757a267848d2d591f8f9c83c754957b8d4f306cbd5b6459d19f1353e486ca9aa88c3780a16545987e56fa96c7522e74dc52505be1630289024e5662d0602a68fa51735b9851a089c27ba199867f5060ef704c8d2f51495e7f901b747089c4572d78455f529f9f95fa8f689b3c8be17678684267dc8d:ea35,523d8f8a6eda68cd950590ed56fd679c88f98fc754c87b:c5c8c9cacbcdcecfd0d2d4d5d6d7d8dbdcdedfe0e2e3e4e7e8e9ebecedeff0f2f3f4f5f6f8f9fafbfdff,7c:0001020304050608090a0d0e101112131415171819#1a1b1c1d1e20212223242528292b2c2d2e2f3031323334353637393a3b3c3d3e42,9ab85b696d776c264ea55bb39a87916361a890af97e9542b6db55bd251fd558a7f:55f0,64bc634d65f161be608d710a6c:5749,592f676d822a58d5568e8c6a6beb90dd597d801753f76d695475559d83:77cf,683879be548c4f55540876d28c8996026cb36db88d6b89109e648d3a563f9ed175d55f8872e0606854fc4ea86a2a886160528f7054c470d886799e3f6d2a5b8f5f187ea255894faf7334543c539a501954:0e7c,4e4e5ffd745a58f6846b80e1877472d07cca6e567c:434445464748494a4b4c4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f70717275767778797a7e7f8081828384858687#888a8b8c8d8e8f90939496999a9ba0a1a3a6a7a8a9abacadafb0b4b5b6b7b8babb,5f27864e552c62a44e926caa623782b154d7534e733e6ed1753b521253168bdd69d05f8a60006dee574f6b2273af68538fd87f13636260a3552475ea8c6271156da35ba65e7b8352614c9ec478fa87577c27768751f060f6714c66435e4c604d8c0e707063258f895fbd606286d456de6bc160946167534960e066668d3f79fd4f1a70e96c478b:b3f2,7ed88364660f5a5a9b426d:51f7,8c416d3b4f19706b83b7621660d1970d8d27797851fb57:3efa,673a75787a3d79ef7b957c:bfc0c2c3c4c6c9cbcecfd0d1d2d3d4d8dadbdddee1e2e3e4e5e6e7e9eaebecedeef0f1f2f3f4f5f6f7f9fafcfdfeff,7d:000102030405060708090b0c0d0e0f10#1112131415161718191a1b1c1d1e1f212324252628292a2c2d2e30313233343536,808c99658ff96fc08ba59e2159ec7ee97f095409678168d88f917c4d96c653ca602575be6c7253735ac97ea7632451e0810a5df184df628051805b634f0e796d524260b86d4e5b:c4c2,8b:a1b0,65e25fcc964559937e:e7aa,560967b759394f735bb652a0835a988a8d3e753294be50477a3c4ef767b69a7e5ac16b7c76d1575a5c167b3a95f4714e517c80a9827059787f04832768c067ec78:b177,62e363617b804fed526a51cf835069db92748d:f531,89c1952e7bad4ef67d:3738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6f70717273747576#78797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798,506582305251996f6e:1085,6da75efa50f559dc5c066d466c5f7586848b686859568bb253209171964d854969127901712680f64ea490ca6d479a845a0756bc640594f077eb4fa5811a72e189d2997a7f347ede527f655991758f:7f83,53eb7a9663:eda5,768679f888579636622a52ab8282685467706377776b7aed6d017ed389e359d0621285c982a5754c501f4ecb75a58beb5c4a5dfe7b4b65a491d14eca6d25895f7d2795264ec58c288fdb9773664b79818fd170ec6d787d:999a9b9c9d9e9fa0a1a2a3a4a5a7a8a9aaabacadafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9#dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fa,5c3d52b283465162830e775b66769cb84eac60ca7c:beb3,7ecf4e958b66666f988897595883656c955c5f8475c997567a:dfde,51c070af7a9863ea7a767ea0739697ed4e4570784e5d915253a965:51e7,81fc8205548e5c31759a97a062d872d975bd5c459a7983ca5c40548077e94e3e6cae805a62d2636e5de851778ddd8e1e952f4ff153e560e770ac526763509e435a1f5026773753777ee26485652b628963985014723589c951b38bc07edd574783cc94a7519b541b5cfb7d:fbfcfdfeff,7e:000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233343536373839#3a3c3d3e3f40424344454648494a4b4c4d4e4f505152535455565758595a5b5c5d,4fca7ae36d5a90e19a8f55805496536154af5f0063e9697751ef6168520a582a52d8574e780d770b5eb761777ce062:5b97,4ea27095800362f770e49760577782db67ef68f578d5989779d158f354b353ef6e34514b523b5ba28bfe80af554357a660735751542d7a7a60505b5463a762a053e362635bc767af54ed7a9f82e691775e9388e4593857ae630e8de880ef57577b774fa95feb5bbd6b3e53217b5072c2684677:ff36,65f751b54e8f76d45cbf7aa58475594e9b4150807e:5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f8081838485868788898a8b8c8d8e8f909192939495969798999a9c9d9e#aeb4bbbcd6e4ecf9,7f:0a101e37393b3c3d3e3f404143464748494a4b4c4d4e4f5253,998861276e8357646606634656f062:ec69,5ed39614578362c955878721814a8fa3556683b167658d5684dd5a6a680f62e67bee961151706f9c8c3063fd89c861d27f0670c26ee57405699472fc5eca90ce67176d6a635e52b3726280014f6c59e5916a70d96d9d52d24e5096f7956d857e78ca7d2f5121579264c2808b7c7b6cea68f1695e51b7539868a872819ece7bf172f879bb6f137406674e91cc9ca4793c83:8954,540f68174e3d538952b1783e5386522950884f:8bd0,7f:56595b5c5d5e6063646566676b6c6d6f7073757677787a7b7c7d7f8082838485868788898b8d8f9091929395969798999b9ca0a2a3a5a6a8a9aaabacadaeb1#b3b4b5b6b7babbbec0c2c3c4c6c7c8c9cbcdcfd0d1d2d3d6d7d9dadbdcdddee2e3,75e27acb7c926ca596b6529b748354e94fe9805483b28fde95705ec9601c6d9f5e18655b813894fe604b70bc7ec37cae51c968817cb1826f4e248f8691cf667e4eae8c0564a9804a50da759771ce5be58fbd6f664e86648295635ed66599521788c270c852a3730e7433679778f797164e3490bb9cde6dcb51db8d41541d62ce73b283f196f69f8494c34f367f9a51cc707596755cad988653e64ee46e9c740969b4786b998f7559521876246d4167f3516d9f99804b54997b3c7abf7f:e4e7e8eaebecedeff2f4f5f6f7f8f9fafdfeff,80:020708090a0e0f11131a1b1d1e1f2123242b2c2d2e2f303234393a3c3e404144454748494e4f505153555657#595b5c5d5e5f6061626364656667686b6c6d6e6f7072737475767778797a7b7c7d,9686578462e29647697c5a0464027bd36f0f964b82a6536298855e90708963b35364864f9c819e93788c97328d:ef42,9e7f6f5e79845f559646622e9a74541594dd4fa365c55c:6561,7f1586516c2f5f8b73876ee47eff5ce6631b5b6a6ee653754e7163a0756562a18f6e4f264ed16ca67eb68bba841d87ba7f57903b95237ba99aa188f8843d6d1b9a867edc59889ebb739b780186829a:6c82,561b541757cb4e709ea653568fc881097792999286ee6ee1851366fc61626f2b80:7e818285888a8d8e8f909192949597999ea3a6a7a8acb0b3b5b6b8b9bbc5c7c8c9cacbcfd0d1d2d3d4d5d8dfe0e2e3e6eef5f7f9fbfeff,81:000103040507080b#0c1517191b1c1d1f202122232425262728292a2b2d2e3033343537393a3b3c3d3f,8c298292832b76f26c135fd983bd732b8305951a6bdb77db94c6536f830251925e3d8c8c8d384e4873ab679a68859176970971646ca177095a9295416bcf7f8e66275bd059b95a9a95:e8f7,4eec84:0c99,6aac76df9530731b68a65b5f772f919a97617cdc8ff78c1c5f257c7379d889c56ccc871c5bc65e4268c977207ef551:954d,52c95a297f05976282d763cf778485d079d26e3a5e9959998511706d6c1162bf76bf654f60af95fd660e879f9e2394ed54:0d7d,8c2c647881:40414243444547494d4e4f525657585b5c5d5e5f6162636466686a6b6c6f727375767778818384858687898b8c8d8e90929394959697999a9e9fa0a1a2a4a5#a7a9abacadaeafb0b1b2b4b5b6b7b8b9bcbdbebfc4c5c7c8c9cbcdcecfd0d1d2d3,647986116a21819c78e864699b5462b9672b83ab58a89ed86cab6f205bde964c8c0b725f67d062c772614ea959c66bcd589366ae5e5552df6155672876ee776672677a4662ff54:ea50,94a090a35a1c7eb36c164e435976801059485357753796be56ca63208111607c95f96dd65462998151855ae980fd59ae9713502a6ce55c3c62df4f60533f817b90066eba852b62c85e7478be64b5637b5ff55a18917f9e1f5c3f634f80425b7d556e95:4a4d,6d8560a867e072de51dd5b8181:d4d5d6d7d8d9dadbdcdddedfe0e1e2e4e5e6e8e9ebeeeff0f1f2f5f6f7f8f9fafdff,82:030708090a0b0e0f111315161718191a1d2024252627292e323a3c3d3f#404142434546484a4c4d4e5051525354555657595b5c5d5e606162636465666769,62e76cde725b626d94ae7ebd81136d53519c5f04597452aa6012597366968650759f632a61e67cef8bfa54e66b279e256bb485d5545550766ca4556a8db4722c5e156015743662cd6392724c5f986e436d3e65006f5876d878d076fc7554522453db4e535e9e65c180:2ad6,629b5486522870ae888d8dd16ce1547880da57f988f48d54966a914d4f696c9b55b776c6783062a870f96f8e5f6d84ec68da787c7bf781a8670b9e4f636778b0576f7812973962:79ab,528874356bd782:6a6b6c6d71757677787b7c808183858687898c90939495969a9b9ea0a2a3a7b2b5b6babbbcbfc0c2c3c5c6c9d0d6d9dadde2e7e8e9eaecedeef0f2f3f5f6f8#fafcfdfeff,83:000a0b0d1012131618191d1e1f20212223242526292a2e3032373b3d,5564813e75b276ae533975de50fb5c418b6c7bc7504f72479a9798d86f0274e27968648777a562fc98918d2b54c180584e52576a82f9840d5e7351ed74f68bc45c4f57616cfc98875a4678349b448feb7c955256625194fa4ec68386846183e984b257d467345703666e6d668c3166dd7011671f6b3a6816621a59bb4e0351c46f0667d26c8f517668cb59476b6775665d0e81109f5065d779:4841,9a918d775c824e5e4f01542f5951780c56686c148fc45f036c:7de3,8bab639083:3e3f41424445484a4b4c4d4e5355565758595d6270717273747576797a7e7f808182838487888a8b8c8d8f909194959697999a9d9fa1a2a3a4a5a6a7acadae#afb5bbbebfc2c3c4c6c8c9cbcdced0d1d2d3d5d7d9dadbdee2e3e4e6e7e8ebeced,60706d3d7275626694:8ec5,53438fc17b7e4edf8c264e7e9ed494:b1b3,524d6f5c90636d458c3458115d4c6b:2049,67aa545b81547f8c589985375f3a62a26a47953965726084686577a74e544fa85de7979864ac7fd85ced4fcf7a8d520783044e14602f7a8394a64fb54eb279e6743452e482b964d279bd5bdd6c8197528f7b6c22503e537f6e0564ce66746c3060c598778bf75e86743c7a7779cb4e1890b174036c4256da914b6cc58d8b533a86c666f28eaf5c489a716e2083:eeeff3f4f5f6f7fafbfcfeff,84:0002050708090a10121314151617191a1b1e1f20212223292a2b2c2d2e2f30323334353637393a3b3e3f404142434445474849#4a4b4c4d4e4f505253545556585d5e5f606264656667686a6e6f70727477797b7c,53d65a369f8b8da353bb570898a76743919b6cc9516875ca62f372ac52:389d,7f3a7094763853749e4a69b7786e96c088d97fa471:36c3,518967d374e458e4651856b78ba9997662707ed560f970ed58ec4e:c1ba,5fcd97e74efb8ba45203598a7eab62544ecd65e5620e833884c98363878d71946eb65bb97ed2519763c967d480898339881551125b7a59828fb14e736c5d516589258f6f962e854a745e95:10f0,6da682e55f3164926d128428816e9cc3585e8d5b4e0953c184:7d7e7f8081838485868a8d8f90919293949596989a9b9d9e9fa0a2a3a4a5a6a7a8a9aaabacadaeb0b1b3b5b6b7bbbcbec0c2c3c5c6c7c8cbcccecfd2d4d5d7#d8d9dadbdcdee1e2e4e7e8e9eaebedeeeff1f2f3f4f5f6f7f8f9fafbfdfe,85:000102,4f1e6563685155d34e2764149a9a626b5ac2745f82726da968ee50e7838e7802674052396c997eb150bb5565715e7b5b665273ca82eb67495c715220717d886b95ea965564c58d6181b355846c5562477f2e58924f2455468d4f664c4e0a5c1a88f368a2634e7a0d70e7828d52fa97f65c1154e890b57ecd59628d4a86c782:0c0d,8d6664445c0461516d89793e8bbe78377533547b4f388eab6df15a207ec5795e6c885ba15a76751a80be614e6e1758f075:1f25,727253477ef385:030405060708090a0b0d0e0f101214151618191b1c1d1e2022232425262728292a2d2e2f303132333435363e3f404142444546474b4c4d4e4f505152535455#57585a5b5c5d5f60616263656667696a6b6c6d6e6f707173757677787c7d7f8081,770176db526980dc57235e08593172ee65bd6e7f8bd75c388671534177f362fe65f64ec098df86805b9e8bc653f277e24f7f5c4e9a7659cb5f0f793a58eb4e1667ff4e8b62ed8a93901d52bf662f55dc566c90024ed54f8d91ca99706c0f5e0260435ba489c68bd56536624b99965b:88ff,6388552e53d77626517d852c67a268b36b8a62928f9353d482126dd1758f4e668d4e5b70719f85af66:91d9,7f7287009ecd9f205c5e672f8ff06811675f620d7ad658855eb665706f3185:82838688898a8b8c8d8e909192939495969798999a9d9e9fa0a1a2a3a5a6a7a9abacadb1b2b3b4b5b6b8babbbcbdbebfc0c2c3c4c5c6c7c8cacbcccdced1d2#d4d6d7d8d9dadbdddedfe0e1e2e3e5e6e7e8eaebecedeeeff0f1f2f3f4f5f6f7f8,60555237800d6454887075295e05681362f4971c53cc723d8c016c3477617a0e542e77ac987a821c8bf47855671470c165af64955636601d79c153f84e1d6b7b80865bfa55e356db4f:3a3c,99725df3677e80386002988290015b8b8b:bcf5,641c825864de55fd82cf91654fd77d20901f7c9f50f358516eaf5bbf8bc980839178849c7b97867d96:8b8f,7ee59ad3788e5c817a57904296a7795f5b59635f7b0b84d168ad55067f2974107d2295016240584c4ed65b835979585485:f9fafcfdfe,86:0001020304060708090a0b0c0d0e0f10121314151718191a1b1c1d1e1f20212223242526282a2b2c2d2e2f3031323334353637393a3b3d3e3f40#4142434445464748494a4b4c525355565758595b5c5d5f6061636465666768696a,736d631e8e:4b0f,80ce82d462ac53f06cf0915e592a60016c70574d644a8d2a762b6ee9575b6a8075f06f6d8c:2d08,57666bef889278b363a253f970ad6c645858642a580268e0819b55107cd650188eba6dcc8d9f70eb638f6d9b6ed47ee68404684390036dd896768ba85957727985e4817e75bc8a8a68af52548e22951163d098988e44557c4f5366ff568f60d56d9552435c4959296dfb586b75:301c,606c82148146631167618fe2773a8d:f334,94c15e165385542c70c386:6d6f7072737475767778838485868788898e8f90919294969798999a9b9e9fa0a1a2a5a6abadaeb2b3b7b8b9bbbcbdbebfc1c2c3c5c8cccdd2d3d5d6d7dadc#dde0e1e2e3e5e6e7e8eaebeceff5f6f7fafbfcfdff,87:010405060b0c0e0f10111416,6c405ef7505c4ead5ead633a8247901a6850916e77b3540c94dc5f647ae5687663457b527edf75db507762955934900f51f879c37a8156fe5f9290146d825c60571f541051546e4d56e263a89893817f8715892a9000541e5c6f81c062:d658,81319e3596409a:6e7c,692d59a562d3553e631654c786d96d3c5a0374e6889c6b6a59168c4c5f2f6e7e73a9987d4e3870f75b8c7897633d665a769660cb5b9b5a494e0781556c6a738b4ea167897f515f8065fa671b5fd859845a0187:191b1d1f20242627282a2b2c2d2f303233353638393a3c3d404142434445464a4b4d4f505152545556585a5b5c5d5e5f6162666768696a6b6c6d6f71727375#7778797a7f8081848687898a8c8e8f90919294959698999a9b9c9d9ea0a1a2a3a4,5dcd5fae537197e68fdd684556f4552f60df4e3a6f4d7ef482c7840e59d44f:1f2a,5c3e7eac672a851a5473754f80c355829b4f4f4d6e2d8c135c096170536b761f6e29868a658795fb7eb9543b7a337d0a95ee55e17fc174ee631d87176da17a9d621165a1536763e16c835deb545c94a84e4c6c618bec5c4b65e0829c68a754:3e34,6b:cb66,4e9463425348821e4f:0dae,575e620a96fe6664726952:ffa1,609f8bef661471996790897f785277fd6670563b54389521727a87:a5a6a7a9aaaeb0b1b2b4b6b7b8b9bbbcbebfc1c2c3c4c5c7c8c9cccdcecfd0d4d5d6d7d8d9dadcdddedfe1e2e3e4e6e7e8e9ebecedeff0f1f2f3f4f5f6f7f8#fafbfcfdff,88:0001020405060708090b0c0d0e0f101112141718191a1c1d1e1f2023,7a00606f5e0c6089819d591560dc718470ef6eaa6c5072806a8488ad5e2d4e605ab3559c94e36d177cfb9699620f7ec6778e867e5323971e8f9666875ce14fa072ed4e0b53a6590f54136380952851484ed99c9c7ea454b88d248854823795f26d8e5f265acc663e966973:b02e,53bf817a99857fa15baa96:7750,7ebf76f853a2957699997bb189446e584e617fd479658be660f354cd4eab98795df76a6150cf54118c618427785d9704524a54ee56a395006d885bb56dc6665388:2425262728292a2b2c2d2e2f30313334353637383a3b3d3e3f414243464748494a4b4e4f505152535556585a5b5c5d5e5f6066676a6d6f717374757678797a#7b7c80838687898a8c8e8f90919394959798999a9b9d9e9fa0a1a3a5a6a7a8a9aa,5c0f5b5d6821809655787b11654869544e9b6b47874e978b534f631f643a90aa659c80c18c10519968b0537887f961c86c:c4fb,8c225c5185aa82af950c6b238f9b65b05f:fbc3,4fe18845661f8165732960fa51745211578b5f6290a2884c91925e78674f602759d351:44f6,80f853086c7996c4718a4f:11ee,7f9e673d55c5950879c088967ee3589f620c9700865a5618987b5f908bb884c4915753d965ed5e8f755c60647d6e5a7f7e:eaed,8f6955a75ba360ac65cb738488:acaeafb0b2b3b4b5b6b8b9babbbdbebfc0c3c4c7c8cacbcccdcfd0d1d3d6d7dadbdcdddee0e1e6e7e9eaebecedeeeff2f5f6f7fafbfdff,89:0001030405060708#090b0c0d0e0f1114151617181c1d1e1f20222324262728292c2d2e2f3132333537,9009766377297eda9774859b5b667a7496ea884052cb718f5faa65ec8be25bfb9a6f5de16b896c5b8b:adaf,900a8fc5538b62bc9e:262d,54404e2b82bd7259869c5d1688596daf96c554d14e9a8bb6710954bd960970df6df976d04e25781487125ca95ef68a00989c960e708e6cbf594463a9773c884d6f148273583071d5538c781a96c155015f6671305bb48c1a9a8c6b83592e9e2f79e76768626c4f6f75a17f8a6d0b96336c274ef075d2517b68376f3e908081705996747689:38393a3b3c3d3e3f40424345464748494a4b4c4d4e4f505152535455565758595a5b5c5d6061626364656768696a6b6c6d6e6f707172737475767778797a7c#7d7e808284858788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1,64475c2790657a918c2359da54ac8200836f898180006930564e8036723791ce51b64e5f987563964e1a53f666f3814b591c6db24e0058f9533b63d694f14f:9d0a,886398905937905779fb4eea80f075916c825b9c59e85f5d69058681501a5df24e5977e34ee5827a6291661390915c794ebf5f7981c69038808475ab4ea688d4610f6bc55fc64e4976ca6ea28b:e3ae,8c0a8bd15f027f:fccc,7ece83:356b,56e06bb797f3963459fb541f94f66deb5bc5996e5c395f15969089:a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c3cdd3d4d5d7d8d9dbdddfe0e1e2e4e7e8e9eaecedeef0f1f2f4f5f6f7f8f9fa#fbfcfdfeff,8a:01020304050608090a0b0c0d0e0f101112131415161718191a1b1c1d,537082f16a315a749e705e947f2883b984:2425,836787478fce8d6276c85f719896786c662054df62e54f6381c375c85eb896cd8e0a86f9548f6cf36d8c6c38607f52c775285e7d4f1860a05fe75c24753190ae94c072b96cb96e389149670953:cbf3,4f5191c98bf153c85e7c8fc26de44e8e76c26986865e611a82064f:59de,903e9c7c61096e:1d14,96854e885a3196e84e0e5c7f79b95b878bed7fbd738957df828b90c15401904755bb5cea5fa161086b3272f180b28a:891e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3f4041424344454647494a4b4c4d4e4f505152535455565758595a5b5c5d5e#5f606162636465666768696a6b6c6d6e6f7071727374757677787a7b7c7d7e7f80,6d745bd388d598848c6b9a6d9e336e0a51:a443,57a38881539f63f48f9556ed54585706733f6e907f188fdc82d1613f6028966266f07ea68d:8ac3,94a55cb37ca4670860a6960580184e9190e75300966851418fd08574915d665597f55b55531d78386742683d54c9707e5bb08f7d518d572854b1651266828d:5e43,810f846c906d7cdf51ff85fb67a365e96fa186a48e81566a90207682707671e58d2362e952196cfd8d3c600e589e618e66fe8d60624e55b36e23672d8f678a:81828384858687888b8c8d8e8f9091929495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2#c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3,94e195f87728680569a8548b4e4d70b88bc86458658b5b857a84503a5be877bb6be18a797c986cbe76cf65a98f975d2d5c5586386808536062187ad96e5b7efd6a1f7ae05f706f335f20638c6da867564e085e108d264ed780c07634969c62db662d627e6cbc8d7571677f695146808753ec906e629854f286f08f998005951785178fd96d5973cd659f771f7504782781fb8d1e94884fa6679575b98bca9707632f9547963584b8632377415f8172f04e896014657462ef6b63653f8a:e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,8b:0001020304050608090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20212223#24252728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445,5e2775c790d18bc1829d679d652f5431871877e580a281026c414e4b7ec7804c76f4690d6b966267503c4f84574063076b628dbe53ea65e87eb85fd763:1ab7,81:f3f4,7f6e5e1c5cd95236667a79e97a1a8d28709975d46ede6cbb7a924e2d76c55fe0949f88777ec879cd80bf91cd4ef24f17821f54685dde6d328bcc7ca58f7480985e1a549276b15b99663c9aa473e0682a86db6731732a8b:f8db,90107af970db716e62c477a956314e3b845767f152a986c08d2e94f87b518b:464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f6061626364656768696a6b6d6e6f707172737475767778797a7b7c7d7e7f80818283848586#8788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9facb1bbc7d0ea,8c:091e,4f4f6ce8795d9a7b6293722a62fd4e1378168f6c64b08d5a7bc668695e8488c55986649e58ee72b6690e95258ffd8d5857607f008c0651c6634962d95353684c74228301914c55447740707c6d4a517954a88d4459ff6ecb6dc45b5c7d2b4ed47c7d6ed35b5081ea6e0d5b579b0368d58e2a5b977efc603b7eb590b98d70594f63cd79df8db3535265cf79568bc5963b7ec494bb7e825634918967007f6a5c0a907566285de64f5067de505a4f5c57505e:a7#3$,8c:38393a3b3c3d3e3f4042434445484a4b4d4e4f5051525354565758595b5c5d5e5f60636465666768696c6d6e6f707172747576777b7c7d7e7f808183848687#888b8d8e8f90919293959697999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacad,4e:8d0c,51404e105eff53454e:15981e,9b325b6c56694e2879ba4e3f53154e47592d723b536e6c1056df80e499976bd3777e9f174e:369f,9f104e:5c6993,82885b5b556c560f4ec453:8d9da3a5ae,97658d5d53:1af5262e3e,8d5c53:6663,52:02080e2d333f404c5e615c,84af52:7d82819093,51827f544e:bbc3c9c2e8e1ebde,4f1b4ef34f:2264,4ef54f:2527092b5e67,65384f:5a5d,8c:aeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebec#edeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,8d:000102030405060708090a0b0c0d,4f:5f57323d76749189838f7e7baa7cac94e6e8eac5dae3dcd1dff8,50:294c,4ff350:2c0f2e2d,4ffe50:1c0c25287e4355484e6c7ba5a7a9bad6,510650:edece6ee,51:070b,4edd6c3d4f:5865ce,9fa06c467c74516e5dfd9ec999985181591452f9530d8a07531051eb591951554ea051564eb388:6ea4,4eb5811488d279805b3488037fb851:abb1bdbc,8d:0e0f101112131415161718191a1b1c205152575f6568696a6c6e6f717278797a7b7c7d7e7f808283868788898c8d8e8f90929395969798999a9b9c9d9ea0a1#a2a4a5a6a7a8a9aaabacadaeafb0b2b6b7b9bbbdc0c1c2c5c7c8c9cacdd0d2d3d4,51:c796a2a5,8b:a0a6a7aab4b5b7c2c3cbcfced2d3d4d6d8d9dcdfe0e4e8e9eef0f3f6f9fcff,8c:000204070c0f1112141516191b181d1f202125272a2b2e2f32333536,53:697a,96:1d2221312a3d3c4249545f676c7274888d97b0,90:979b9d99aca1b4b3b6ba,8d:d5d8d9dce0e1e2e5e6e7e9edeef0f1f2f4f6fcfeff,8e:00010203040607080b0d0e1011121315161718191a1b1c202124252627282b2d303233343637383b3c3e#3f4345464c4d4e4f505354555657585a5b5c5d5e5f60616263646567686a6b6e71,90:b8b0cfc5bed0c4c7d3e6e2dcd7dbebeffe,91:04221e23312f394346,520d594252:a2acadbe,54ff52:d0d6f0,53df71ee77cd5ef451:f5fc,9b2f53b65f01755a5def57:4ca9a1,58:7ebcc5d1,57:292c2a33392e2f5c3b4269856b867c7b686d7673ada48cb2cfa7b493a0d5d8dad9d2b8f4eff8e4dd,8e:73757778797a7b7d7e808283848688898a8b8c8d8e91929395969798999a9b9d9fa0a1a2a3a4a5a6a7a8a9aaadaeb0b1b3b4b5b6b7b8b9bbbcbdbebfc0c1c2#c3c4c5c6c7c8c9cacbcccdcfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4,58:0b0d,57:fded,58:001e194420656c81899a80,99a89f1961ff82:797d7f8f8aa8848e919799abb8beb0c8cae398b7aecbccc1a9b4a1aa9fc4cea4e1,830982:f7e4,83:0f07,82:dcf4d2d8,830c82:fbd3,83:111a061415,82:e0d5,83:1c515b5c08923c34319b5e2f4f47435f4017602d3a336665,8e:e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,8f:000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20212223#2425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f4041424344,83:681b696c6a6d6eb078b3b4a0aa939c857cb6a97db87b989ea8babcc1,840183:e5d8,580784:180b,83:ddfdd6,84:1c381106,83:d4df,84:0f03,83:f8f9eac5c0,842683:f0e1,84:5c515a597387887a89783c4669768c8e316dc1cdd0e6bdd3cabfbae0a1b9b497e5e3,850c750d853884f085:391f3a,8f:45464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f6061626364656a808c929da0a1a2a4a5a6a7aaacadaeafb2b3b4b5b7b8babbbcbfc0c3c6#c9cacbcccdcfd2d6d7dae0e1e3e7eceff1f2f4f5f6fafbfcfeff,90:07080c0e131518,85:563b,84:fffc,85:594868645e7a,77a285:43727ba4a8878f79ae9c85b9b7b0d3c1dcff,86:270529163c,5efe5f0859:3c41,803759:555a58,530f5c:22252c34,62:4c6a9fbbcadad7ee,632262f663:394b43adf6717a8eb46dac8a69aebcf2f8e0ffc4dece,645263:c6be,64:45410b1b200c26215e846d96,90:191c2324252728292a2b2c303132333437393a3d3f4043454648494a4b4c4e545556595a5c5d5e5f6061646667696a6b6c6f70717273767778797a7b7c7e81#84858687898a8c8d8e8f90929496989a9c9e9fa0a4a5a7a8a9abadb2b7bcbdbfc0,64:7ab7b899bac0d0d7e4e2,65:09252e,5f:0bd2,75195f1153:5ff1fde9e8fb,54:1216064b5253545643215759233282947771649a9b8476669dd0adc2b4d2a7a6d3d472a3d5bbbfccd9dadca9aaa4ddcfde,551b54e7552054fd551454f355:22230f11272a678fb5496d41553f503c,90:c2c3c6c8c9cbcccdd2d4d5d6d8d9dadedfe0e3e4e5e9eaeceef0f1f2f3f5f6f7f9fafbfcff,91:00010305060708090a0b0c0d0e0f1011121314151617181a1b1c#1d1f20212425262728292a2b2c2d2e30323334353637383a3b3c3d3e3f40414244,55:375675767733305c8bd283b1b988819f7ed6917bdfbdbe9499eaf7c9,561f55:d1ebecd4e6ddc4efe5f2f3cccde8f5e4,8f9456:1e080c012423,55fe56:00272d5839572c4d62595c4c548664716b7b7c8593afd4d7dde1f5ebf9ff,57:040a091c,5e:0f191411313b3c,91:454748515354555658595b5c5f606667686b6d737a7b7c808182838486888a8e8f939495969798999c9d9e9fa0a1a4a5a6a7a8a9abacb0b1b2b3b6b7b8b9bb#bcbdbebfc0c1c2c3c4c5c6c8cbd0d2d3d4d5d6d7d8d9dadbdddedfe0e1e2e3e4e5,5e:3744545b5e61,5c:8c7a8d9096889899919a9cb5a2bdacabb1a3c1b7c4d2e4cbe5,5d:020327262e241e061b583e343d6c5b6f5d6b4b4a697482999d,8c735d:b7c5,5f:73778287898c95999ca8adb5bc,88625f6172:adb0b4b7b8c3c1cecdd2e8efe9f2f4f7,730172f3730372fa91:e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,92:000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2021222324#25262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445,72fb73:1713210a1e1d152239252c3831504d57606c6f7e,821b592598e759:2402,99:636768696a6b6c74777d8084878a8d9091939495,5e:80918b96a5a0b9b5beb3,8d535e:d2d1dbe8ea,81ba5f:c4c9d6cf,60035fee60045f:e1e4fe,60:0506,5f:eaedf8,60:1935261b0f0d292b0a3f2178797b7a42,92:464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f7071727375767778797a7b7c7d7e7f808182838485#868788898a8b8c8d8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7,60:6a7d969aad9d83928c9becbbb1ddd8c6dab4,61:20261523,60f461:000e2b4a75ac94a7b7d4f5,5fdd96b395:e9ebf1f3f5f6fcfe,96:030406080a0b0c0d0f12151617191a,4e2c723f62156c:35545c4aa38590948c6869747686a9d0d4adf7f8f1d7b2e0d6faebeeb1d3effe,92:a8a9aaabacadafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8#e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,93:00010203040506070809,6d:39270c43480704190e2b4d2e351a4f525433916f9ea05e93945c607c63,6e1a6d:c7c5de,6e0e6d:bfe0,6e116d:e6ddd9,6e166dab6e0c6dae6e:2b6e4e6bb25f865354322544dfb198e0,6f2d6e:e2a5a7bdbbb7d7b4cf8fc29f,6f:6246472415,6ef96f:2f364b742a0929898d8c78727c7ad1,93:0a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3f40414243444546474849#4a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696b,6f:c9a7b9b6c2e1eedee0ef,70:1a231b39354f5e,5b:80849593a5b8,752f9a9e64345b:e4ee,89305bf08e478b078f:b6d3d5e5eee4e9e6f3e8,90:05040b26110d162135362d2f445152506858625b,66b990:747d8288838b,5f:50575658,5c3b54ab5c:5059,5b715c:6366,7fbc5f:2a292d,82745f3c9b3b5c6e59:81838da9aaa3,93:6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaab#acadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cbcccd,59:97caab9ea4d2b2afd7be,5a:0506,59dd5a0859:e3d8f9,5a:0c09323411231340674a553c6275,80ec5a:aa9b777abeebb2d2d4b8e0e3f1d6e6d8dc,5b:091716323740,5c:151c,5b:5a6573515362,9a:7577787a7f7d808185888a90929396989b9c9d9fa0a2a3a5a7,7e:9fa1a3a5a8a9,93:cecfd0d1d2d3d4d5d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,94:000102030405060708090a0b0c0d#0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e,7e:adb0bec0c1c2c9cbccd0d4d7dbe0e1e8ebeeeff1f2,7f0d7e:f6fafbfe,7f:01020307080b0c0f111217191c1b1f212223242526272a2b2c2d2f3031323335,5e7a757f5ddb753e909573:8e91aea29fcfc2d1b7b3c0c9c8e5d9,987c740a73:e9e7debaf2,74:0f2a5b262528302e2c,94:2f303132333435363738393a3b3c3d3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6c6d6e6f#707172737475767778797a7b7c7d7e7f8081828384919698c7cfd3d4dae6fb,95:1c20,74:1b1a415c575559776d7e9c8e8081878b9ea8a990a7d2ba,97:eaebec,67:4c535e4869a5876a7398a775a89ead8b777cf0,680967d8680a67:e9b0,680c67:d9b5dab3dd,680067:c3b8e2,680e67:c1fd,68:323360614e624464831d55664167403e4a4929b58f7477936bc2,696e68fc69:1f20,68f995:27333d43484b555a606e74757778797a7b7c7d7e808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aa#abacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacb,692468f069:0b0157,68e369:10713960425d846b80987834cc8788ce896663799ba7bbabadd4b1c1cadf95e08dff,6a2f69ed6a:171865,69f26a:443ea0505b358e793d28587c9190a997ab,73:3752,6b:8182878492938d9a9ba1aa,8f:6b6d71727375767877797a7c7e818284878b,95:cccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7ecff,96:0713181b1e20232425262728292b2c2d2f303738393a3e41434a4e4f5152535657#58595a5c5d5e606365666b6d6e6f70717378797a7b7c7d7e7f808182838487898a,8f:8d8e8f989a,8ece62:0b171b1f222125242c,81e774:eff4ff,75:0f1113,65:34eeeff0,66:0a19,677266:031500,708566:f71d34313635,800666:5f54414f56615777848ca79dbedbdce6e9,8d:3233363b3d4045464849474d5559,89:c7cacbcccecfd0d1,72:6e9f5d666f7e7f848b8d8f92,63:0832b0,96:8c8e91929395969a9b9d9e9fa0a1a2a3a4a5a6a8a9aaabacadaeafb1b2b4b5b7b8babbbfc2c3c8cacbd0d1d3d4d6d7d8d9dadbdcdddedfe1e2e3e4e5e6e7eb#ecedeef0f1f2f4f5f8fafbfcfdff,97:0203050a0b0c10111214151718191a1b1d1f20,64:3fd8,80046b:eaf3fdf5f9,6c:0507060d1518191a2129242a32,65:35556b,72:4d525630,8662521680:9f9c93bc,670a80:bdb1abadb4b7e7e8e9eadbc2c4d9cdd7,671080:ddebf1f4ed,81:0d0e,80:f2fc,671581128c5a81:361e2c1832484c5374595a7160697c7d6d67,584d5ab581:888291,6ed581:a3aacc,672681:cabb,97:2122232425262728292b2c2e2f3133343536373a3b3c3d3f404142434445464748494a4b4c4d4e4f5051545557585a5c5d5f63646667686a6b6c6d6e6f7071#72757778797a7b7d7e7f8081828384868788898a8c8e8f9093959697999a9b9c9d,81:c1a6,6b:243739434659,98:d1d2d3d5d9da,6bb35f406bc289f365909f5165:93bcc6c4c3ccced2d6,70:809c969dbbc0b7abb1e8ca,71:1013162f31735c6845724a787a98b3b5a8a0e0d4e7f9,72:1d28,706c71:1866b9,62:3e3d434849,79:3b4046495b5c535a6257606f677a858a9aa7b3,5f:d1d0,97:9e9fa1a2a4a5a6a7a8a9aaacaeb0b1b3b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3#e4e5e8eeeff0f1f2f4f7f8f9fafbfcfdfeff,98:000102030405060708090a0b0c0d0e,60:3c5d5a67415963ab,61:060d5da99dcbd1,620680:807f,6c:93f6,6dfc77:f6f8,78:0009171811,65ab78:2d1c1d393a3b1f3c252c23294e6d56572650474c6a9b939a879ca1a3b2b9a5d4d9c9ecf2,790578f479:13241e34,9f9b9e:f9fbfc,76f177:040d,76f977:07081a22192d263538505147435a68,98:0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d#4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e,77:62657f8d7d808c919fa0b0b5bd,75:3a404e4b485b727983,7f:58615f,8a487f:68747179817e,76:cde5,883294:8586878b8a8c8d8f909497959a9b9ca3a4abaaadacafb0b2b4b6b7b8b9babcbdbfc4c8c9cacbcccdced0d1d2d5d6d7d9d8dbdedfe0e2e4e5e7e8ea,98:6f70717273748b8e929599a3a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcfd0d4d6d7dbdcdde0e1e2e3e4#e5e6e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,99:0001020304050607,94:e9ebeeeff3f4f5f7f9fcfdff,95:03020607090a0d0e0f1213141516181b1d1e1f222a2b292c3132343637383c3e3f4235444546494c4e4f525354565758595b5e5f5d61626465666768696a6b6c6f7172733a,77:e7ec,96c979:d5ede3eb,7a065d477a:03021e14,99:08090a0b0c0e0f1112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2f303132333435363738393a3b3c3d3e3f40414243444546474849#4a4b4c4d4e4f50515253565758595a5b5c5d5e5f60616264667378797b7e828389,7a:393751,9ecf99a57a7076:888e9399a4,74:dee0,752c9e:202228292a2b2c3231363837393a3e414244464748494b4c4e5155575a5b5c5e63666768696a6b6c716d73,75:929496a09daca3b3b4b8c4b1b0c3c2d6cde3e8e6e4ebe7,760375:f1fcff,76:1000050c170a25181519,99:8c8e9a9b9c9d9e9fa0a1a2a3a4a6a7a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8#d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9,76:1b3c2220402d303f35433e334d5e545c566b6f,7fca7a:e6787980868895a6a0aca8adb3,88:6469727d7f82a2c6b7bcc9e2cee3e5f1,891a88:fce8fef0,89:2119131b0a342b3641667b,758b80e576:b2b4,77dc80:1214161c20222526272928310b3543464d526971,898398:788083,99:fafbfcfdfeff,9a:000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738#393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f50515253545556575859,98:898c8d8f949a9b9e9fa1a2a5a6,86:4d546c6e7f7a7c7ba88d8bac9da7a3aa93a9b6c4b5ceb0bab1afc9cfb4e9f1f2edf3d0,871386:def4dfd8d1,87:0307,86f887:080a0d09233b1e252e1a3e48343129373f82227d7e7b60704c6e8b53637c64596593afa8d2,9a:5a5b5c5d5e5f606162636465666768696a6b7283898d8e949599a6a9aaabacadaeafb2b3b4b5b9bbbdbebfc3c4c6c7c8c9cacdcecfd0d2d4d5d6d7d9dadbdc#dddee0e2e3e4e5e7e8e9eaeceef0f1f2f3f4f5f6f7f8fafcfdfeff,9b:000102040506,87:c68885ad9783abe5acb5b3cbd3bdd1c0cadbeae0ee,88:1613,87fe88:0a1b21393c,7f:36424445,82107a:fafd,7b:080304150a2b0f47382a192e31202524333e1e585a45754c5d606e7b62727190a6a7b8ac9da885aa9ca2abb4d1c1ccdddae5e6ea,7c0c7b:fefc,7c:0f160b,9b:07090a0b0c0d0e1011121415161718191a1b1c1d1e2021222425262728292a2b2c2d2e3031333435363738393a3d3e3f40464a4b4c4e50525355565758595a#5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b,7c:1f2a26384140,81fe82:010204,81ec884482:2122232d2f282b383b33343e44494b4f5a5f68,88:7e8588d8df,895e7f:9d9fa7afb0b2,7c7c65497c:919d9c9ea2b2bcbdc1c7cccdc8c5d7e8,826e66a87f:bfced5e5e1e6e9eef3,7cf87d:77a6ae,7e:479b,9e:b8b4,8d:73849491b1676d,8c:4749,91:4a504e4f64,9b:7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9ba#bbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadb,91:626170696f7d7e7274798c85908d91a2a3aaadaeafb5b4ba,8c559e7e8d:b8eb,8e:055969,8d:b5bfbcbac4d6d7dadececfdbc6ecf7f8e3f9fbe4,8e098dfd8e:141d1f2c2e232f3a4039353d3149414251524a70767c6f74858f94909c9e,8c:78828a859894,659b89:d6dedadc,9b:dcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,9c:000102030405060708090a0b0c0d0e0f101112131415161718191a#1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b,89:e5ebef,8a3e8b26975396:e9f3ef,97:0601080f0e2a2d303e,9f:808385868788898a8c,9efe9f:0b0d,96:b9bcbdced2,77bf96e092:8eaec8,93:3e6aca8f,94:3e6b,9c:7f8285868788,7a239c:8b8e90919294959a9b9e9fa0a1a2a3a5a6a7a8a9abadaeb0b1b2b3b4b5b6b7babbbcbdc4c5c6c7cacb3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a#7b7d7e808384898a8c8f93969798999daaacafb9bebfc0c1c2c8c9d1d2dadbe0e1cccdcecfd0d3d4d5d7d8d9dcdddfe2,97:7c85919294afaba3b2b4,9a:b1b0b7,9e589a:b6babcc1c0c5c2cbccd1,9b:45434749484d51,98e899:0d2e5554,9a:dfe1e6efebfbedf9,9b:080f131f23,9e:bdbe,7e3b9e:8287888b92,93d69e:9d9fdbdcdde0dfe2e9e7e5eaef,9f:222c2f39373d3e44,9c:e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,9d:000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2021#22232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142#92$434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f8081#82838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2#92$a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1#e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff,9e:000102#92$030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e24272e30343b3c404d5052535456595d5f606162656e6f727475767778797a7b7c7d80#8183848586898a8c8d8e8f90919495969798999a9b9c9ea0a1a2a3a4a5a7a8a9aa#92$abacadaeafb0b1b2b3b5b6b7b9babcbfc0c1c2c3c5c6c7c8cacbccd0d2d3d5d6d7d9dadee1e3e4e6e8ebecedeef0f1f2f3f4f5f6f7f8fafdff,9f:000102030405#060708090a0c0f1112141516181a1b1c1d1e1f21232425262728292a2b2d2e3031#92$3233343536383a3c3f4041424345464748494a4b4c4d4e4f52535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778#797a7b7c7d7e81828d8e8f9091929394959697989c9d9ea1a2a3a4a5,f9:2c7995e7f1#92$,fa:0c0d0e0f111314181f20212324272829,e8:15161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f40414243#4445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f6061626364");
  135. let index = 0;
  136. this.#data = dataText.match(/..../g);
  137. for (let i = 0x81; i <= 0xfe; i++) {
  138. for (let j = 0x40; j <= 0xfe; j++) {
  139. this.#U2Ghash[this.#data[index++]] = ("%" +
  140. i.toString(16) +
  141. "%" +
  142. j.toString(16)).toUpperCase();
  143. }
  144. }
  145. for (let key in this.#U2Ghash) {
  146. this.#G2Uhash[this.#U2Ghash[key]] = key;
  147. }
  148. }
  149. handleText(text) {
  150. text = text
  151. .replace(/#(\d+)\$/g, function (a, b) {
  152. return Array(+b + 3).join("#");
  153. })
  154. .replace(/#/g, "####")
  155. .replace(/(\w\w):([\w#]+)(?:,|$)/g, function (a, hd, dt) {
  156. return dt.replace(/../g, function (a) {
  157. if (a != "##") {
  158. return hd + a;
  159. }
  160. else {
  161. return a;
  162. }
  163. });
  164. });
  165. return text;
  166. }
  167. isAscii(unicode) {
  168. return unicode <= 0x007f && unicode >= 0x0000;
  169. }
  170. /**
  171. * 编码
  172. * @param str
  173. */
  174. encode(str) {
  175. let that = this;
  176. return [...str].reduce((result, val, i) => {
  177. return result + toGBK(val);
  178. }, "");
  179. function toGBK(val) {
  180. let result = "";
  181. for (let i = 0; i < val.length; i++) {
  182. const codePoint = val.codePointAt(i);
  183. const code = String.fromCodePoint(codePoint);
  184. let key = codePoint.toString(16);
  185. key.length != 4 && (key = ("000" + key).match(/....$/)?.[0]);
  186. /* Add up i by code.length */
  187. i += code.length - 1;
  188. /* If code is in ascii range */
  189. if (that.isAscii(codePoint)) {
  190. result += encodeURIComponent(code);
  191. continue;
  192. }
  193. /* If Got encoded string from U2Ghash */
  194. if (that.#U2Ghash[key]) {
  195. result += that.#U2Ghash[key];
  196. continue;
  197. }
  198. /*
  199. If 2 or more char combines to one visible code,
  200. or just this code is not in GBK
  201. */
  202. result += toGBK(`&#${codePoint};`);
  203. }
  204. return result;
  205. }
  206. }
  207. /**
  208. * 解码
  209. * @param str
  210. */
  211. decode(str) {
  212. var GBKMatcher = /%[0-9A-F]{2}%[0-9A-F]{2}/;
  213. var UTFMatcher = /%[0-9A-F]{2}/;
  214. // @ts-ignore
  215. var utf = true;
  216. let that = this;
  217. while (utf) {
  218. let gbkMatch = str.match(GBKMatcher);
  219. let utfMatch = str.match(UTFMatcher);
  220. utf = Boolean(utfMatch);
  221. if (gbkMatch && gbkMatch in that.#G2Uhash) {
  222. str = str.replace(gbkMatch, String.fromCharCode(("0x" + that.#G2Uhash[gbkMatch])));
  223. }
  224. else {
  225. // @ts-ignore
  226. str = str.replace(utfMatch, decodeURIComponent(utfMatch));
  227. }
  228. }
  229. return str;
  230. }
  231. }
  232.  
  233. class UtilsGMCookie {
  234. windowApi = {
  235. window: window,
  236. document: document,
  237. };
  238. constructor(windowApiOption) {
  239. if (windowApiOption) {
  240. this.windowApi = Object.assign({}, windowApiOption);
  241. }
  242. }
  243. /**
  244. * 获取Cookie分组
  245. */
  246. getCookiesList() {
  247. if (this.windowApi.document.cookie.trim() === "") {
  248. return [];
  249. }
  250. return this.windowApi.document.cookie.split(";");
  251. }
  252. /**
  253. * 获取单个cookie
  254. * @param cookieName cookie名
  255. */
  256. get(cookieName) {
  257. if (typeof cookieName !== "string") {
  258. throw new TypeError("Utils.GMCookie.get 参数cookieName 必须为字符串");
  259. }
  260. let cookies = this.getCookiesList();
  261. let findValue = undefined;
  262. for (const cookieItem of cookies) {
  263. let item = cookieItem.trim();
  264. let itemSplit = item.split("=");
  265. let itemName = itemSplit[0];
  266. itemSplit.splice(0, 1);
  267. let itemValue = decodeURIComponent(itemSplit.join(""));
  268. if (itemName === cookieName) {
  269. findValue = {
  270. domain: this.windowApi.window.location.hostname,
  271. expirationDate: null,
  272. hostOnly: true,
  273. httpOnly: false,
  274. name: cookieName,
  275. path: "/",
  276. sameSite: "unspecified",
  277. secure: true,
  278. session: false,
  279. value: itemValue,
  280. };
  281. break;
  282. }
  283. }
  284. return findValue;
  285. }
  286. /**
  287. * 获取多组Cookie
  288. * @param option 配置
  289. * @param callback 获取操作后的回调
  290. * + cookies object[]
  291. * + error string|undefined
  292. **/
  293. list(option, callback) {
  294. if (option == null) {
  295. throw new Error("Utils.GMCookie.list 参数不能为空");
  296. }
  297. let resultData = [];
  298. try {
  299. let defaultOption = {
  300. url: this.windowApi.window.location.href,
  301. domain: this.windowApi.window.location.hostname,
  302. name: "",
  303. path: "/",
  304. };
  305. defaultOption = utils.assign(defaultOption, option);
  306. let cookies = this.getCookiesList();
  307. cookies.forEach((item) => {
  308. item = item.trim();
  309. let itemSplit = item.split("=");
  310. let itemName = itemSplit[0];
  311. itemSplit.splice(0, 1);
  312. let itemValue = decodeURIComponent(itemSplit.join(""));
  313. let nameRegexp = defaultOption.name instanceof RegExp
  314. ? defaultOption.name
  315. : new RegExp("^" + defaultOption.name, "g");
  316. if (itemName.match(nameRegexp)) {
  317. resultData.push({
  318. domain: this.windowApi.window.location.hostname,
  319. expirationDate: null,
  320. hostOnly: true,
  321. httpOnly: false,
  322. name: itemName,
  323. path: "/",
  324. sameSite: "unspecified",
  325. secure: true,
  326. session: false,
  327. value: itemValue,
  328. });
  329. }
  330. });
  331. if (typeof callback === "function") {
  332. callback(resultData);
  333. }
  334. }
  335. catch (error) {
  336. if (typeof callback === "function") {
  337. callback(resultData, error);
  338. }
  339. }
  340. }
  341. /**
  342. * 获取多组Cookie
  343. * @param option 配置
  344. **/
  345. getList(option) {
  346. if (option == null) {
  347. throw new Error("Utils.GMCookie.list 参数不能为空");
  348. }
  349. let resultData = [];
  350. let defaultOption = {
  351. url: this.windowApi.window.location.href,
  352. domain: this.windowApi.window.location.hostname,
  353. name: "",
  354. path: "/",
  355. };
  356. defaultOption = utils.assign(defaultOption, option);
  357. let cookies = this.getCookiesList();
  358. cookies.forEach((item) => {
  359. item = item.trim();
  360. let itemSplit = item.split("=");
  361. let itemName = itemSplit[0];
  362. itemSplit.splice(0, 1);
  363. let itemValue = decodeURIComponent(itemSplit.join(""));
  364. let nameRegexp = defaultOption.name instanceof RegExp
  365. ? defaultOption.name
  366. : new RegExp("^" + defaultOption.name, "g");
  367. if (itemName.match(nameRegexp)) {
  368. resultData.push({
  369. domain: this.windowApi.window.location.hostname,
  370. expirationDate: null,
  371. hostOnly: true,
  372. httpOnly: false,
  373. name: itemName,
  374. path: "/",
  375. sameSite: "unspecified",
  376. secure: true,
  377. session: false,
  378. value: itemValue,
  379. });
  380. }
  381. });
  382. return resultData;
  383. }
  384. /**
  385. * 设置Cookie
  386. * @param option 配置
  387. * @param callback 设置操作后的回调(成功/失败)
  388. */
  389. set(option, callback) {
  390. let errorInfo;
  391. try {
  392. let defaultOption = {
  393. url: this.windowApi.window.location.href,
  394. name: "",
  395. value: "",
  396. domain: "",
  397. path: "/",
  398. secure: true,
  399. httpOnly: false,
  400. /**
  401. * Expires in 30 days
  402. */
  403. expirationDate: Math.floor(Date.now()) + 60 * 60 * 24 * 30,
  404. };
  405. defaultOption = utils.assign(defaultOption, option);
  406. let life = defaultOption.expirationDate
  407. ? defaultOption.expirationDate
  408. : Math.floor(Date.now()) + 60 * 60 * 24 * 30;
  409. let cookieStr = defaultOption.name +
  410. "=" +
  411. decodeURIComponent(defaultOption.value) +
  412. ";expires=" +
  413. new Date(life).toGMTString() +
  414. "; path=/";
  415. if (utils.isNotNull(defaultOption.domain)) {
  416. cookieStr += "; domain=" + defaultOption.domain;
  417. }
  418. this.windowApi.document.cookie = cookieStr;
  419. }
  420. catch (error) {
  421. errorInfo = error;
  422. }
  423. finally {
  424. if (typeof callback === "function") {
  425. callback(errorInfo);
  426. }
  427. }
  428. }
  429. /**
  430. * 删除Cookie
  431. * @param option 配置
  432. * @param callback 删除操作后的回调(成功/失败)
  433. */
  434. delete(option, callback) {
  435. let errorInfo;
  436. try {
  437. let defaultOption = {
  438. url: this.windowApi.window.location.href,
  439. name: "",
  440. path: "/",
  441. firstPartyDomain: "",
  442. };
  443. defaultOption = utils.assign(defaultOption, option);
  444. let cookieStr = `${defaultOption.name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${defaultOption.path}`;
  445. if (utils.isNotNull(defaultOption.firstPartyDomain)) {
  446. cookieStr += `; domain=${defaultOption.firstPartyDomain};`;
  447. }
  448. this.windowApi.document.cookie = cookieStr;
  449. }
  450. catch (error) {
  451. errorInfo = error;
  452. }
  453. finally {
  454. if (typeof callback === "function") {
  455. callback(errorInfo);
  456. }
  457. }
  458. }
  459. /**
  460. * 解析cookie字符串
  461. * 例如:document.cookie
  462. * @param cookieStr
  463. */
  464. parseCookie(cookieStr) {
  465. if (cookieStr.trim() === "") {
  466. return [];
  467. }
  468. let cookies = cookieStr.split(";");
  469. let result = [];
  470. for (const cookieItem of cookies) {
  471. let item = cookieItem.trim();
  472. let itemSplit = item.split("=");
  473. let itemName = itemSplit[0];
  474. itemSplit.splice(0, 1);
  475. let itemValue = decodeURIComponent(itemSplit.join(""));
  476. result.push({
  477. key: itemName,
  478. value: itemValue,
  479. });
  480. }
  481. return result;
  482. }
  483. }
  484.  
  485. // @name ajaxHooker
  486. // @author cxxjackie
  487. // @version 1.4.4
  488. // @updateLog 修复头条、抖音部分站点下this引用错误的问题。
  489. // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
  490.  
  491. const AjaxHooker = function () {
  492. return (function () {
  493. const version = "1.4.4";
  494. const hookInst = {
  495. hookFns: [],
  496. filters: [],
  497. };
  498. const win = window.unsafeWindow || document.defaultView || window;
  499. let winAh = win.__ajaxHooker;
  500. const resProto = win.Response.prototype;
  501. const xhrResponses = ["response", "responseText", "responseXML"];
  502. const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
  503. const fetchInitProps = [
  504. "method",
  505. "headers",
  506. "body",
  507. "mode",
  508. "credentials",
  509. "cache",
  510. "redirect",
  511. "referrer",
  512. "referrerPolicy",
  513. "integrity",
  514. "keepalive",
  515. "signal",
  516. "priority",
  517. ];
  518. const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
  519. const getType = {}.toString.call.bind({}.toString);
  520. const getDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
  521. const emptyFn = () => {};
  522. const errorFn = (e) => console.error(e);
  523. function isThenable(obj) {
  524. return (
  525. obj &&
  526. ["object", "function"].includes(typeof obj) &&
  527. typeof obj.then === "function"
  528. );
  529. }
  530. function catchError(fn, ...args) {
  531. try {
  532. const result = fn(...args);
  533. if (isThenable(result)) return result.then(null, errorFn);
  534. return result;
  535. } catch (err) {
  536. console.error(err);
  537. }
  538. }
  539. function defineProp(obj, prop, getter, setter) {
  540. Object.defineProperty(obj, prop, {
  541. configurable: true,
  542. enumerable: true,
  543. get: getter,
  544. set: setter,
  545. });
  546. }
  547. function readonly(obj, prop, value = obj[prop]) {
  548. defineProp(obj, prop, () => value, emptyFn);
  549. }
  550. function writable(obj, prop, value = obj[prop]) {
  551. Object.defineProperty(obj, prop, {
  552. configurable: true,
  553. enumerable: true,
  554. writable: true,
  555. value: value,
  556. });
  557. }
  558. function parseHeaders(obj) {
  559. const headers = {};
  560. switch (getType(obj)) {
  561. case "[object String]":
  562. for (const line of obj.trim().split(/[\r\n]+/)) {
  563. const [header, value] = line.split(/\s*:\s*/);
  564. if (!header) break;
  565. const lheader = header.toLowerCase();
  566. headers[lheader] =
  567. lheader in headers ? `${headers[lheader]}, ${value}` : value;
  568. }
  569. break;
  570. case "[object Headers]":
  571. for (const [key, val] of obj) {
  572. headers[key] = val;
  573. }
  574. break;
  575. case "[object Object]":
  576. return { ...obj };
  577. }
  578. return headers;
  579. }
  580. function stopImmediatePropagation() {
  581. this.ajaxHooker_isStopped = true;
  582. }
  583. class SyncThenable {
  584. then(fn) {
  585. fn && fn();
  586. return new SyncThenable();
  587. }
  588. }
  589. class AHRequest {
  590. constructor(request) {
  591. this.request = request;
  592. this.requestClone = { ...this.request };
  593. }
  594. shouldFilter(filters) {
  595. const { type, url, method, async } = this.request;
  596. return (
  597. filters.length &&
  598. !filters.find((obj) => {
  599. switch (true) {
  600. case obj.type && obj.type !== type:
  601. case getType(obj.url) === "[object String]" &&
  602. !url.includes(obj.url):
  603. case getType(obj.url) === "[object RegExp]" && !obj.url.test(url):
  604. case obj.method &&
  605. obj.method.toUpperCase() !== method.toUpperCase():
  606. case "async" in obj && obj.async !== async:
  607. return false;
  608. }
  609. return true;
  610. })
  611. );
  612. }
  613. waitForRequestKeys() {
  614. const requestKeys = ["url", "method", "abort", "headers", "data"];
  615. if (!this.request.async) {
  616. win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
  617. if (this.shouldFilter(filters)) return;
  618. hookFns.forEach((fn) => {
  619. if (getType(fn) === "[object Function]")
  620. catchError(fn, this.request);
  621. });
  622. requestKeys.forEach((key) => {
  623. if (isThenable(this.request[key]))
  624. this.request[key] = this.requestClone[key];
  625. });
  626. });
  627. return new SyncThenable();
  628. }
  629. const promises = [];
  630. win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
  631. if (this.shouldFilter(filters)) return;
  632. promises.push(
  633. Promise.all(hookFns.map((fn) => catchError(fn, this.request))).then(
  634. () =>
  635. Promise.all(
  636. requestKeys.map((key) =>
  637. Promise.resolve(this.request[key]).then(
  638. (val) => (this.request[key] = val),
  639. () => (this.request[key] = this.requestClone[key])
  640. )
  641. )
  642. )
  643. )
  644. );
  645. });
  646. return Promise.all(promises);
  647. }
  648. waitForResponseKeys(response) {
  649. const responseKeys =
  650. this.request.type === "xhr" ? xhrResponses : fetchResponses;
  651. if (!this.request.async) {
  652. if (getType(this.request.response) === "[object Function]") {
  653. catchError(this.request.response, response);
  654. responseKeys.forEach((key) => {
  655. if (
  656. "get" in getDescriptor(response, key) ||
  657. isThenable(response[key])
  658. ) {
  659. delete response[key];
  660. }
  661. });
  662. }
  663. return new SyncThenable();
  664. }
  665. return Promise.resolve(
  666. catchError(this.request.response, response)
  667. ).then(() =>
  668. Promise.all(
  669. responseKeys.map((key) => {
  670. const descriptor = getDescriptor(response, key);
  671. if (descriptor && "value" in descriptor) {
  672. return Promise.resolve(descriptor.value).then(
  673. (val) => (response[key] = val),
  674. () => delete response[key]
  675. );
  676. } else {
  677. delete response[key];
  678. }
  679. })
  680. )
  681. );
  682. }
  683. }
  684. const proxyHandler = {
  685. get(target, prop) {
  686. const descriptor = getDescriptor(target, prop);
  687. if (
  688. descriptor &&
  689. !descriptor.configurable &&
  690. !descriptor.writable &&
  691. !descriptor.get
  692. )
  693. return target[prop];
  694. const ah = target.__ajaxHooker;
  695. if (ah && ah.proxyProps) {
  696. if (prop in ah.proxyProps) {
  697. const pDescriptor = ah.proxyProps[prop];
  698. if ("get" in pDescriptor) return pDescriptor.get();
  699. if (typeof pDescriptor.value === "function")
  700. return pDescriptor.value.bind(ah);
  701. return pDescriptor.value;
  702. }
  703. if (typeof target[prop] === "function")
  704. return target[prop].bind(target);
  705. }
  706. return target[prop];
  707. },
  708. set(target, prop, value) {
  709. const descriptor = getDescriptor(target, prop);
  710. if (
  711. descriptor &&
  712. !descriptor.configurable &&
  713. !descriptor.writable &&
  714. !descriptor.set
  715. )
  716. return true;
  717. const ah = target.__ajaxHooker;
  718. if (ah && ah.proxyProps && prop in ah.proxyProps) {
  719. const pDescriptor = ah.proxyProps[prop];
  720. pDescriptor.set
  721. ? pDescriptor.set(value)
  722. : (pDescriptor.value = value);
  723. } else {
  724. target[prop] = value;
  725. }
  726. return true;
  727. },
  728. };
  729. class XhrHooker {
  730. constructor(xhr) {
  731. const ah = this;
  732. Object.assign(ah, {
  733. originalXhr: xhr,
  734. proxyXhr: new Proxy(xhr, proxyHandler),
  735. resThenable: new SyncThenable(),
  736. proxyProps: {},
  737. proxyEvents: {},
  738. });
  739. xhr.addEventListener("readystatechange", (e) => {
  740. if (
  741. ah.proxyXhr.readyState === 4 &&
  742. ah.request &&
  743. typeof ah.request.response === "function"
  744. ) {
  745. const response = {
  746. finalUrl: ah.proxyXhr.responseURL,
  747. status: ah.proxyXhr.status,
  748. responseHeaders: parseHeaders(
  749. ah.proxyXhr.getAllResponseHeaders()
  750. ),
  751. };
  752. const tempValues = {};
  753. for (const key of xhrResponses) {
  754. try {
  755. tempValues[key] = ah.originalXhr[key];
  756. } catch (err) {}
  757. defineProp(
  758. response,
  759. key,
  760. () => {
  761. return (response[key] = tempValues[key]);
  762. },
  763. (val) => {
  764. delete response[key];
  765. response[key] = val;
  766. }
  767. );
  768. }
  769. ah.resThenable = new AHRequest(ah.request)
  770. .waitForResponseKeys(response)
  771. .then(() => {
  772. for (const key of xhrResponses) {
  773. ah.proxyProps[key] = {
  774. get: () => {
  775. if (!(key in response)) response[key] = tempValues[key];
  776. return response[key];
  777. },
  778. };
  779. }
  780. });
  781. }
  782. ah.dispatchEvent(e);
  783. });
  784. xhr.addEventListener("load", (e) => ah.dispatchEvent(e));
  785. xhr.addEventListener("loadend", (e) => ah.dispatchEvent(e));
  786. for (const evt of xhrAsyncEvents) {
  787. const onEvt = "on" + evt;
  788. ah.proxyProps[onEvt] = {
  789. get: () => ah.proxyEvents[onEvt] || null,
  790. set: (val) => ah.addEvent(onEvt, val),
  791. };
  792. }
  793. for (const method of [
  794. "setRequestHeader",
  795. "addEventListener",
  796. "removeEventListener",
  797. "open",
  798. "send",
  799. ]) {
  800. ah.proxyProps[method] = { value: ah[method] };
  801. }
  802. }
  803. toJSON() {} // Converting circular structure to JSON
  804. addEvent(type, event) {
  805. if (type.startsWith("on")) {
  806. this.proxyEvents[type] = typeof event === "function" ? event : null;
  807. } else {
  808. if (typeof event === "object" && event !== null)
  809. event = event.handleEvent;
  810. if (typeof event !== "function") return;
  811. this.proxyEvents[type] = this.proxyEvents[type] || new Set();
  812. this.proxyEvents[type].add(event);
  813. }
  814. }
  815. removeEvent(type, event) {
  816. if (type.startsWith("on")) {
  817. this.proxyEvents[type] = null;
  818. } else {
  819. if (typeof event === "object" && event !== null)
  820. event = event.handleEvent;
  821. this.proxyEvents[type] && this.proxyEvents[type].delete(event);
  822. }
  823. }
  824. dispatchEvent(e) {
  825. e.stopImmediatePropagation = stopImmediatePropagation;
  826. defineProp(e, "target", () => this.proxyXhr);
  827. defineProp(e, "currentTarget", () => this.proxyXhr);
  828. this.proxyEvents[e.type] &&
  829. this.proxyEvents[e.type].forEach((fn) => {
  830. this.resThenable.then(
  831. () => !e.ajaxHooker_isStopped && fn.call(this.proxyXhr, e)
  832. );
  833. });
  834. if (e.ajaxHooker_isStopped) return;
  835. const onEvent = this.proxyEvents["on" + e.type];
  836. onEvent && this.resThenable.then(onEvent.bind(this.proxyXhr, e));
  837. }
  838. setRequestHeader(header, value) {
  839. this.originalXhr.setRequestHeader(header, value);
  840. if (!this.request) return;
  841. const headers = this.request.headers;
  842. headers[header] =
  843. header in headers ? `${headers[header]}, ${value}` : value;
  844. }
  845. addEventListener(...args) {
  846. if (xhrAsyncEvents.includes(args[0])) {
  847. this.addEvent(args[0], args[1]);
  848. } else {
  849. this.originalXhr.addEventListener(...args);
  850. }
  851. }
  852. removeEventListener(...args) {
  853. if (xhrAsyncEvents.includes(args[0])) {
  854. this.removeEvent(args[0], args[1]);
  855. } else {
  856. this.originalXhr.removeEventListener(...args);
  857. }
  858. }
  859. open(method, url, async = true, ...args) {
  860. this.request = {
  861. type: "xhr",
  862. url: url.toString(),
  863. method: method.toUpperCase(),
  864. abort: false,
  865. headers: {},
  866. data: null,
  867. response: null,
  868. async: !!async,
  869. };
  870. this.openArgs = args;
  871. this.resThenable = new SyncThenable();
  872. [
  873. "responseURL",
  874. "readyState",
  875. "status",
  876. "statusText",
  877. ...xhrResponses,
  878. ].forEach((key) => {
  879. delete this.proxyProps[key];
  880. });
  881. return this.originalXhr.open(method, url, async, ...args);
  882. }
  883. send(data) {
  884. const ah = this;
  885. const xhr = ah.originalXhr;
  886. const request = ah.request;
  887. if (!request) return xhr.send(data);
  888. request.data = data;
  889. new AHRequest(request).waitForRequestKeys().then(() => {
  890. if (request.abort) {
  891. if (typeof request.response === "function") {
  892. Object.assign(ah.proxyProps, {
  893. responseURL: { value: request.url },
  894. readyState: { value: 4 },
  895. status: { value: 200 },
  896. statusText: { value: "OK" },
  897. });
  898. xhrAsyncEvents.forEach((evt) =>
  899. xhr.dispatchEvent(new Event(evt))
  900. );
  901. }
  902. } else {
  903. xhr.open(
  904. request.method,
  905. request.url,
  906. request.async,
  907. ...ah.openArgs
  908. );
  909. for (const header in request.headers) {
  910. xhr.setRequestHeader(header, request.headers[header]);
  911. }
  912. xhr.send(request.data);
  913. }
  914. });
  915. }
  916. }
  917. function fakeXHR() {
  918. const xhr = new winAh.realXHR();
  919. if ("__ajaxHooker" in xhr)
  920. console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
  921. xhr.__ajaxHooker = new XhrHooker(xhr);
  922. return xhr.__ajaxHooker.proxyXhr;
  923. }
  924. fakeXHR.prototype = win.XMLHttpRequest.prototype;
  925. Object.keys(win.XMLHttpRequest).forEach(
  926. (key) => (fakeXHR[key] = win.XMLHttpRequest[key])
  927. );
  928. function fakeFetch(url, options = {}) {
  929. if (!url) return winAh.realFetch.call(win, url, options);
  930. return new Promise(async (resolve, reject) => {
  931. const init = {};
  932. if (getType(url) === "[object Request]") {
  933. for (const prop of fetchInitProps) init[prop] = url[prop];
  934. if (url.body) init.body = await url.arrayBuffer();
  935. url = url.url;
  936. }
  937. url = url.toString();
  938. Object.assign(init, options);
  939. init.method = init.method || "GET";
  940. init.headers = init.headers || {};
  941. const request = {
  942. type: "fetch",
  943. url: url,
  944. method: init.method.toUpperCase(),
  945. abort: false,
  946. headers: parseHeaders(init.headers),
  947. data: init.body,
  948. response: null,
  949. async: true,
  950. };
  951. const req = new AHRequest(request);
  952. await req.waitForRequestKeys();
  953. if (request.abort) {
  954. if (typeof request.response === "function") {
  955. const response = {
  956. finalUrl: request.url,
  957. status: 200,
  958. responseHeaders: {},
  959. };
  960. await req.waitForResponseKeys(response);
  961. const key = fetchResponses.find((k) => k in response);
  962. let val = response[key];
  963. if (key === "json" && typeof val === "object") {
  964. val = catchError(JSON.stringify.bind(JSON), val);
  965. }
  966. const res = new Response(val, {
  967. status: 200,
  968. statusText: "OK",
  969. });
  970. defineProp(res, "type", () => "basic");
  971. defineProp(res, "url", () => request.url);
  972. resolve(res);
  973. } else {
  974. reject(new DOMException("aborted", "AbortError"));
  975. }
  976. return;
  977. }
  978. init.method = request.method;
  979. init.headers = request.headers;
  980. init.body = request.data;
  981. winAh.realFetch.call(win, request.url, init).then((res) => {
  982. if (typeof request.response === "function") {
  983. const response = {
  984. finalUrl: res.url,
  985. status: res.status,
  986. responseHeaders: parseHeaders(res.headers),
  987. };
  988. fetchResponses.forEach(
  989. (key) =>
  990. (res[key] = function () {
  991. if (key in response) return Promise.resolve(response[key]);
  992. return resProto[key].call(this).then((val) => {
  993. response[key] = val;
  994. return req
  995. .waitForResponseKeys(response)
  996. .then(() => (key in response ? response[key] : val));
  997. });
  998. })
  999. );
  1000. }
  1001. resolve(res);
  1002. }, reject);
  1003. });
  1004. }
  1005. function fakeFetchClone() {
  1006. const descriptors = Object.getOwnPropertyDescriptors(this);
  1007. const res = winAh.realFetchClone.call(this);
  1008. Object.defineProperties(res, descriptors);
  1009. return res;
  1010. }
  1011. winAh = win.__ajaxHooker = winAh || {
  1012. version,
  1013. fakeXHR,
  1014. fakeFetch,
  1015. fakeFetchClone,
  1016. realXHR: win.XMLHttpRequest,
  1017. realFetch: win.fetch,
  1018. realFetchClone: resProto.clone,
  1019. hookInsts: new Set(),
  1020. };
  1021. if (winAh.version !== version)
  1022. console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
  1023. win.XMLHttpRequest = winAh.fakeXHR;
  1024. win.fetch = winAh.fakeFetch;
  1025. resProto.clone = winAh.fakeFetchClone;
  1026. winAh.hookInsts.add(hookInst);
  1027. // 针对头条、抖音 secsdk.umd.js 的兼容性处理
  1028. class AHFunction {
  1029. call(thisArg, ...args) {
  1030. if (
  1031. thisArg &&
  1032. thisArg.__ajaxHooker &&
  1033. thisArg.__ajaxHooker.proxyXhr === thisArg
  1034. ) {
  1035. thisArg = thisArg.__ajaxHooker.originalXhr;
  1036. }
  1037. return Reflect.apply(this, thisArg, args);
  1038. }
  1039. apply(thisArg, args) {
  1040. if (
  1041. thisArg &&
  1042. thisArg.__ajaxHooker &&
  1043. thisArg.__ajaxHooker.proxyXhr === thisArg
  1044. ) {
  1045. thisArg = thisArg.__ajaxHooker.originalXhr;
  1046. }
  1047. return Reflect.apply(this, thisArg, args || []);
  1048. }
  1049. }
  1050. function hookSecsdk(csrf) {
  1051. Object.setPrototypeOf(
  1052. csrf.nativeXMLHttpRequestSetRequestHeader,
  1053. AHFunction.prototype
  1054. );
  1055. Object.setPrototypeOf(
  1056. csrf.nativeXMLHttpRequestOpen,
  1057. AHFunction.prototype
  1058. );
  1059. Object.setPrototypeOf(
  1060. csrf.nativeXMLHttpRequestSend,
  1061. AHFunction.prototype
  1062. );
  1063. }
  1064. if (win.secsdk) {
  1065. if (win.secsdk.csrf && win.secsdk.csrf.nativeXMLHttpRequestOpen)
  1066. hookSecsdk(win.secsdk.csrf);
  1067. } else {
  1068. defineProp(win, "secsdk", emptyFn, (secsdk) => {
  1069. delete win.secsdk;
  1070. win.secsdk = secsdk;
  1071. defineProp(secsdk, "csrf", emptyFn, (csrf) => {
  1072. delete secsdk.csrf;
  1073. secsdk.csrf = csrf;
  1074. if (csrf.nativeXMLHttpRequestOpen) hookSecsdk(csrf);
  1075. });
  1076. });
  1077. }
  1078. return {
  1079. hook: (fn) => hookInst.hookFns.push(fn),
  1080. filter: (arr) => {
  1081. if (Array.isArray(arr)) hookInst.filters = arr;
  1082. },
  1083. protect: () => {
  1084. readonly(win, "XMLHttpRequest", winAh.fakeXHR);
  1085. readonly(win, "fetch", winAh.fakeFetch);
  1086. readonly(resProto, "clone", winAh.fakeFetchClone);
  1087. },
  1088. unhook: () => {
  1089. winAh.hookInsts.delete(hookInst);
  1090. if (!winAh.hookInsts.size) {
  1091. writable(win, "XMLHttpRequest", winAh.realXHR);
  1092. writable(win, "fetch", winAh.realFetch);
  1093. writable(resProto, "clone", winAh.realFetchClone);
  1094. delete win.__ajaxHooker;
  1095. }
  1096. },
  1097. };
  1098. })();
  1099. };
  1100.  
  1101. // ==UserScript==
  1102. // @name ajaxHooker
  1103. // @author cxxjackie
  1104. // @version 1.2.4
  1105. // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
  1106. // ==/UserScript==
  1107.  
  1108. const AjaxHooker1_2_4 = function () {
  1109. return (function () {
  1110. const win = window.unsafeWindow || document.defaultView || window;
  1111. const hookFns = [];
  1112. const realXhr = win.XMLHttpRequest;
  1113. const resProto = win.Response.prototype;
  1114. const toString = Object.prototype.toString;
  1115. const realFetch = win.fetch;
  1116. const xhrResponses = ["response", "responseText", "responseXML"];
  1117. const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
  1118. const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
  1119. let filter;
  1120. function emptyFn() {}
  1121. function errorFn(err) {
  1122. console.error(err);
  1123. }
  1124. function defineProp(obj, prop, getter, setter) {
  1125. Object.defineProperty(obj, prop, {
  1126. configurable: true,
  1127. enumerable: true,
  1128. get: getter,
  1129. set: setter,
  1130. });
  1131. }
  1132. function readonly(obj, prop, value = obj[prop]) {
  1133. defineProp(obj, prop, () => value, emptyFn);
  1134. }
  1135. function writable(obj, prop, value = obj[prop]) {
  1136. Object.defineProperty(obj, prop, {
  1137. configurable: true,
  1138. enumerable: true,
  1139. writable: true,
  1140. value: value,
  1141. });
  1142. }
  1143. function toFilterObj(obj) {
  1144. return {
  1145. type: obj.type,
  1146. url: obj.url,
  1147. method: obj.method && obj.method.toUpperCase(),
  1148. };
  1149. }
  1150. function shouldFilter(type, url, method) {
  1151. return (
  1152. filter &&
  1153. !filter.find(
  1154. (obj) =>
  1155. (!obj.type || obj.type === type) &&
  1156. (!obj.url ||
  1157. (toString.call(obj.url) === "[object String]"
  1158. ? url.includes(obj.url)
  1159. : obj.url.test(url))) &&
  1160. (!obj.method || obj.method === method.toUpperCase())
  1161. )
  1162. );
  1163. }
  1164. function lookupGetter(obj, prop) {
  1165. let getter;
  1166. let proto = obj;
  1167. while (proto) {
  1168. const descriptor = Object.getOwnPropertyDescriptor(proto, prop);
  1169. getter = descriptor && descriptor.get;
  1170. if (getter) break;
  1171. proto = Object.getPrototypeOf(proto);
  1172. }
  1173. return getter ? getter.bind(obj) : emptyFn;
  1174. }
  1175. function waitForHookFns(request) {
  1176. return Promise.all(
  1177. hookFns.map((fn) => Promise.resolve(fn(request)).then(emptyFn, errorFn))
  1178. );
  1179. }
  1180. function waitForRequestKeys(request, requestClone) {
  1181. return Promise.all(
  1182. ["url", "method", "abort", "headers", "data"].map((key) => {
  1183. return Promise.resolve(request[key]).then(
  1184. (val) => (request[key] = val),
  1185. () => (request[key] = requestClone[key])
  1186. );
  1187. })
  1188. );
  1189. }
  1190. function fakeEventSIP() {
  1191. this.ajaxHooker_stopped = true;
  1192. }
  1193. function xhrDelegateEvent(e) {
  1194. const xhr = e.target;
  1195. e.stopImmediatePropagation = fakeEventSIP;
  1196. xhr.__ajaxHooker.hookedEvents[e.type].forEach(
  1197. (fn) => !e.ajaxHooker_stopped && fn.call(xhr, e)
  1198. );
  1199. const onEvent = xhr.__ajaxHooker.hookedEvents["on" + e.type];
  1200. typeof onEvent === "function" && onEvent.call(xhr, e);
  1201. }
  1202. function xhrReadyStateChange(e) {
  1203. if (e.target.readyState === 4) {
  1204. e.target.dispatchEvent(
  1205. new CustomEvent("ajaxHooker_responseReady", { detail: e })
  1206. );
  1207. } else {
  1208. e.target.__ajaxHooker.delegateEvent(e);
  1209. }
  1210. }
  1211. function xhrLoadAndLoadend(e) {
  1212. e.target.__ajaxHooker.delegateEvent(e);
  1213. }
  1214. function fakeXhrOpen(method, url, ...args) {
  1215. const ah = this.__ajaxHooker;
  1216. ah.url = url.toString();
  1217. ah.method = method.toUpperCase();
  1218. ah.openArgs = args;
  1219. ah.headers = {};
  1220. return ah.originalMethods.open(method, url, ...args);
  1221. }
  1222. function fakeXhr() {
  1223. const xhr = new realXhr();
  1224. let ah = xhr.__ajaxHooker;
  1225. if (!ah) {
  1226. ah = xhr.__ajaxHooker = {
  1227. headers: {},
  1228. hookedEvents: {
  1229. readystatechange: new Set(),
  1230. load: new Set(),
  1231. loadend: new Set(),
  1232. },
  1233. delegateEvent: xhrDelegateEvent,
  1234. originalGetters: {},
  1235. originalMethods: {},
  1236. };
  1237. xhr.addEventListener("readystatechange", xhrReadyStateChange);
  1238. xhr.addEventListener("load", xhrLoadAndLoadend);
  1239. xhr.addEventListener("loadend", xhrLoadAndLoadend);
  1240. for (const key of xhrResponses) {
  1241. ah.originalGetters[key] = lookupGetter(xhr, key);
  1242. }
  1243. for (const method of [
  1244. "open",
  1245. "setRequestHeader",
  1246. "addEventListener",
  1247. "removeEventListener",
  1248. ]) {
  1249. ah.originalMethods[method] = xhr[method].bind(xhr);
  1250. }
  1251. xhr.open = fakeXhrOpen;
  1252. xhr.setRequestHeader = (header, value) => {
  1253. ah.originalMethods.setRequestHeader(header, value);
  1254. if (xhr.readyState === 1) {
  1255. if (ah.headers[header]) {
  1256. ah.headers[header] += ", " + value;
  1257. } else {
  1258. ah.headers[header] = value;
  1259. }
  1260. }
  1261. };
  1262. xhr.addEventListener = function (...args) {
  1263. if (xhrAsyncEvents.includes(args[0])) {
  1264. ah.hookedEvents[args[0]].add(args[1]);
  1265. } else {
  1266. ah.originalMethods.addEventListener(...args);
  1267. }
  1268. };
  1269. xhr.removeEventListener = function (...args) {
  1270. if (xhrAsyncEvents.includes(args[0])) {
  1271. ah.hookedEvents[args[0]].delete(args[1]);
  1272. } else {
  1273. ah.originalMethods.removeEventListener(...args);
  1274. }
  1275. };
  1276. xhrAsyncEvents.forEach((evt) => {
  1277. const onEvt = "on" + evt;
  1278. defineProp(
  1279. xhr,
  1280. onEvt,
  1281. () => {
  1282. return ah.hookedEvents[onEvt] || null;
  1283. },
  1284. (val) => {
  1285. ah.hookedEvents[onEvt] = typeof val === "function" ? val : null;
  1286. }
  1287. );
  1288. });
  1289. }
  1290. const realSend = xhr.send.bind(xhr);
  1291. xhr.send = function (data) {
  1292. if (xhr.readyState !== 1) return realSend(data);
  1293. ah.delegateEvent = xhrDelegateEvent;
  1294. xhrResponses.forEach((prop) => {
  1295. delete xhr[prop]; // delete descriptor
  1296. });
  1297. if (shouldFilter("xhr", ah.url, ah.method)) {
  1298. xhr.addEventListener("ajaxHooker_responseReady", (e) => {
  1299. ah.delegateEvent(e.detail);
  1300. });
  1301. return realSend(data);
  1302. }
  1303. try {
  1304. const request = {
  1305. type: "xhr",
  1306. url: ah.url,
  1307. method: ah.method,
  1308. abort: false,
  1309. headers: ah.headers,
  1310. data: data,
  1311. response: null,
  1312. };
  1313. const requestClone = { ...request };
  1314. waitForHookFns(request).then(() => {
  1315. waitForRequestKeys(request, requestClone).then(() => {
  1316. if (request.abort) return;
  1317. ah.originalMethods.open(
  1318. request.method,
  1319. request.url,
  1320. ...ah.openArgs
  1321. );
  1322. for (const header in request.headers) {
  1323. ah.originalMethods.setRequestHeader(
  1324. header,
  1325. request.headers[header]
  1326. );
  1327. }
  1328. data = request.data;
  1329. xhr.addEventListener("ajaxHooker_responseReady", (e) => {
  1330. try {
  1331. if (typeof request.response === "function") {
  1332. const arg = {
  1333. finalUrl: xhr.responseURL,
  1334. status: xhr.status,
  1335. responseHeaders: {},
  1336. };
  1337. for (const line of xhr
  1338. .getAllResponseHeaders()
  1339. .trim()
  1340. .split(/[\r\n]+/)) {
  1341. const parts = line.split(/:\s*/);
  1342. if (parts.length === 2) {
  1343. const lheader = parts[0].toLowerCase();
  1344. if (arg.responseHeaders[lheader]) {
  1345. arg.responseHeaders[lheader] += ", " + parts[1];
  1346. } else {
  1347. arg.responseHeaders[lheader] = parts[1];
  1348. }
  1349. }
  1350. }
  1351. xhrResponses.forEach((prop) => {
  1352. defineProp(
  1353. arg,
  1354. prop,
  1355. () => {
  1356. return (arg[prop] = ah.originalGetters[prop]());
  1357. },
  1358. (val) => {
  1359. delete arg[prop];
  1360. arg[prop] = val;
  1361. }
  1362. );
  1363. defineProp(xhr, prop, () => {
  1364. const val = ah.originalGetters[prop]();
  1365. xhr.dispatchEvent(
  1366. new CustomEvent("ajaxHooker_readResponse", {
  1367. detail: { prop, val },
  1368. })
  1369. );
  1370. return val;
  1371. });
  1372. });
  1373. xhr.addEventListener("ajaxHooker_readResponse", (e) => {
  1374. arg[e.detail.prop] = e.detail.val;
  1375. });
  1376. const resPromise = Promise.resolve(
  1377. request.response(arg)
  1378. ).then(() => {
  1379. const task = [];
  1380. xhrResponses.forEach((prop) => {
  1381. const descriptor = Object.getOwnPropertyDescriptor(
  1382. arg,
  1383. prop
  1384. );
  1385. if (descriptor && "value" in descriptor) {
  1386. task.push(
  1387. Promise.resolve(descriptor.value).then((val) => {
  1388. arg[prop] = val;
  1389. defineProp(xhr, prop, () => {
  1390. xhr.dispatchEvent(
  1391. new CustomEvent("ajaxHooker_readResponse", {
  1392. detail: { prop, val },
  1393. })
  1394. );
  1395. return val;
  1396. });
  1397. }, emptyFn)
  1398. );
  1399. }
  1400. });
  1401. return Promise.all(task);
  1402. }, errorFn);
  1403. const eventsClone = {};
  1404. xhrAsyncEvents.forEach((type) => {
  1405. eventsClone[type] = new Set([...ah.hookedEvents[type]]);
  1406. eventsClone["on" + type] = ah.hookedEvents["on" + type];
  1407. });
  1408. ah.delegateEvent = (event) =>
  1409. resPromise.then(() => {
  1410. event.stopImmediatePropagation = fakeEventSIP;
  1411. eventsClone[event.type].forEach(
  1412. (fn) =>
  1413. !event.ajaxHooker_stopped && fn.call(xhr, event)
  1414. );
  1415. const onEvent = eventsClone["on" + event.type];
  1416. typeof onEvent === "function" &&
  1417. onEvent.call(xhr, event);
  1418. });
  1419. }
  1420. } catch (err) {
  1421. console.error(err);
  1422. }
  1423. ah.delegateEvent(e.detail);
  1424. });
  1425. realSend(data);
  1426. });
  1427. });
  1428. } catch (err) {
  1429. console.error(err);
  1430. realSend(data);
  1431. }
  1432. };
  1433. return xhr;
  1434. }
  1435. function hookFetchResponse(response, arg, callback) {
  1436. fetchResponses.forEach((prop) => {
  1437. response[prop] = () =>
  1438. new Promise((resolve, reject) => {
  1439. resProto[prop].call(response).then((res) => {
  1440. if (prop in arg) {
  1441. resolve(arg[prop]);
  1442. } else {
  1443. try {
  1444. arg[prop] = res;
  1445. Promise.resolve(callback(arg)).then(() => {
  1446. if (prop in arg) {
  1447. Promise.resolve(arg[prop]).then(
  1448. (val) => resolve((arg[prop] = val)),
  1449. () => resolve(res)
  1450. );
  1451. } else {
  1452. resolve(res);
  1453. }
  1454. }, errorFn);
  1455. } catch (err) {
  1456. console.error(err);
  1457. resolve(res);
  1458. }
  1459. }
  1460. }, reject);
  1461. });
  1462. });
  1463. }
  1464. function fakeFetch(url, init) {
  1465. if (url && typeof url.toString === "function") {
  1466. url = url.toString();
  1467. init = init || {};
  1468. init.method = init.method || "GET";
  1469. init.headers = init.headers || {};
  1470. if (shouldFilter("fetch", url, init.method))
  1471. return realFetch.call(win, url, init);
  1472. const request = {
  1473. type: "fetch",
  1474. url: url,
  1475. method: init.method.toUpperCase(),
  1476. abort: false,
  1477. headers: {},
  1478. data: init.body,
  1479. response: null,
  1480. };
  1481. if (toString.call(init.headers) === "[object Headers]") {
  1482. for (const [key, val] of init.headers) {
  1483. request.headers[key] = val;
  1484. }
  1485. } else {
  1486. request.headers = { ...init.headers };
  1487. }
  1488. const requestClone = { ...request };
  1489. return new Promise((resolve, reject) => {
  1490. try {
  1491. waitForHookFns(request).then(() => {
  1492. waitForRequestKeys(request, requestClone).then(() => {
  1493. if (request.abort) return reject("aborted");
  1494. url = request.url;
  1495. init.method = request.method;
  1496. init.headers = request.headers;
  1497. init.body = request.data;
  1498. realFetch.call(win, url, init).then((response) => {
  1499. if (typeof request.response === "function") {
  1500. const arg = {
  1501. finalUrl: response.url,
  1502. status: response.status,
  1503. responseHeaders: {},
  1504. };
  1505. for (const [key, val] of response.headers) {
  1506. arg.responseHeaders[key] = val;
  1507. }
  1508. hookFetchResponse(response, arg, request.response);
  1509. response.clone = () => {
  1510. const resClone = resProto.clone.call(response);
  1511. hookFetchResponse(resClone, arg, request.response);
  1512. return resClone;
  1513. };
  1514. }
  1515. resolve(response);
  1516. }, reject);
  1517. });
  1518. });
  1519. } catch (err) {
  1520. console.error(err);
  1521. return realFetch.call(win, url, init);
  1522. }
  1523. });
  1524. } else {
  1525. return realFetch.call(win, url, init);
  1526. }
  1527. }
  1528. win.XMLHttpRequest = fakeXhr;
  1529. Object.keys(realXhr).forEach((key) => (fakeXhr[key] = realXhr[key]));
  1530. fakeXhr.prototype = realXhr.prototype;
  1531. win.fetch = fakeFetch;
  1532. return {
  1533. hook: (fn) => hookFns.push(fn),
  1534. filter: (arr) => {
  1535. filter = Array.isArray(arr) && arr.map(toFilterObj);
  1536. },
  1537. protect: () => {
  1538. readonly(win, "XMLHttpRequest", fakeXhr);
  1539. readonly(win, "fetch", fakeFetch);
  1540. },
  1541. unhook: () => {
  1542. writable(win, "XMLHttpRequest", realXhr);
  1543. writable(win, "fetch", realFetch);
  1544. },
  1545. };
  1546. })();
  1547. };
  1548.  
  1549. class GMMenu {
  1550. GM_Api = {
  1551. /**
  1552. * 获取存储的数据
  1553. */
  1554. getValue: null,
  1555. /**
  1556. * 设置数据到存储
  1557. */
  1558. setValue: null,
  1559. /**
  1560. * 注册(不可用)菜单
  1561. */
  1562. registerMenuCommand: null,
  1563. /**
  1564. * 卸载菜单
  1565. */
  1566. unregisterMenuCommand: null,
  1567. };
  1568. MenuHandle = {
  1569. context: this,
  1570. $data: {
  1571. /**
  1572. * 菜单数据
  1573. */
  1574. data: [],
  1575. /**
  1576. * 本地存储的键名
  1577. */
  1578. key: "GM_Menu_Local_Map",
  1579. },
  1580. $default: {
  1581. /** 自动刷新网页,默认为true */
  1582. autoReload: true,
  1583. /**
  1584. * 菜单isStoreValue的默认值
  1585. */
  1586. isStoreValue: true,
  1587. },
  1588. $emoji: {
  1589. /**
  1590. * 菜单enable为true的emoji
  1591. */
  1592. success: "✅",
  1593. /**
  1594. * 菜单enable为false的emoji
  1595. */
  1596. error: "❌",
  1597. },
  1598. /**
  1599. * 初始化数据
  1600. */
  1601. init() {
  1602. for (let index = 0; index < this.$data.data.length; index++) {
  1603. let menuOption = this.$data.data[index]["data"];
  1604. menuOption.enable = Boolean(this.getLocalMenuData(menuOption.key, menuOption.enable));
  1605. if (typeof menuOption.showText !== "function") {
  1606. menuOption.showText = (menuText, menuEnable) => {
  1607. if (menuEnable) {
  1608. return this.$emoji.success + " " + menuText;
  1609. }
  1610. else {
  1611. return this.$emoji.error + " " + menuText;
  1612. }
  1613. };
  1614. }
  1615. }
  1616. },
  1617. /**
  1618. * 注册(不可用)油猴菜单
  1619. * @param menuOptions 如果存在,使用它
  1620. */
  1621. register(menuOptions) {
  1622. let that = this;
  1623. if (menuOptions == null) {
  1624. throw new TypeError("register菜单数据不能为空");
  1625. }
  1626. if (!Array.isArray(menuOptions)) {
  1627. menuOptions = [menuOptions];
  1628. }
  1629. for (let index = 0; index < menuOptions.length; index++) {
  1630. let cloneMenuOptionData = utils.deepClone(menuOptions[index].data);
  1631. const { showText, clickCallBack } = this.handleMenuData(cloneMenuOptionData);
  1632. let menuId = that.context.GM_Api.registerMenuCommand(showText, clickCallBack);
  1633. menuOptions[index].id = menuId;
  1634. cloneMenuOptionData.deleteMenu = function () {
  1635. that.context.GM_Api.unregisterMenuCommand(menuId);
  1636. };
  1637. Reflect.deleteProperty(menuOptions[index], "handleData");
  1638. menuOptions[index].handleData = cloneMenuOptionData;
  1639. }
  1640. },
  1641. /**
  1642. * 获取本地存储菜单键值
  1643. * @param {string} key 键
  1644. */
  1645. getLocalMenuData(key, defaultValue) {
  1646. let localData = this.context.GM_Api.getValue(this.$data.key, {});
  1647. if (key in localData) {
  1648. return localData[key];
  1649. }
  1650. else {
  1651. return defaultValue;
  1652. }
  1653. },
  1654. /**
  1655. * 设置本地存储菜单键值
  1656. * @param key 键
  1657. * @param value 值
  1658. */
  1659. setLocalMenuData(key, value) {
  1660. let localData = this.context.GM_Api.getValue(this.$data.key, {});
  1661. localData[key] = value;
  1662. this.context.GM_Api.setValue(this.$data.key, localData);
  1663. },
  1664. /**
  1665. * 处理初始化配置
  1666. * @param menuOption
  1667. */
  1668. handleInitDetail(menuOption) {
  1669. menuOption.enable = Boolean(this.getLocalMenuData(menuOption.key, menuOption.enable));
  1670. if (typeof menuOption.showText !== "function") {
  1671. menuOption.showText = (menuText, menuEnable) => {
  1672. if (menuEnable) {
  1673. return this.$emoji.success + " " + menuText;
  1674. }
  1675. else {
  1676. return this.$emoji.error + " " + menuText;
  1677. }
  1678. };
  1679. }
  1680. return menuOption;
  1681. },
  1682. /**
  1683. * 对菜单数据进行处理
  1684. * @param menuOption
  1685. */
  1686. handleMenuData(menuOption) {
  1687. let that = this;
  1688. let menuLocalDataItemKey = menuOption.key;
  1689. /* 菜单默认开启的状态 */
  1690. let defaultEnable = Boolean(this.getLocalMenuData(menuLocalDataItemKey, menuOption.enable));
  1691. /** 油猴菜单上显示的文本 */
  1692. let showText = menuOption.showText(menuOption.text, defaultEnable);
  1693. // @ts-ignore
  1694. ({
  1695. /**
  1696. * 菜单的id
  1697. */
  1698. id: menuOption.id,
  1699. /**
  1700. * 点击菜单项后是否应关闭弹出菜单
  1701. */
  1702. autoClose: menuOption.autoClose,
  1703. /**
  1704. * 菜单项的可选访问键
  1705. */
  1706. accessKey: menuOption.accessKey,
  1707. /**
  1708. * 菜单项的鼠标悬浮上的工具提示
  1709. */
  1710. title: menuOption.title,
  1711. });
  1712. /* 点击菜单后触发callback后的网页是否刷新 */
  1713. menuOption.autoReload =
  1714. typeof menuOption.autoReload !== "boolean"
  1715. ? this.$default.autoReload
  1716. : menuOption.autoReload;
  1717. /* 点击菜单后触发callback后的网页是否存储值 */
  1718. menuOption.isStoreValue =
  1719. typeof menuOption.isStoreValue !== "boolean"
  1720. ? this.$default.isStoreValue
  1721. : menuOption.isStoreValue;
  1722. /**
  1723. * 用户点击菜单后的回调函数
  1724. * @param event
  1725. */
  1726. function clickCallBack(event) {
  1727. let localEnable = Boolean(that.getLocalMenuData(menuLocalDataItemKey, defaultEnable));
  1728. if (menuOption.isStoreValue) {
  1729. that.setLocalMenuData(menuLocalDataItemKey, !localEnable);
  1730. }
  1731. if (typeof menuOption.callback === "function") {
  1732. menuOption.callback({
  1733. key: menuLocalDataItemKey,
  1734. enable: !localEnable,
  1735. oldEnable: localEnable,
  1736. event: event,
  1737. storeValue(value) {
  1738. that.setLocalMenuData(menuLocalDataItemKey, value);
  1739. },
  1740. });
  1741. }
  1742. /* 不刷新网页就刷新菜单 */
  1743. if (menuOption.autoReload) {
  1744. window.location.reload();
  1745. }
  1746. else {
  1747. that.context.update();
  1748. }
  1749. }
  1750. return {
  1751. showText,
  1752. clickCallBack,
  1753. };
  1754. },
  1755. /**
  1756. * 获取目标菜单配置数据
  1757. * @param menuKey 菜单-键key
  1758. */
  1759. getMenuData(menuKey) {
  1760. return this.$data.data.find((item) => item.data.key === menuKey);
  1761. },
  1762. /**
  1763. * 获取目标菜单配置
  1764. * @param menuKey 菜单-键key
  1765. */
  1766. getMenuOption(menuKey) {
  1767. return this.$data.data.find((item) => item.data.key === menuKey)?.data;
  1768. },
  1769. /**
  1770. * 获取目标菜单处理后的配置
  1771. * @param menuKey 菜单-键key
  1772. */
  1773. getMenuHandledOption(menuKey) {
  1774. return this.$data.data.find((item) => item.handleData.key === menuKey)
  1775. ?.handleData;
  1776. },
  1777. };
  1778. constructor(details) {
  1779. this.GM_Api.getValue = details.GM_getValue;
  1780. this.GM_Api.setValue = details.GM_setValue;
  1781. this.GM_Api.registerMenuCommand = details.GM_registerMenuCommand;
  1782. this.GM_Api.unregisterMenuCommand = details.GM_unregisterMenuCommand;
  1783. this.MenuHandle.$default.autoReload =
  1784. typeof details.autoReload === "boolean" ? details.autoReload : true;
  1785. for (const keyName of Object.keys(this.GM_Api)) {
  1786. if (typeof this.GM_Api[keyName] !== "function") {
  1787. throw new Error(`Utils.GM_Menu 请在脚本开头加上 @grant ${keyName},且传入该对象`);
  1788. }
  1789. }
  1790. this.add(details?.data || []);
  1791. }
  1792. /**
  1793. * 新增菜单数据
  1794. * @param menuOption
  1795. */
  1796. __add(menuOption) {
  1797. if (Array.isArray(menuOption)) {
  1798. for (let index = 0; index < menuOption.length; index++) {
  1799. const option = menuOption[index];
  1800. this.MenuHandle.$data.data.push({
  1801. data: option,
  1802. id: undefined,
  1803. });
  1804. }
  1805. }
  1806. else {
  1807. this.MenuHandle.$data.data.push({
  1808. data: menuOption,
  1809. id: undefined,
  1810. });
  1811. }
  1812. }
  1813. /**
  1814. * 新增菜单数据
  1815. *
  1816. * 自动调用.update()
  1817. * @param menuOption
  1818. */
  1819. add(menuOption) {
  1820. this.__add(menuOption);
  1821. this.update();
  1822. }
  1823. /**
  1824. * 更新菜单数据
  1825. *
  1826. * 实现方式:先取消注册(不可用)所有已注册(不可用)的菜单、再依次注册(不可用)所有菜单项
  1827. *
  1828. * 如果菜单不存在,新增菜单项
  1829. *
  1830. * 如果菜单已存在,新菜单项覆盖旧的菜单项
  1831. * @param options 数据
  1832. */
  1833. update(options) {
  1834. let menuOptionList = [];
  1835. if (Array.isArray(options)) {
  1836. menuOptionList = [...menuOptionList, ...options];
  1837. }
  1838. else if (options != null) {
  1839. menuOptionList = [...menuOptionList, options];
  1840. }
  1841. menuOptionList.forEach((menuOption) => {
  1842. let oldMenuOption = this.MenuHandle.getMenuOption(menuOption.key);
  1843. if (oldMenuOption) {
  1844. // 覆盖
  1845. Object.assign(oldMenuOption, menuOption);
  1846. }
  1847. else {
  1848. this.__add(menuOption);
  1849. }
  1850. });
  1851. this.MenuHandle.$data.data.forEach((value) => {
  1852. if (value.handleData) {
  1853. value.handleData.deleteMenu();
  1854. }
  1855. });
  1856. this.MenuHandle.init();
  1857. this.MenuHandle.register(this.MenuHandle.$data.data);
  1858. }
  1859. /**
  1860. * 卸载菜单
  1861. * @param menuId 已注册(不可用)的菜单id
  1862. */
  1863. delete(menuId) {
  1864. this.GM_Api.unregisterMenuCommand(menuId);
  1865. }
  1866. /**
  1867. * 根据键值获取enable值
  1868. * @param menuKey 菜单-键key
  1869. * @deprecated
  1870. */
  1871. get(menuKey) {
  1872. return this.getEnable(menuKey);
  1873. }
  1874. /**
  1875. * 根据键值获取enable值
  1876. * @param menuKey 菜单-键key
  1877. */
  1878. getEnable(menuKey) {
  1879. return this.MenuHandle.getMenuHandledOption(menuKey).enable;
  1880. }
  1881. /**
  1882. * 根据键值获取text值
  1883. * @param menuKey 菜单-键key
  1884. */
  1885. getText(menuKey) {
  1886. return this.MenuHandle.getMenuHandledOption(menuKey).text;
  1887. }
  1888. /**
  1889. * 根据键值获取showText函数的值
  1890. * @param menuKey 菜单-键key
  1891. */
  1892. getShowTextValue(menuKey) {
  1893. return this.MenuHandle.getMenuHandledOption(menuKey).showText(this.getText(menuKey), this.getEnable(menuKey));
  1894. }
  1895. /**
  1896. * 获取当前已注册(不可用)菜单的id
  1897. * @param menuKey
  1898. */
  1899. getMenuId(menuKey) {
  1900. let result = null;
  1901. for (let index = 0; index < this.MenuHandle.$data.data.length; index++) {
  1902. const optionData = this.MenuHandle.$data.data[index];
  1903. if (optionData.handleData.key === menuKey) {
  1904. result = optionData.id;
  1905. break;
  1906. }
  1907. }
  1908. return result;
  1909. }
  1910. /**
  1911. * 根据键值获取accessKey值
  1912. * @param menuKey 菜单-键key
  1913. */
  1914. getAccessKey(menuKey) {
  1915. return this.MenuHandle.getMenuHandledOption(menuKey)?.accessKey;
  1916. }
  1917. /**
  1918. * 根据键值获取autoClose值
  1919. * @param menuKey 菜单-键key
  1920. */
  1921. getAutoClose(menuKey) {
  1922. return this.MenuHandle.getMenuHandledOption(menuKey)?.autoClose;
  1923. }
  1924. /**
  1925. * 根据键值获取autoReload值
  1926. * @param menuKey 菜单-键key
  1927. */
  1928. getAutoReload(menuKey) {
  1929. return this.MenuHandle.getMenuHandledOption(menuKey)?.autoReload;
  1930. }
  1931. /**
  1932. * 根据键值获取callback函数
  1933. * @param menuKey 菜单-键key
  1934. */
  1935. getCallBack(menuKey) {
  1936. return this.MenuHandle.getMenuHandledOption(menuKey)?.callback;
  1937. }
  1938. /**
  1939. * 获取当enable为true时默认显示在菜单中前面的emoji图标
  1940. */
  1941. getEnableTrueEmoji() {
  1942. return this.MenuHandle.$emoji.success;
  1943. }
  1944. /**
  1945. * 获取当enable为false时默认显示在菜单中前面的emoji图标
  1946. */
  1947. getEnableFalseEmoji() {
  1948. return this.MenuHandle.$emoji.error;
  1949. }
  1950. /**
  1951. * 获取本地存储的菜单外部的键名
  1952. * @param keyName
  1953. */
  1954. getLocalStorageKeyName() {
  1955. return this.MenuHandle.$data.key;
  1956. }
  1957. /**
  1958. * 设置菜单的值
  1959. * @param menuKey 菜单-键key
  1960. * @param value 需要设置的值
  1961. */
  1962. setValue(menuKey, value) {
  1963. this.MenuHandle.setLocalMenuData(menuKey, value);
  1964. }
  1965. /**
  1966. * 设置菜单的值
  1967. * @param menuKey 菜单-键key
  1968. * @param value 需要设置的值
  1969. */
  1970. setEnable(menuKey, value) {
  1971. this.setValue(menuKey, Boolean(value));
  1972. }
  1973. /**
  1974. * 设置当enable为true时默认显示在菜单中前面的emoji图标
  1975. * @param emojiString
  1976. */
  1977. setEnableTrueEmoji(emojiString) {
  1978. if (typeof emojiString !== "string") {
  1979. throw new Error("参数emojiString必须是string类型");
  1980. }
  1981. this.MenuHandle.$emoji.success = emojiString;
  1982. }
  1983. /**
  1984. * 设置当enable为false时默认显示在菜单中前面的emoji图标
  1985. * @param emojiString
  1986. */
  1987. setEnableFalseEmoji(emojiString) {
  1988. if (typeof emojiString !== "string") {
  1989. throw new Error("参数emojiString必须是string类型");
  1990. }
  1991. this.MenuHandle.$emoji.error = emojiString;
  1992. }
  1993. /**
  1994. * 设置本地存储的菜单外部的键名
  1995. * @param keyName
  1996. */
  1997. setLocalStorageKeyName(keyName) {
  1998. if (typeof keyName !== "string") {
  1999. throw new Error("参数keyName必须是string类型");
  2000. }
  2001. this.MenuHandle.$data.key = keyName;
  2002. }
  2003. }
  2004.  
  2005. class Hooks {
  2006. /**
  2007. * 在Function原型上添加自定义方法.hook和.unhook
  2008. */
  2009. initEnv() {
  2010. Function.prototype.hook = function (realFunc, hookFunc, context) {
  2011. let _context = null; //函数上下文
  2012. let _funcName = null; //函数名
  2013. _context = context || window;
  2014. _funcName = getFuncName(this);
  2015. _context["realFunc_" + _funcName] = this;
  2016. if (_context[_funcName].prototype &&
  2017. _context[_funcName].prototype.isHooked) {
  2018. console.log("Already has been hooked,unhook first");
  2019. return false;
  2020. }
  2021. function getFuncName(fn) {
  2022. // 获取函数名
  2023. let strFunc = fn.toString();
  2024. let _regex = /function\s+(\w+)\s*\(/;
  2025. let patten = strFunc.match(_regex);
  2026. if (patten) {
  2027. return patten[1];
  2028. }
  2029. return "";
  2030. }
  2031. try {
  2032. eval("_context[_funcName] = function " +
  2033. _funcName +
  2034. "(){\n" +
  2035. "let args = Array.prototype.slice.call(arguments,0);\n" +
  2036. "let obj = this;\n" +
  2037. "hookFunc.apply(obj,args);\n" +
  2038. "return _context['realFunc_" +
  2039. _funcName +
  2040. "'].apply(obj,args);\n" +
  2041. "};");
  2042. _context[_funcName].prototype.isHooked = true;
  2043. return true;
  2044. }
  2045. catch (e) {
  2046. console.log("Hook failed,check the params.");
  2047. return false;
  2048. }
  2049. };
  2050. Function.prototype.unhook = function (realFunc, funcName, context) {
  2051. let _context = null;
  2052. let _funcName = null;
  2053. _context = context || window;
  2054. _funcName = funcName;
  2055. if (!_context[_funcName].prototype.isHooked) {
  2056. console.log("No function is hooked on");
  2057. return false;
  2058. }
  2059. _context[_funcName] = _context["realFunc" + _funcName];
  2060. Reflect.deleteProperty(_context, "realFunc_" + _funcName);
  2061. return true;
  2062. };
  2063. }
  2064. /**
  2065. * 删除在Function原型上添加的自定义方法.hook和.unhook
  2066. */
  2067. cleanEnv() {
  2068. if (Function.prototype.hasOwnProperty("hook")) {
  2069. Reflect.deleteProperty(Function.prototype, "hook");
  2070. }
  2071. if (Function.prototype.hasOwnProperty("unhook")) {
  2072. Reflect.deleteProperty(Function.prototype, "unhook");
  2073. }
  2074. return true;
  2075. }
  2076. }
  2077.  
  2078. /**
  2079. * 生成uuid
  2080. */
  2081. const GenerateUUID = function () {
  2082. if (typeof window?.crypto?.randomUUID === "function") {
  2083. return window.crypto.randomUUID();
  2084. }
  2085. else {
  2086. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (charStr) {
  2087. var randomValue = (Math.random() * 16) | 0, randomCharValue = charStr === "x" ? randomValue : (randomValue & 0x3) | 0x8;
  2088. return randomCharValue.toString(16);
  2089. });
  2090. }
  2091. };
  2092.  
  2093. class Httpx {
  2094. GM_Api = {
  2095. xmlHttpRequest: null,
  2096. };
  2097. HttpxRequestHook = {
  2098. /**
  2099. * @private
  2100. */
  2101. $config: {
  2102. configList: [],
  2103. },
  2104. /**
  2105. * 发送请求前的回调
  2106. * 如果返回false则阻止本次返回
  2107. * @param details 当前的请求配置
  2108. * @private
  2109. */
  2110. async beforeRequestCallBack(details) {
  2111. if (typeof details.allowInterceptConfig === "boolean") {
  2112. if (!details.allowInterceptConfig) {
  2113. // 不允许拦截
  2114. return details;
  2115. }
  2116. }
  2117. else {
  2118. if (details.allowInterceptConfig != null) {
  2119. // 配置存在
  2120. // 细分处理是否拦截
  2121. if (typeof details.allowInterceptConfig.beforeRequest === "boolean" &&
  2122. !details.allowInterceptConfig.beforeRequest) {
  2123. // 设置了禁止拦截
  2124. return details;
  2125. }
  2126. }
  2127. }
  2128. for (let index = 0; index < this.$config.configList.length; index++) {
  2129. let item = this.$config.configList[index];
  2130. if (typeof item.fn === "function") {
  2131. let result = await item.fn(details);
  2132. if (result == null) {
  2133. return;
  2134. }
  2135. }
  2136. }
  2137. return details;
  2138. },
  2139. /**
  2140. * 添加请求前的回调处理配置
  2141. */
  2142. add(fn) {
  2143. if (typeof fn === "function") {
  2144. let uuid = GenerateUUID();
  2145. this.$config.configList.push({
  2146. id: uuid,
  2147. fn: fn,
  2148. });
  2149. return uuid;
  2150. }
  2151. else {
  2152. console.warn("[Httpx-HttpxRequestHook.addBeforeRequestCallBack] fn is not a function");
  2153. }
  2154. },
  2155. /**
  2156. * 删除请求前的回调处理配置
  2157. * @param id
  2158. */
  2159. delete(id) {
  2160. if (typeof id === "string") {
  2161. let findIndex = this.$config.configList.findIndex((item) => item.id === id);
  2162. if (findIndex !== -1) {
  2163. this.$config.configList.splice(findIndex, 1);
  2164. return true;
  2165. }
  2166. }
  2167. return false;
  2168. },
  2169. /**
  2170. * 清空设置的请求前的回调处理配置
  2171. */
  2172. clearAll() {
  2173. this.$config.configList = [];
  2174. },
  2175. };
  2176. HttpxResponseHook = {
  2177. /**
  2178. * @private
  2179. */
  2180. $config: {
  2181. configList: [],
  2182. },
  2183. /**
  2184. * 成功的回调
  2185. * @param response 响应
  2186. * @param details 请求的配置
  2187. */
  2188. async successResponseCallBack(response, details) {
  2189. if (typeof details.allowInterceptConfig === "boolean") {
  2190. if (!details.allowInterceptConfig) {
  2191. // 不允许拦截
  2192. return details;
  2193. }
  2194. }
  2195. else {
  2196. if (details.allowInterceptConfig != null) {
  2197. // 配置存在
  2198. // 细分处理是否拦截
  2199. if (typeof details.allowInterceptConfig.afterResponseSuccess ===
  2200. "boolean" &&
  2201. !details.allowInterceptConfig.afterResponseSuccess) {
  2202. // 设置了禁止拦截
  2203. return details;
  2204. }
  2205. }
  2206. }
  2207. for (let index = 0; index < this.$config.configList.length; index++) {
  2208. let item = this.$config.configList[index];
  2209. if (typeof item.successFn === "function") {
  2210. let result = await item.successFn(response, details);
  2211. if (result == null) {
  2212. return;
  2213. }
  2214. }
  2215. }
  2216. return response;
  2217. },
  2218. /**
  2219. * 失败的回调
  2220. * @param data 配置
  2221. * @returns
  2222. * 返回null|undefined就是拦截掉了
  2223. */
  2224. async errorResponseCallBack(data) {
  2225. if (typeof data.details.allowInterceptConfig === "boolean") {
  2226. if (!data.details.allowInterceptConfig) {
  2227. // 不允许拦截
  2228. return data;
  2229. }
  2230. }
  2231. else {
  2232. if (data.details.allowInterceptConfig != null) {
  2233. // 配置存在
  2234. // 细分处理是否拦截
  2235. if (typeof data.details.allowInterceptConfig.afterResponseError ===
  2236. "boolean" &&
  2237. !data.details.allowInterceptConfig.afterResponseError) {
  2238. // 设置了禁止拦截
  2239. return data;
  2240. }
  2241. }
  2242. }
  2243. for (let index = 0; index < this.$config.configList.length; index++) {
  2244. let item = this.$config.configList[index];
  2245. if (typeof item.errorFn === "function") {
  2246. let result = await item.errorFn(data);
  2247. if (result == null) {
  2248. return;
  2249. }
  2250. }
  2251. }
  2252. return data;
  2253. },
  2254. /**
  2255. * 添加请求前的回调处理配置
  2256. */
  2257. add(successFn, errorFn) {
  2258. let id = GenerateUUID();
  2259. this.$config.configList.push({
  2260. id: id,
  2261. successFn: successFn,
  2262. errorFn: errorFn,
  2263. });
  2264. return id;
  2265. },
  2266. /**
  2267. * 删除请求前的回调处理配置
  2268. * @param id
  2269. */
  2270. delete(id) {
  2271. if (typeof id === "string") {
  2272. let findIndex = this.$config.configList.findIndex((item) => item.id === id);
  2273. if (findIndex !== -1) {
  2274. this.$config.configList.splice(findIndex, 1);
  2275. return true;
  2276. }
  2277. }
  2278. return false;
  2279. },
  2280. /**
  2281. * 清空设置的请求前的回调处理配置
  2282. */
  2283. clearAll() {
  2284. this.$config.configList = [];
  2285. },
  2286. };
  2287. HttpxRequestOption = {
  2288. context: this,
  2289. /**
  2290. * 根据传入的参数处理获取details配置
  2291. */
  2292. handleBeforeRequestOption(...args) {
  2293. let option = {};
  2294. if (typeof args[0] === "string") {
  2295. /* 传入的是url,details? */
  2296. let url = args[0];
  2297. option.url = url;
  2298. if (typeof args[1] === "object") {
  2299. /* 处理第二个参数details */
  2300. let details = args[1];
  2301. option = details;
  2302. option.url = url;
  2303. }
  2304. }
  2305. else {
  2306. /* 传入的是details */
  2307. option = args[0];
  2308. }
  2309. return option;
  2310. },
  2311. /**
  2312. * 获取请求配置
  2313. * @param method 当前请求方法,默认get
  2314. * @param userRequestOption 用户的请求配置
  2315. * @param resolve promise回调
  2316. * @param reject 抛出错误回调
  2317. */
  2318. getRequestOption(method, userRequestOption, resolve, reject) {
  2319. let that = this;
  2320. let requestOption = {
  2321. url: userRequestOption.url || this.context.#defaultDetails.url,
  2322. method: (method || "GET").toString().toUpperCase().trim(),
  2323. timeout: userRequestOption.timeout || this.context.#defaultDetails.timeout,
  2324. responseType: userRequestOption.responseType ||
  2325. this.context.#defaultDetails.responseType,
  2326. /* 对象使用深拷贝 */
  2327. headers: utils.deepClone(this.context.#defaultDetails.headers),
  2328. data: userRequestOption.data || this.context.#defaultDetails.data,
  2329. redirect: userRequestOption.redirect || this.context.#defaultDetails.redirect,
  2330. cookie: userRequestOption.cookie || this.context.#defaultDetails.cookie,
  2331. cookiePartition: userRequestOption.cookiePartition ||
  2332. this.context.#defaultDetails.cookiePartition,
  2333. binary: userRequestOption.binary || this.context.#defaultDetails.binary,
  2334. nocache: userRequestOption.nocache || this.context.#defaultDetails.nocache,
  2335. revalidate: userRequestOption.revalidate ||
  2336. this.context.#defaultDetails.revalidate,
  2337. /* 对象使用深拷贝 */
  2338. context: utils.deepClone(userRequestOption.context || this.context.#defaultDetails.context),
  2339. overrideMimeType: userRequestOption.overrideMimeType ||
  2340. this.context.#defaultDetails.overrideMimeType,
  2341. anonymous: userRequestOption.anonymous || this.context.#defaultDetails.anonymous,
  2342. fetch: userRequestOption.fetch || this.context.#defaultDetails.fetch,
  2343. /* 对象使用深拷贝 */
  2344. fetchInit: utils.deepClone(this.context.#defaultDetails.fetchInit),
  2345. allowInterceptConfig: {
  2346. beforeRequest: this.context.#defaultDetails
  2347. .allowInterceptConfig.beforeRequest,
  2348. afterResponseSuccess: this.context.#defaultDetails
  2349. .allowInterceptConfig.afterResponseSuccess,
  2350. afterResponseError: this.context.#defaultDetails
  2351. .allowInterceptConfig.afterResponseError,
  2352. },
  2353. user: userRequestOption.user || this.context.#defaultDetails.user,
  2354. password: userRequestOption.password || this.context.#defaultDetails.password,
  2355. onabort(...args) {
  2356. that.context.HttpxCallBack.onAbort(userRequestOption, resolve, reject, args);
  2357. },
  2358. onerror(...args) {
  2359. that.context.HttpxCallBack.onError(userRequestOption, resolve, reject, args);
  2360. },
  2361. onloadstart(...args) {
  2362. that.context.HttpxCallBack.onLoadStart(userRequestOption, args);
  2363. },
  2364. onprogress(...args) {
  2365. that.context.HttpxCallBack.onProgress(userRequestOption, args);
  2366. },
  2367. onreadystatechange(...args) {
  2368. that.context.HttpxCallBack.onReadyStateChange(userRequestOption, args);
  2369. },
  2370. ontimeout(...args) {
  2371. that.context.HttpxCallBack.onTimeout(userRequestOption, resolve, reject, args);
  2372. },
  2373. onload(...args) {
  2374. that.context.HttpxCallBack.onLoad(userRequestOption, resolve, reject, args);
  2375. },
  2376. };
  2377. // 补全allowInterceptConfig参数
  2378. if (typeof userRequestOption.allowInterceptConfig === "boolean") {
  2379. Object.keys(requestOption.allowInterceptConfig).forEach((keyName) => {
  2380. Reflect.set(requestOption.allowInterceptConfig, keyName, userRequestOption.allowInterceptConfig);
  2381. });
  2382. }
  2383. else {
  2384. if (typeof userRequestOption.allowInterceptConfig === "object" &&
  2385. userRequestOption.allowInterceptConfig != null) {
  2386. Object.keys(userRequestOption.allowInterceptConfig).forEach((keyName) => {
  2387. let value = Reflect.get(userRequestOption.allowInterceptConfig, keyName);
  2388. if (typeof value === "boolean" &&
  2389. Reflect.has(requestOption.allowInterceptConfig, keyName)) {
  2390. Reflect.set(requestOption.allowInterceptConfig, keyName, value);
  2391. }
  2392. });
  2393. }
  2394. }
  2395. if (typeof this.context.GM_Api.xmlHttpRequest !== "function") {
  2396. // GM函数不存在,强制使用fetch
  2397. requestOption.fetch = true;
  2398. }
  2399. if (typeof requestOption.headers === "object") {
  2400. if (typeof userRequestOption.headers === "object") {
  2401. Object.keys(userRequestOption.headers).forEach((keyName, index) => {
  2402. if (keyName in requestOption.headers &&
  2403. userRequestOption.headers?.[keyName] == null) {
  2404. /* 在默认的header中存在,且设置它新的值为空,那么就是默认的值 */
  2405. Reflect.deleteProperty(requestOption.headers, keyName);
  2406. }
  2407. else {
  2408. requestOption.headers[keyName] =
  2409. userRequestOption?.headers?.[keyName];
  2410. }
  2411. });
  2412. }
  2413. }
  2414. else {
  2415. /* 默认的headers不是对象,那么就直接使用新的 */
  2416. Reflect.set(requestOption, "headers", userRequestOption.headers);
  2417. }
  2418. if (typeof requestOption.fetchInit === "object") {
  2419. /* 使用assign替换且添加 */
  2420. if (typeof userRequestOption.fetchInit === "object") {
  2421. Object.keys(userRequestOption.fetchInit).forEach((keyName, index) => {
  2422. if (keyName in requestOption.fetchInit &&
  2423. userRequestOption.fetchInit[keyName] == null) {
  2424. /* 在默认的fetchInit中存在,且设置它新的值为空,那么就是默认的值 */
  2425. Reflect.deleteProperty(requestOption.fetchInit, keyName);
  2426. }
  2427. else {
  2428. Reflect.set(requestOption.fetchInit, keyName, Reflect.get(userRequestOption.fetchInit, keyName));
  2429. }
  2430. });
  2431. }
  2432. }
  2433. else {
  2434. Reflect.set(requestOption, "fetchInit", userRequestOption.fetchInit);
  2435. }
  2436. // 处理新的cookiePartition
  2437. if (typeof requestOption.cookiePartition === "object" &&
  2438. requestOption.cookiePartition != null) {
  2439. if (Reflect.has(requestOption.cookiePartition, "topLevelSite") &&
  2440. typeof requestOption.cookiePartition.topLevelSite !== "string") {
  2441. // topLevelSite必须是字符串
  2442. Reflect.deleteProperty(requestOption.cookiePartition, "topLevelSite");
  2443. }
  2444. }
  2445. /* 完善请求的url */
  2446. try {
  2447. new URL(requestOption.url);
  2448. }
  2449. catch (error) {
  2450. if (requestOption.url.startsWith("//")) {
  2451. // 补充https:
  2452. requestOption.url = globalThis.location.protocol + requestOption.url;
  2453. }
  2454. else if (requestOption.url.startsWith("/")) {
  2455. // 补充origin
  2456. requestOption.url = globalThis.location.origin + requestOption.url;
  2457. }
  2458. else {
  2459. // 补充origin+/
  2460. requestOption.url =
  2461. globalThis.location.origin + "/" + requestOption.url;
  2462. }
  2463. }
  2464. if (requestOption.fetchInit && !requestOption.fetch) {
  2465. // 清空fetchInit
  2466. Reflect.deleteProperty(requestOption, "fetchInit");
  2467. }
  2468. // 转换data类型
  2469. try {
  2470. /** 是否对数据进行处理 */
  2471. let processData = userRequestOption.processData ?? true;
  2472. if (requestOption.data != null && processData) {
  2473. let method = requestOption.method;
  2474. if (method === "GET" || method === "HEAD") {
  2475. // GET类型,data如果有,那么需要转为searchParams
  2476. let urlObj = new URL(requestOption.url);
  2477. let urlSearch = "";
  2478. let isHandler = false;
  2479. if (typeof requestOption.data === "string") {
  2480. isHandler = true;
  2481. urlSearch = requestOption.data;
  2482. }
  2483. else if (typeof requestOption.data === "object") {
  2484. isHandler = true;
  2485. // URLSearchParams参数可以转普通的string:string,包括FormData
  2486. // @ts-ignore
  2487. let searchParams = new URLSearchParams(requestOption.data);
  2488. urlSearch = searchParams.toString();
  2489. }
  2490. if (isHandler) {
  2491. // GET/HEAD请求不支持data参数
  2492. // 对data进行处理了才可以删除
  2493. Reflect.deleteProperty(requestOption, "data");
  2494. }
  2495. if (urlSearch != "") {
  2496. if (urlObj.search === "") {
  2497. // url没有search参数,直接覆盖
  2498. urlObj.search = urlSearch;
  2499. }
  2500. else {
  2501. // 有search参数
  2502. if (urlObj.search.endsWith("&")) {
  2503. // xxx=xxx&
  2504. urlObj.search = urlObj.search + urlSearch;
  2505. }
  2506. else {
  2507. // xxx=xxx&xxx=
  2508. urlObj.search = urlObj.search + "&" + urlSearch;
  2509. }
  2510. }
  2511. }
  2512. requestOption.url = urlObj.toString();
  2513. }
  2514. else if (method === "POST" && requestOption.headers != null) {
  2515. // POST类型,data如果是FormData,那么需要转为string
  2516. let headersKeyList = Object.keys(requestOption.headers);
  2517. let ContentTypeIndex = headersKeyList.findIndex((headerKey) => {
  2518. return (headerKey.trim().toLowerCase() === "content-type" &&
  2519. typeof requestOption.headers[headerKey] === "string");
  2520. });
  2521. if (ContentTypeIndex !== -1) {
  2522. let ContentTypeKey = headersKeyList[ContentTypeIndex];
  2523. let ContentType = requestOption.headers[ContentTypeKey];
  2524. // 设置了Content-Type
  2525. if (ContentType.includes("application/json")) {
  2526. // application/json
  2527. if (requestOption.data instanceof FormData) {
  2528. const entries = {};
  2529. requestOption.data.forEach((value, key) => {
  2530. entries[key] = value;
  2531. });
  2532. requestOption.data = JSON.stringify(entries);
  2533. }
  2534. else if (typeof requestOption.data === "object") {
  2535. requestOption.data = JSON.stringify(requestOption.data);
  2536. }
  2537. }
  2538. else if (ContentType.includes("application/x-www-form-urlencoded")) {
  2539. // application/x-www-form-urlencoded
  2540. if (typeof requestOption.data === "object") {
  2541. requestOption.data = new URLSearchParams(
  2542. // @ts-ignore
  2543. requestOption.data).toString();
  2544. }
  2545. }
  2546. else if (ContentType.includes("multipart/form-data")) {
  2547. // multipart/form-data
  2548. if (requestOption.data instanceof FormData) {
  2549. Reflect.deleteProperty(requestOption.headers, ContentTypeKey);
  2550. }
  2551. }
  2552. }
  2553. }
  2554. }
  2555. }
  2556. catch (error) {
  2557. console.warn("Httpx ==> 转换data参数错误", error);
  2558. }
  2559. return requestOption;
  2560. },
  2561. /**
  2562. * 处理发送请求的配置,去除值为undefined、空function的值
  2563. * @param option
  2564. */
  2565. removeRequestNullOption(option) {
  2566. Object.keys(option).forEach((keyName) => {
  2567. if (option[keyName] == null ||
  2568. (option[keyName] instanceof Function &&
  2569. utils.isNull(option[keyName]))) {
  2570. Reflect.deleteProperty(option, keyName);
  2571. return;
  2572. }
  2573. });
  2574. if (utils.isNull(option.url)) {
  2575. throw new TypeError(`Utils.Httpx 参数 url不符合要求: ${option.url}`);
  2576. }
  2577. return option;
  2578. },
  2579. /**
  2580. * 处理fetch的配置
  2581. * @param option
  2582. */
  2583. handleFetchOption(option) {
  2584. /**
  2585. * fetch的请求配置
  2586. **/
  2587. let fetchRequestOption = {};
  2588. if ((option.method === "GET" || option.method === "HEAD") &&
  2589. option.data != null) {
  2590. /* GET 或 HEAD 方法的请求不能包含 body 信息 */
  2591. Reflect.deleteProperty(option, "data");
  2592. }
  2593. /* 中止信号控制器 */
  2594. let abortController = new AbortController();
  2595. let signal = abortController.signal;
  2596. signal.onabort = () => {
  2597. option.onabort({
  2598. isFetch: true,
  2599. responseText: "",
  2600. response: null,
  2601. readyState: 4,
  2602. responseHeaders: "",
  2603. status: 0,
  2604. statusText: "",
  2605. error: "aborted",
  2606. });
  2607. };
  2608. // 设置请求
  2609. fetchRequestOption.method = option.method ?? "GET";
  2610. // 设置请求头
  2611. fetchRequestOption.headers = option.headers;
  2612. // 设置请求体
  2613. fetchRequestOption.body = option.data;
  2614. // 设置跨域
  2615. fetchRequestOption.mode = "cors";
  2616. // 设置包含
  2617. fetchRequestOption.credentials = "include";
  2618. // 设置不缓存
  2619. fetchRequestOption.cache = "no-cache";
  2620. // 设置始终重定向
  2621. fetchRequestOption.redirect = "follow";
  2622. // 设置referer跨域
  2623. fetchRequestOption.referrerPolicy = "origin-when-cross-origin";
  2624. // 设置信号中断
  2625. fetchRequestOption.signal = signal;
  2626. Object.assign(fetchRequestOption, option.fetchInit || {});
  2627. return {
  2628. fetchOption: option,
  2629. fetchRequestOption: fetchRequestOption,
  2630. abortController: abortController,
  2631. };
  2632. },
  2633. };
  2634. HttpxCallBack = {
  2635. context: this,
  2636. /**
  2637. * onabort请求被取消-触发
  2638. * @param details 配置
  2639. * @param resolve 回调
  2640. * @param reject 抛出错误
  2641. * @param argsResult 返回的参数列表
  2642. */
  2643. async onAbort(details, resolve, reject, argsResult) {
  2644. // console.log(argsResult);
  2645. if ("onabort" in details) {
  2646. details.onabort.apply(this, argsResult);
  2647. }
  2648. else if ("onabort" in this.context.#defaultDetails) {
  2649. this.context.#defaultDetails.onabort.apply(this, argsResult);
  2650. }
  2651. let response = argsResult;
  2652. if (response.length) {
  2653. response = response[0];
  2654. }
  2655. if ((await this.context.HttpxResponseHook.errorResponseCallBack({
  2656. type: "onabort",
  2657. error: new TypeError("request canceled"),
  2658. response: null,
  2659. details: details,
  2660. })) == null) {
  2661. // reject(new TypeError("response is intercept with onabort"));
  2662. return;
  2663. }
  2664. resolve({
  2665. data: response,
  2666. details: details,
  2667. msg: "请求被取消",
  2668. status: false,
  2669. statusCode: -1,
  2670. type: "onabort",
  2671. });
  2672. },
  2673. /**
  2674. * onerror请求异常-触发
  2675. * @param details 配置
  2676. * @param resolve 回调
  2677. * @param reject 抛出错误
  2678. * @param argsResult 返回的参数列表
  2679. */
  2680. async onError(details, resolve, reject, argsResult) {
  2681. // console.log(argsResult);
  2682. if ("onerror" in details) {
  2683. details.onerror.apply(this, argsResult);
  2684. }
  2685. else if ("onerror" in this.context.#defaultDetails) {
  2686. this.context.#defaultDetails.onerror.apply(this, argsResult);
  2687. }
  2688. let response = argsResult;
  2689. if (response.length) {
  2690. response = response[0];
  2691. }
  2692. if ((await this.context.HttpxResponseHook.errorResponseCallBack({
  2693. type: "onerror",
  2694. error: new TypeError("request error"),
  2695. response: response,
  2696. details: details,
  2697. })) == null) {
  2698. // reject(new TypeError("response is intercept with onerror"));
  2699. return;
  2700. }
  2701. resolve({
  2702. data: response,
  2703. details: details,
  2704. msg: "请求异常",
  2705. status: false,
  2706. statusCode: response["status"],
  2707. type: "onerror",
  2708. });
  2709. },
  2710. /**
  2711. * ontimeout请求超时-触发
  2712. * @param details 配置
  2713. * @param resolve 回调
  2714. * @param reject 抛出错误
  2715. * @param argsResult 返回的参数列表
  2716. */
  2717. async onTimeout(details, resolve, reject, argsResult) {
  2718. // console.log(argsResult);
  2719. if ("ontimeout" in details) {
  2720. details.ontimeout.apply(this, argsResult);
  2721. }
  2722. else if ("ontimeout" in this.context.#defaultDetails) {
  2723. this.context.#defaultDetails.ontimeout.apply(this, argsResult);
  2724. }
  2725. let response = argsResult;
  2726. if (response.length) {
  2727. response = response[0];
  2728. }
  2729. if ((await this.context.HttpxResponseHook.errorResponseCallBack({
  2730. type: "ontimeout",
  2731. error: new TypeError("request timeout"),
  2732. response: (argsResult || [null])[0],
  2733. details: details,
  2734. })) == null) {
  2735. // reject(new TypeError("response is intercept with ontimeout"));
  2736. return;
  2737. }
  2738. resolve({
  2739. data: response,
  2740. details: details,
  2741. msg: "请求超时",
  2742. status: false,
  2743. statusCode: 0,
  2744. type: "ontimeout",
  2745. });
  2746. },
  2747. /**
  2748. * onloadstart请求开始-触发
  2749. * @param details 配置
  2750. * @param argsResult 返回的参数列表
  2751. */
  2752. onLoadStart(details, argsResult) {
  2753. // console.log(argsResult);
  2754. if ("onloadstart" in details) {
  2755. details.onloadstart.apply(this, argsResult);
  2756. }
  2757. else if ("onloadstart" in this.context.#defaultDetails) {
  2758. this.context.#defaultDetails.onloadstart.apply(this, argsResult);
  2759. }
  2760. },
  2761. /**
  2762. * onload加载完毕-触发
  2763. * @param details 请求的配置
  2764. * @param resolve 回调
  2765. * @param reject 抛出错误
  2766. * @param argsResult 返回的参数列表
  2767. */
  2768. async onLoad(details, resolve, reject, argsResult) {
  2769. // console.log(argsResult);
  2770. /* X浏览器会因为设置了responseType导致不返回responseText */
  2771. let originResponse = argsResult[0];
  2772. /* responseText为空,response不为空的情况 */
  2773. if (utils.isNull(originResponse["responseText"]) &&
  2774. utils.isNotNull(originResponse["response"])) {
  2775. if (typeof originResponse["response"] === "object") {
  2776. utils.tryCatch().run(() => {
  2777. originResponse["responseText"] = JSON.stringify(originResponse["response"]);
  2778. });
  2779. }
  2780. else {
  2781. originResponse["responseText"] = originResponse["response"];
  2782. }
  2783. }
  2784. /* response为空,responseText不为空的情况 */
  2785. if (originResponse["response"] == null &&
  2786. typeof originResponse["responseText"] === "string" &&
  2787. originResponse["responseText"].trim() !== "") {
  2788. /** 原始的请求text */
  2789. let httpxResponseText = originResponse.responseText;
  2790. // 自定义个新的response
  2791. let httpxResponse = httpxResponseText;
  2792. if (details.responseType === "json") {
  2793. httpxResponse = utils.toJSON(httpxResponseText);
  2794. }
  2795. else if (details.responseType === "document") {
  2796. let parser = new DOMParser();
  2797. httpxResponse = parser.parseFromString(httpxResponseText, "text/html");
  2798. }
  2799. else if (details.responseType === "arraybuffer") {
  2800. let encoder = new TextEncoder();
  2801. let arrayBuffer = encoder.encode(httpxResponseText);
  2802. httpxResponse = arrayBuffer;
  2803. }
  2804. else if (details.responseType === "blob") {
  2805. let encoder = new TextEncoder();
  2806. let arrayBuffer = encoder.encode(httpxResponseText);
  2807. httpxResponse = new Blob([arrayBuffer]);
  2808. }
  2809. // 尝试覆盖原response
  2810. try {
  2811. let setStatus = Reflect.set(originResponse, "response", httpxResponse);
  2812. if (!setStatus) {
  2813. console.warn("[Httpx-HttpxCallBack.oonLoad] 覆盖原始 response 失败,尝试添加新的httpxResponse");
  2814. try {
  2815. Reflect.set(originResponse, "httpxResponse", httpxResponse);
  2816. }
  2817. catch (error) {
  2818. console.warn("[Httpx-HttpxCallBack.oonLoad] httpxResponse 无法被覆盖");
  2819. }
  2820. }
  2821. }
  2822. catch (error) {
  2823. console.warn("[Httpx-HttpxCallBack.oonLoad] 原始 response 无法被覆盖,尝试添加新的httpxResponse");
  2824. try {
  2825. Reflect.set(originResponse, "httpxResponse", httpxResponse);
  2826. }
  2827. catch (error) {
  2828. console.warn("[Httpx-HttpxCallBack.oonLoad] httpxResponse 无法被覆盖");
  2829. }
  2830. }
  2831. }
  2832. /* Stay扩展中没有finalUrl,对应的是responseURL */
  2833. let originResponseURL = Reflect.get(originResponse, "responseURL");
  2834. if (originResponse["finalUrl"] == null && originResponseURL != null) {
  2835. Reflect.set(originResponse, "finalUrl", originResponseURL);
  2836. }
  2837. /* 状态码2xx都是成功的 */
  2838. if (Math.floor(originResponse.status / 100) === 2) {
  2839. if ((await this.context.HttpxResponseHook.successResponseCallBack(originResponse, details)) == null) {
  2840. // reject(new TypeError("response is intercept with onloada"));
  2841. return;
  2842. }
  2843. resolve({
  2844. data: originResponse,
  2845. details: details,
  2846. msg: "请求成功",
  2847. status: true,
  2848. statusCode: originResponse.status,
  2849. type: "onload",
  2850. });
  2851. }
  2852. else {
  2853. this.context.HttpxCallBack.onError(details, resolve, reject, argsResult);
  2854. }
  2855. },
  2856. /**
  2857. * onprogress上传进度-触发
  2858. * @param details 配置
  2859. * @param argsResult 返回的参数列表
  2860. */
  2861. onProgress(details, argsResult) {
  2862. // console.log(argsResult);
  2863. if ("onprogress" in details) {
  2864. details.onprogress.apply(this, argsResult);
  2865. }
  2866. else if ("onprogress" in this.context.#defaultDetails) {
  2867. this.context.#defaultDetails.onprogress.apply(this, argsResult);
  2868. }
  2869. },
  2870. /**
  2871. * onreadystatechange准备状态改变-触发
  2872. * @param details 配置
  2873. * @param argsResult 返回的参数列表
  2874. */
  2875. onReadyStateChange(details, argsResult) {
  2876. // console.log(argsResult);
  2877. if ("onreadystatechange" in details) {
  2878. details.onreadystatechange.apply(this, argsResult);
  2879. }
  2880. else if ("onreadystatechange" in this.context.#defaultDetails) {
  2881. this.context.#defaultDetails.onreadystatechange.apply(this, argsResult);
  2882. }
  2883. },
  2884. };
  2885. HttpxRequest = {
  2886. context: this,
  2887. /**
  2888. * 发送请求
  2889. * @param details
  2890. */
  2891. async request(details) {
  2892. if (this.context.#LOG_DETAILS) {
  2893. console.log("[Httpx-HttpxRequest.request] 请求前的配置👇", details);
  2894. }
  2895. if (typeof this.context.HttpxRequestHook.beforeRequestCallBack ===
  2896. "function") {
  2897. let hookResult = await this.context.HttpxRequestHook.beforeRequestCallBack(details);
  2898. if (hookResult == null) {
  2899. return;
  2900. }
  2901. }
  2902. if (details.fetch) {
  2903. // 使用fetch请求
  2904. const { fetchOption: fetchOption, fetchRequestOption: fetchRequestOption, abortController, } = this.context.HttpxRequestOption.handleFetchOption(details);
  2905. return this.fetch(fetchOption, fetchRequestOption, abortController);
  2906. }
  2907. else {
  2908. // 使用GM_xmlHttpRequest请求
  2909. return this.xmlHttpRequest(details);
  2910. }
  2911. },
  2912. /**
  2913. * 使用油猴函数GM_xmlhttpRequest发送请求
  2914. * @param details
  2915. */
  2916. xmlHttpRequest(details) {
  2917. return this.context.GM_Api.xmlHttpRequest(details);
  2918. },
  2919. /**
  2920. * 使用fetch发送请求
  2921. * @param option
  2922. * @param fetchRequestOption
  2923. * @param abortController
  2924. */
  2925. fetch(option, fetchRequestOption, abortController) {
  2926. fetch(option.url, fetchRequestOption)
  2927. .then(async (fetchResponse) => {
  2928. /** 自定义的response */
  2929. let httpxResponse = {
  2930. isFetch: true,
  2931. finalUrl: fetchResponse.url,
  2932. readyState: 4,
  2933. // @ts-ignore
  2934. status: fetchResponse.status,
  2935. statusText: fetchResponse.statusText,
  2936. // @ts-ignore
  2937. response: undefined,
  2938. responseFetchHeaders: fetchResponse.headers,
  2939. responseHeaders: "",
  2940. // @ts-ignore
  2941. responseText: undefined,
  2942. responseType: option.responseType,
  2943. responseXML: undefined,
  2944. };
  2945. Object.assign(httpxResponse, option.context || {});
  2946. // 把headers转为字符串
  2947. for (const [key, value] of fetchResponse.headers.entries()) {
  2948. httpxResponse.responseHeaders += `${key}: ${value}\n`;
  2949. }
  2950. /** 请求返回的类型 */
  2951. const fetchResponseType = fetchResponse.headers.get("Content-Type");
  2952. /* 如果需要stream,且获取到的是stream,那直接返回 */
  2953. if (option.responseType === "stream" ||
  2954. (fetchResponse.headers.has("Content-Type") &&
  2955. fetchResponse.headers
  2956. .get("Content-Type")
  2957. .includes("text/event-stream"))) {
  2958. Reflect.set(httpxResponse, "isStream", true);
  2959. Reflect.set(httpxResponse, "response", fetchResponse.body);
  2960. Reflect.deleteProperty(httpxResponse, "responseText");
  2961. Reflect.deleteProperty(httpxResponse, "responseXML");
  2962. option.onload(httpxResponse);
  2963. return;
  2964. }
  2965. /** 响应 */
  2966. let response = "";
  2967. /** 响应字符串 */
  2968. let responseText = "";
  2969. /** 响应xml文档 */
  2970. let responseXML = "";
  2971. /** 先获取二进制数据 */
  2972. let arrayBuffer = await fetchResponse.arrayBuffer();
  2973. /** 数据编码 */
  2974. let encoding = "utf-8";
  2975. if (fetchResponse.headers.has("Content-Type")) {
  2976. let charsetMatched = fetchResponse.headers
  2977. .get("Content-Type")
  2978. ?.match(/charset=(.+)/);
  2979. if (charsetMatched) {
  2980. encoding = charsetMatched[1];
  2981. encoding = encoding.toLowerCase();
  2982. }
  2983. }
  2984. // Failed to construct 'TextDecoder': The encoding label provided ('"UTF-8"') is invalid.
  2985. // 去除引号
  2986. encoding = encoding.replace(/('|")/gi, "");
  2987. // 编码
  2988. let textDecoder = new TextDecoder(encoding);
  2989. responseText = textDecoder.decode(arrayBuffer);
  2990. response = responseText;
  2991. if (option.responseType === "arraybuffer") {
  2992. // response返回格式是二进制流
  2993. response = arrayBuffer;
  2994. }
  2995. else if (option.responseType === "blob") {
  2996. // response返回格式是blob
  2997. response = new Blob([arrayBuffer]);
  2998. }
  2999. else if (option.responseType === "json" ||
  3000. (typeof fetchResponseType === "string" &&
  3001. fetchResponseType.includes("application/json"))) {
  3002. // response返回格式是JSON格式
  3003. response = utils.toJSON(responseText);
  3004. }
  3005. else if (option.responseType === "document" ||
  3006. option.responseType == null) {
  3007. // response返回格式是文档格式
  3008. let parser = new DOMParser();
  3009. response = parser.parseFromString(responseText, "text/html");
  3010. }
  3011. // 转为XML结构
  3012. let parser = new DOMParser();
  3013. responseXML = parser.parseFromString(responseText, "text/xml");
  3014. Reflect.set(httpxResponse, "response", response);
  3015. Reflect.set(httpxResponse, "responseText", responseText);
  3016. Reflect.set(httpxResponse, "responseXML", responseXML);
  3017. // 执行回调
  3018. option.onload(httpxResponse);
  3019. })
  3020. .catch((error) => {
  3021. if (error.name === "AbortError") {
  3022. return;
  3023. }
  3024. option.onerror({
  3025. isFetch: true,
  3026. finalUrl: option.url,
  3027. readyState: 4,
  3028. status: 0,
  3029. statusText: "",
  3030. responseHeaders: "",
  3031. responseText: "",
  3032. error: error,
  3033. });
  3034. });
  3035. option.onloadstart({
  3036. isFetch: true,
  3037. finalUrl: option.url,
  3038. readyState: 1,
  3039. responseHeaders: "",
  3040. responseText: "",
  3041. status: 0,
  3042. statusText: "",
  3043. });
  3044. return {
  3045. abort() {
  3046. abortController.abort();
  3047. },
  3048. };
  3049. },
  3050. };
  3051. /**
  3052. * 默认配置
  3053. */
  3054. #defaultDetails = {
  3055. url: undefined,
  3056. timeout: 5000,
  3057. async: false,
  3058. responseType: undefined,
  3059. headers: undefined,
  3060. data: undefined,
  3061. redirect: undefined,
  3062. cookie: undefined,
  3063. cookiePartition: undefined,
  3064. binary: undefined,
  3065. nocache: undefined,
  3066. revalidate: undefined,
  3067. context: undefined,
  3068. overrideMimeType: undefined,
  3069. anonymous: undefined,
  3070. fetch: undefined,
  3071. fetchInit: undefined,
  3072. allowInterceptConfig: {
  3073. beforeRequest: true,
  3074. afterResponseSuccess: true,
  3075. afterResponseError: true,
  3076. },
  3077. user: undefined,
  3078. password: undefined,
  3079. onabort() { },
  3080. onerror() { },
  3081. ontimeout() { },
  3082. onloadstart() { },
  3083. onreadystatechange() { },
  3084. onprogress() { },
  3085. };
  3086. /**
  3087. * 当前使用请求时,输出请求的配置
  3088. */
  3089. #LOG_DETAILS = false;
  3090. /**
  3091. * 实例化,可传入GM_xmlhttpRequest,未传入则使用window.fetch
  3092. * @param xmlHttpRequest
  3093. */
  3094. constructor(xmlHttpRequest) {
  3095. if (typeof xmlHttpRequest !== "function") {
  3096. console.warn("[Httpx-constructor] 未传入GM_xmlhttpRequest函数或传入的GM_xmlhttpRequest不是Function,将默认使用window.fetch");
  3097. }
  3098. this.interceptors.request.context = this;
  3099. this.interceptors.response.context = this;
  3100. this.GM_Api.xmlHttpRequest = xmlHttpRequest;
  3101. }
  3102. /**
  3103. * 覆盖当前配置
  3104. * @param details
  3105. */
  3106. config(details = {}) {
  3107. if ("logDetails" in details && typeof details["logDetails"] === "boolean") {
  3108. this.#LOG_DETAILS = details["logDetails"];
  3109. }
  3110. this.#defaultDetails = utils.assign(this.#defaultDetails, details);
  3111. }
  3112. /**
  3113. * 拦截器
  3114. */
  3115. interceptors = {
  3116. /**
  3117. * 请求拦截器
  3118. */
  3119. request: {
  3120. context: null,
  3121. /**
  3122. * 添加拦截器
  3123. * @param fn 设置的请求前回调函数,如果返回配置,则使用返回的配置,如果返回null|undefined,则阻止请求
  3124. */
  3125. use(fn) {
  3126. if (typeof fn !== "function") {
  3127. console.warn("[Httpx-interceptors-request] 请传入拦截器函数");
  3128. return;
  3129. }
  3130. return this.context.HttpxRequestHook.add(fn);
  3131. },
  3132. /**
  3133. * 移除拦截器
  3134. * @param id 通过use返回的id
  3135. */
  3136. eject(id) {
  3137. return this.context.HttpxRequestHook.delete(id);
  3138. },
  3139. /**
  3140. * 移除所有拦截器
  3141. */
  3142. ejectAll() {
  3143. this.context.HttpxRequestHook.clearAll();
  3144. },
  3145. },
  3146. /**
  3147. * 响应拦截器
  3148. */
  3149. response: {
  3150. context: null,
  3151. /**
  3152. * 添加拦截器
  3153. * @param successFn 设置的响应后回调函数,如果返回响应,则使用返回的响应,如果返回null|undefined,则阻止响应
  3154. * + 2xx 范围内的状态码都会触发该函数
  3155. * @param errorFn 设置的响应后回调函数,如果返回响应,则使用返回的响应,如果返回null|undefined,则阻止响应
  3156. * + 超出 2xx 范围的状态码都会触发该函数
  3157. */
  3158. use(successFn, errorFn) {
  3159. if (typeof successFn !== "function" && typeof errorFn !== "function") {
  3160. console.warn("[Httpx-interceptors-response] 必须传入一个拦截器函数");
  3161. return;
  3162. }
  3163. return this.context.HttpxResponseHook.add(successFn, errorFn);
  3164. },
  3165. /**
  3166. * 移除拦截器
  3167. * @param id 通过use返回的id
  3168. */
  3169. eject(id) {
  3170. return this.context.HttpxResponseHook.delete(id);
  3171. },
  3172. /**
  3173. * 移除所有拦截器
  3174. */
  3175. ejectAll() {
  3176. this.context.HttpxResponseHook.clearAll();
  3177. },
  3178. },
  3179. };
  3180. /**
  3181. * 修改xmlHttpRequest
  3182. * @param httpRequest 网络请求函数
  3183. */
  3184. setXMLHttpRequest(httpRequest) {
  3185. this.GM_Api.xmlHttpRequest = httpRequest;
  3186. }
  3187. /**
  3188. * GET 请求
  3189. * @param url 网址
  3190. * @param details 配置
  3191. */
  3192. get(...args // @ts-ignore
  3193. ) {
  3194. let userRequestOption = this.HttpxRequestOption.handleBeforeRequestOption(...args);
  3195. let abortFn = null;
  3196. let promise = new globalThis.Promise(async (resolve, reject) => {
  3197. let requestOption = this.HttpxRequestOption.getRequestOption("GET", userRequestOption, resolve, reject);
  3198. Reflect.deleteProperty(requestOption, "onprogress");
  3199. this.HttpxRequestOption.removeRequestNullOption(requestOption);
  3200. const requestResult = await this.HttpxRequest.request(requestOption);
  3201. if (requestResult != null &&
  3202. typeof requestResult.abort === "function") {
  3203. abortFn = requestResult.abort;
  3204. }
  3205. });
  3206. // @ts-ignore
  3207. promise.abort = () => {
  3208. if (typeof abortFn === "function") {
  3209. abortFn();
  3210. }
  3211. };
  3212. // @ts-ignore
  3213. return promise;
  3214. }
  3215. /**
  3216. * POST 请求
  3217. */
  3218. post(...args // @ts-ignore
  3219. ) {
  3220. let userRequestOption = this.HttpxRequestOption.handleBeforeRequestOption(...args);
  3221. let abortFn = null;
  3222. let promise = new Promise(async (resolve, reject) => {
  3223. let requestOption = this.HttpxRequestOption.getRequestOption("POST", userRequestOption, resolve, reject);
  3224. // @ts-ignore
  3225. requestOption =
  3226. this.HttpxRequestOption.removeRequestNullOption(requestOption);
  3227. const requestResult = await this.HttpxRequest.request(requestOption);
  3228. if (requestResult != null &&
  3229. typeof requestResult.abort === "function") {
  3230. abortFn = requestResult.abort;
  3231. }
  3232. });
  3233. // @ts-ignore
  3234. promise.abort = () => {
  3235. if (typeof abortFn === "function") {
  3236. abortFn();
  3237. }
  3238. };
  3239. // @ts-ignore
  3240. return promise;
  3241. }
  3242. /**
  3243. * HEAD 请求
  3244. */
  3245. head(...args // @ts-ignore
  3246. ) {
  3247. let userRequestOption = this.HttpxRequestOption.handleBeforeRequestOption(...args);
  3248. let abortFn = null;
  3249. let promise = new Promise(async (resolve, reject) => {
  3250. let requestOption = this.HttpxRequestOption.getRequestOption("HEAD", userRequestOption, resolve, reject);
  3251. Reflect.deleteProperty(requestOption, "onprogress");
  3252. // @ts-ignore
  3253. requestOption =
  3254. this.HttpxRequestOption.removeRequestNullOption(requestOption);
  3255. const requestResult = await this.HttpxRequest.request(requestOption);
  3256. if (requestResult != null &&
  3257. typeof requestResult.abort === "function") {
  3258. abortFn = requestResult.abort;
  3259. }
  3260. });
  3261. // @ts-ignore
  3262. promise.abort = () => {
  3263. if (typeof abortFn === "function") {
  3264. abortFn();
  3265. }
  3266. };
  3267. // @ts-ignore
  3268. return promise;
  3269. }
  3270. /**
  3271. * OPTIONS 请求
  3272. */
  3273. options(...args // @ts-ignore
  3274. ) {
  3275. let userRequestOption = this.HttpxRequestOption.handleBeforeRequestOption(...args);
  3276. let abortFn = null;
  3277. let promise = new Promise(async (resolve, reject) => {
  3278. let requestOption = this.HttpxRequestOption.getRequestOption("OPTIONS", userRequestOption, resolve, reject);
  3279. Reflect.deleteProperty(requestOption, "onprogress");
  3280. // @ts-ignore
  3281. requestOption =
  3282. this.HttpxRequestOption.removeRequestNullOption(requestOption);
  3283. const requestResult = await this.HttpxRequest.request(requestOption);
  3284. if (requestResult != null &&
  3285. typeof requestResult.abort === "function") {
  3286. abortFn = requestResult.abort;
  3287. }
  3288. });
  3289. // @ts-ignore
  3290. promise.abort = () => {
  3291. if (typeof abortFn === "function") {
  3292. abortFn();
  3293. }
  3294. };
  3295. // @ts-ignore
  3296. return promise;
  3297. }
  3298. /**
  3299. * DELETE 请求
  3300. */
  3301. delete(...args // @ts-ignore
  3302. ) {
  3303. let userRequestOption = this.HttpxRequestOption.handleBeforeRequestOption(...args);
  3304. let abortFn = null;
  3305. let promise = new Promise(async (resolve, reject) => {
  3306. let requestOption = this.HttpxRequestOption.getRequestOption("DELETE", userRequestOption, resolve, reject);
  3307. Reflect.deleteProperty(requestOption, "onprogress");
  3308. // @ts-ignore
  3309. requestOption =
  3310. this.HttpxRequestOption.removeRequestNullOption(requestOption);
  3311. const requestResult = await this.HttpxRequest.request(requestOption);
  3312. if (requestResult != null &&
  3313. typeof requestResult.abort === "function") {
  3314. abortFn = requestResult.abort;
  3315. }
  3316. });
  3317. // @ts-ignore
  3318. promise.abort = () => {
  3319. if (typeof abortFn === "function") {
  3320. abortFn();
  3321. }
  3322. };
  3323. // @ts-ignore
  3324. return promise;
  3325. }
  3326. /**
  3327. * PUT 请求
  3328. */
  3329. put(...args // @ts-ignore
  3330. ) {
  3331. let userRequestOption = this.HttpxRequestOption.handleBeforeRequestOption(...args);
  3332. let abortFn = null;
  3333. let promise = new Promise(async (resolve, reject) => {
  3334. let requestOption = this.HttpxRequestOption.getRequestOption("PUT", userRequestOption, resolve, reject);
  3335. // @ts-ignore
  3336. requestOption =
  3337. this.HttpxRequestOption.removeRequestNullOption(requestOption);
  3338. const requestResult = await this.HttpxRequest.request(requestOption);
  3339. if (requestResult != null &&
  3340. typeof requestResult.abort === "function") {
  3341. abortFn = requestResult.abort;
  3342. }
  3343. });
  3344. // @ts-ignore
  3345. promise.abort = () => {
  3346. if (typeof abortFn === "function") {
  3347. abortFn();
  3348. }
  3349. };
  3350. // @ts-ignore
  3351. return promise;
  3352. }
  3353. }
  3354.  
  3355. class indexedDB {
  3356. #dbName;
  3357. #storeName;
  3358. #dbVersion;
  3359. /* websql的版本号,由于ios的问题,版本号的写法不一样 */
  3360. // @ts-ignore
  3361. #slqVersion = "1";
  3362. /* 监听IndexDB */
  3363. #indexedDB = window.indexedDB ||
  3364. window.mozIndexedDB ||
  3365. window.webkitIndexedDB ||
  3366. window.msIndexedDB;
  3367. /* 缓存数据库,避免同一个页面重复创建和销毁 */
  3368. #db = {};
  3369. // @ts-ignore
  3370. #store = null;
  3371. /** 状态码 */
  3372. #statusCode = {
  3373. operationSuccess: {
  3374. code: 200,
  3375. msg: "操作成功",
  3376. },
  3377. operationFailed: {
  3378. code: 401,
  3379. msg: "操作失败",
  3380. },
  3381. empty: {
  3382. code: 201,
  3383. msg: "操作成功,但是没有数据",
  3384. },
  3385. openFailed: { code: 91001, msg: "打开数据库失败" },
  3386. saveFailed: { code: 91002, msg: "保存数据失败" },
  3387. getFailed: { code: 91003, msg: "获取数据失败" },
  3388. deleteFailed: { code: 91004, msg: "删除数据失败" },
  3389. deleteAllFailed: { code: 91005, msg: "清空数据库失败" },
  3390. regexpGetFailed: { code: 91006, msg: "正则获取数据失败" },
  3391. };
  3392. /**
  3393. * @param dbName 数据存储名,默认为:default_db
  3394. * @param storeName 表名,默认为:default_form
  3395. * @param dbVersion indexDB的版本号,默认为:1
  3396. */
  3397. constructor(dbName = "default_db", storeName = "default_form", dbVersion = 1) {
  3398. this.#dbName = dbName;
  3399. this.#storeName = storeName;
  3400. this.#dbVersion = dbVersion;
  3401. if (!this.#indexedDB) {
  3402. alert("很抱歉,您的浏览器不支持indexedDB");
  3403. throw new TypeError("很抱歉,您的浏览器不支持indexedDB");
  3404. }
  3405. }
  3406. /**
  3407. * 创建 “表”
  3408. * @param dbName 表名
  3409. */
  3410. createStore(dbName) {
  3411. let txn, store;
  3412. txn = this.#db[dbName].transaction(this.#storeName, "readwrite");
  3413. /* IndexDB的读写权限 */
  3414. store = txn.objectStore(this.#storeName);
  3415. this.#store = store;
  3416. return store;
  3417. }
  3418. /**
  3419. * 打开数据库
  3420. * @param callback 回调
  3421. * @param dbName 数据库名
  3422. */
  3423. open(callback, dbName) {
  3424. let that = this;
  3425. /* 打开数据库 */
  3426. /* 如果支持IndexDB */
  3427. if (!that.#db[dbName]) {
  3428. /* 如果缓存中没有,则进行数据库的创建或打开,提高效率 */
  3429. let request = that.#indexedDB.open(dbName, that.#dbVersion);
  3430. request.onerror = function (event) {
  3431. callback(null, {
  3432. code: that.#statusCode.openFailed.code,
  3433. msg: that.#statusCode.openFailed.msg,
  3434. event: event,
  3435. });
  3436. };
  3437. request.onsuccess = function (event) {
  3438. if (!that.#db[dbName]) {
  3439. let target = event.target;
  3440. that.#db[dbName] = target.result;
  3441. }
  3442. let store = that.createStore(dbName);
  3443. callback(store);
  3444. };
  3445. request.onupgradeneeded = function (event) {
  3446. let target = event.target;
  3447. that.#db[dbName] = target.result;
  3448. let store = that.#db[dbName].createObjectStore(that.#storeName, {
  3449. keyPath: "key",
  3450. });
  3451. store.transaction.oncomplete = function (event) {
  3452. callback(store);
  3453. };
  3454. };
  3455. }
  3456. else {
  3457. /* 如果缓存中已经打开了数据库,就直接使用 */
  3458. let store = this.createStore(dbName);
  3459. callback(store);
  3460. }
  3461. }
  3462. /**
  3463. * 保存数据到数据库
  3464. * @param key 数据key
  3465. * @param value 数据值
  3466. */
  3467. async save(key, value) {
  3468. let that = this;
  3469. return new Promise((resolve) => {
  3470. let dbName = this.#dbName;
  3471. let inData = {
  3472. key: key,
  3473. value: value,
  3474. };
  3475. this.open(function (idbStore) {
  3476. if (idbStore == null) {
  3477. resolve({
  3478. success: false,
  3479. code: that.#statusCode.saveFailed.code,
  3480. msg: that.#statusCode.saveFailed.msg,
  3481. });
  3482. }
  3483. else {
  3484. let request = idbStore.put(inData);
  3485. request.onsuccess = function (event) {
  3486. /* 保存成功有success 字段 */
  3487. resolve({
  3488. success: true,
  3489. code: that.#statusCode.operationSuccess.code,
  3490. msg: that.#statusCode.operationSuccess.msg,
  3491. event: event,
  3492. });
  3493. };
  3494. request.onerror = function (event) {
  3495. resolve({
  3496. success: false,
  3497. code: that.#statusCode.saveFailed.code,
  3498. msg: that.#statusCode.saveFailed.msg,
  3499. event: event,
  3500. });
  3501. };
  3502. }
  3503. }, dbName);
  3504. });
  3505. }
  3506. /**
  3507. * 判断是否存在该数据
  3508. * @param key 数据key
  3509. */
  3510. async has(key) {
  3511. let that = this;
  3512. return new Promise((resolve) => {
  3513. let dbName = this.#dbName;
  3514. this.open(function (idbStore) {
  3515. /* 判断返回的数据中是否有error字段 */
  3516. if (idbStore == null) {
  3517. resolve({
  3518. success: false,
  3519. code: that.#statusCode.getFailed.code,
  3520. msg: that.#statusCode.getFailed.msg,
  3521. });
  3522. }
  3523. else {
  3524. let request = idbStore.get(key);
  3525. request.onsuccess = function (event) {
  3526. /* result 返回的是 {key: string, value: any} */
  3527. /* 键值对存储 */
  3528. resolve({
  3529. success: true,
  3530. code: that.#statusCode.operationSuccess.code,
  3531. msg: that.#statusCode.operationSuccess.msg,
  3532. event: event,
  3533. });
  3534. };
  3535. request.onerror = function (event) {
  3536. resolve({
  3537. success: false,
  3538. code: that.#statusCode.getFailed.code,
  3539. msg: that.#statusCode.getFailed.msg,
  3540. event: event,
  3541. });
  3542. };
  3543. }
  3544. }, dbName);
  3545. });
  3546. }
  3547. /**
  3548. * 根据key获取值
  3549. * @param key 数据key
  3550. */
  3551. async get(key) {
  3552. let that = this;
  3553. return new Promise((resolve) => {
  3554. let dbName = this.#dbName;
  3555. this.open(function (idbStore) {
  3556. /* 判断返回的数据中是否有error字段 */
  3557. if (idbStore == null) {
  3558. resolve({
  3559. success: false,
  3560. code: that.#statusCode.getFailed.code,
  3561. msg: that.#statusCode.getFailed.msg,
  3562. data: undefined,
  3563. });
  3564. }
  3565. else {
  3566. let request = idbStore.get(key);
  3567. request.onsuccess = function (event) {
  3568. let target = event.target;
  3569. let result = target.result;
  3570. /* result 返回的是 {key: string, value: any} */
  3571. /* 键值对存储 */
  3572. let data = result ? result.value : undefined;
  3573. if (data == null) {
  3574. resolve({
  3575. success: true,
  3576. code: that.#statusCode.empty.code,
  3577. msg: that.#statusCode.empty.msg,
  3578. data: data,
  3579. event: event,
  3580. result: result,
  3581. });
  3582. }
  3583. else {
  3584. resolve({
  3585. success: true,
  3586. code: that.#statusCode.operationSuccess.code,
  3587. msg: that.#statusCode.operationSuccess.msg,
  3588. data: data,
  3589. event: event,
  3590. result: result,
  3591. });
  3592. }
  3593. };
  3594. request.onerror = function (event) {
  3595. resolve({
  3596. success: false,
  3597. code: that.#statusCode.getFailed.code,
  3598. msg: that.#statusCode.getFailed.msg,
  3599. data: undefined,
  3600. event: event,
  3601. });
  3602. };
  3603. }
  3604. }, dbName);
  3605. });
  3606. }
  3607. /**
  3608. * 正则获取数据
  3609. * @param key 数据key,可以是正则
  3610. */
  3611. async regexpGet(key) {
  3612. let list = [];
  3613. let that = this;
  3614. return new Promise((resolve) => {
  3615. /* 正则查询 */
  3616. let dbName = that.#dbName;
  3617. this.open(function (idbStore) {
  3618. /* 判断返回的数据中是否有error字段 */
  3619. if (idbStore == null) {
  3620. resolve({
  3621. success: false,
  3622. code: that.#statusCode.regexpGetFailed.code,
  3623. msg: that.#statusCode.regexpGetFailed.msg,
  3624. data: [],
  3625. });
  3626. }
  3627. else {
  3628. let request = idbStore.getAll();
  3629. request.onsuccess = function (event) {
  3630. let target = event.target;
  3631. let result = target.result;
  3632. if (result.length !== 0) {
  3633. result.forEach((dataItem, index) => {
  3634. // 当前项的key
  3635. let __key = dataItem["key"];
  3636. // 当前项的value
  3637. let __value = dataItem["value"];
  3638. if (__key.match(key)) {
  3639. list = list.concat(__value);
  3640. }
  3641. });
  3642. }
  3643. resolve({
  3644. success: true,
  3645. code: that.#statusCode.operationSuccess.code,
  3646. msg: that.#statusCode.operationSuccess.msg,
  3647. data: list,
  3648. event: event,
  3649. });
  3650. };
  3651. request.onerror = function (event) {
  3652. resolve({
  3653. success: false,
  3654. code: that.#statusCode.getFailed.code,
  3655. msg: that.#statusCode.getFailed.msg,
  3656. data: [],
  3657. event: event,
  3658. });
  3659. };
  3660. }
  3661. }, dbName);
  3662. });
  3663. }
  3664. /**
  3665. * 删除数据
  3666. * @param key 数据key
  3667. */
  3668. async delete(key) {
  3669. let that = this;
  3670. return new Promise((resolve) => {
  3671. /* 根据key删除某条数据 */
  3672. let dbName = that.#dbName;
  3673. this.open(function (idbStore) {
  3674. if (idbStore == null) {
  3675. resolve({
  3676. success: false,
  3677. code: that.#statusCode.deleteFailed.code,
  3678. msg: that.#statusCode.deleteFailed.msg,
  3679. });
  3680. }
  3681. else {
  3682. // 删除键
  3683. let request = idbStore.delete(key);
  3684. request.onsuccess = function (event) {
  3685. resolve({
  3686. success: true,
  3687. code: that.#statusCode.operationSuccess.code,
  3688. msg: that.#statusCode.operationSuccess.msg,
  3689. event: event,
  3690. });
  3691. };
  3692. request.onerror = function (event) {
  3693. resolve({
  3694. success: false,
  3695. code: that.#statusCode.deleteFailed.code,
  3696. msg: that.#statusCode.deleteFailed.msg,
  3697. event: event,
  3698. });
  3699. };
  3700. }
  3701. }, dbName);
  3702. });
  3703. }
  3704. /**
  3705. * 删除所有数据
  3706. */
  3707. async deleteAll() {
  3708. let that = this;
  3709. return new Promise((resolve) => {
  3710. /* 清空数据库 */
  3711. let dbName = that.#dbName;
  3712. this.open(function (idbStore) {
  3713. if (idbStore == null) {
  3714. resolve({
  3715. success: false,
  3716. code: that.#statusCode.deleteAllFailed.code,
  3717. msg: that.#statusCode.deleteAllFailed.msg,
  3718. });
  3719. }
  3720. else {
  3721. // 清空
  3722. let operateResult = idbStore.clear();
  3723. operateResult.onsuccess = function (event) {
  3724. resolve({
  3725. success: true,
  3726. code: that.#statusCode.operationSuccess.code,
  3727. msg: that.#statusCode.operationSuccess.msg,
  3728. event: event,
  3729. });
  3730. };
  3731. operateResult.onerror = function (event) {
  3732. resolve({
  3733. success: false,
  3734. code: that.#statusCode.deleteAllFailed.code,
  3735. msg: that.#statusCode.deleteAllFailed.msg,
  3736. event: event,
  3737. });
  3738. };
  3739. }
  3740. }, dbName);
  3741. });
  3742. }
  3743. }
  3744.  
  3745. class LockFunction {
  3746. #flag = false;
  3747. #delayTime = 0;
  3748. #callback;
  3749. #context;
  3750. lock;
  3751. unlock;
  3752. run;
  3753. isLock;
  3754. constructor(callback, context, delayTime) {
  3755. let that = this;
  3756. this.#callback = callback;
  3757. if (typeof context === "number") {
  3758. this.#delayTime = context;
  3759. this.#context = utils;
  3760. }
  3761. else {
  3762. this.#delayTime = delayTime;
  3763. this.#context = context;
  3764. }
  3765. /**
  3766. * 锁
  3767. */
  3768. this.lock = function () {
  3769. that.#flag = true;
  3770. };
  3771. /**
  3772. * 解锁
  3773. */
  3774. this.unlock = function () {
  3775. setTimeout(() => {
  3776. that.#flag = false;
  3777. }, that.#delayTime);
  3778. };
  3779. /**
  3780. * 判断是否被锁
  3781. */
  3782. this.isLock = function () {
  3783. return that.#flag;
  3784. };
  3785. /**
  3786. * 执行
  3787. */
  3788. this.run = async function (...args) {
  3789. if (that.isLock()) {
  3790. return;
  3791. }
  3792. that.lock();
  3793. await that.#callback.apply(that.#context, args);
  3794. that.unlock();
  3795. };
  3796. }
  3797. }
  3798.  
  3799. class Log {
  3800. /** 是否禁用输出的flag */
  3801. #disable = false;
  3802. /** 前面的TAG标志 */
  3803. tag = "Utils.Log";
  3804. /* 使用的console函数 */
  3805. #console = null;
  3806. /* 当前输出的数量 */
  3807. #logCount = 0;
  3808. /* 配置 */
  3809. #details = {
  3810. tag: true,
  3811. successColor: "#0000FF",
  3812. errorColor: "#FF0000",
  3813. infoColor: "0",
  3814. warnColor: "0",
  3815. debug: false,
  3816. autoClearConsole: false,
  3817. logMaxCount: 999,
  3818. };
  3819. /**
  3820. * 颜色配置
  3821. */
  3822. #msgColorDetails = [
  3823. "font-weight: bold; color: cornflowerblue",
  3824. "font-weight: bold; color: cornflowerblue",
  3825. "font-weight: bold; color: darkorange",
  3826. "font-weight: bold; color: cornflowerblue",
  3827. ];
  3828. /**
  3829. * @param __GM_info 油猴管理器的API GM_info,或者是一个对象,如{"script":{name:"Utils.Log"}},或者直接是一个字符串,用作tag名
  3830. * @param console 可指定console对象为unsafeWindow下的console或者是油猴window下的console
  3831. */
  3832. constructor(__GM_info, console = window.console) {
  3833. if (typeof __GM_info === "string") {
  3834. this.tag = __GM_info;
  3835. }
  3836. else if (typeof __GM_info === "object" &&
  3837. typeof __GM_info?.script?.name === "string") {
  3838. this.tag = __GM_info.script.name;
  3839. }
  3840. this.#console = console;
  3841. }
  3842. /**
  3843. * 解析Error的堆栈获取实际调用者的函数名及函数所在的位置
  3844. * @param stack
  3845. */
  3846. parseErrorStack(stack) {
  3847. let result = {
  3848. name: "",
  3849. position: "",
  3850. };
  3851. for (let stackString of stack) {
  3852. stackString = stackString.trim();
  3853. let stackFunctionNameMatch = stackString.match(/^at[\s]+(.+?)[\s]+/i);
  3854. let stackFunctionNamePositionMatch = stackString.match(/^at[\s]+.+[\s]+\((.+?)\)/i);
  3855. if (stackFunctionNameMatch == null) {
  3856. continue;
  3857. }
  3858. if (stackFunctionNamePositionMatch == null) {
  3859. continue;
  3860. }
  3861. /* 获取最后一个,因为第一个是包含了at */
  3862. let stackFunctionName = stackFunctionNameMatch[stackFunctionNameMatch.length - 1];
  3863. let stackFunctionNamePosition = stackFunctionNamePositionMatch[stackFunctionNamePositionMatch.length - 1];
  3864. if (stackFunctionName === "" ||
  3865. stackFunctionName.match(/^(Utils\.|)Log(\.|)|.<anonymous>$|^Function.each|^NodeList.forEach|^k.fn.init.each/g)) {
  3866. continue;
  3867. }
  3868. else {
  3869. result.name = stackFunctionName;
  3870. result.position = stackFunctionNamePosition;
  3871. break;
  3872. }
  3873. }
  3874. if (result.position === "") {
  3875. let lastStackString = stack[stack.length - 1].trim();
  3876. if (lastStackString.startsWith("at chrome-extension://")) {
  3877. let lastStackMatch = lastStackString.match(/^at[\s]+(.+)/);
  3878. if (lastStackMatch) {
  3879. result.position = lastStackMatch[lastStackMatch.length - 1];
  3880. }
  3881. }
  3882. }
  3883. if (result.position === "") {
  3884. result.position = stack[stack.length - 1].trim().replace(/^at[\s]*/g, "");
  3885. }
  3886. return result;
  3887. }
  3888. /**
  3889. * 检测清理控制台
  3890. */
  3891. checkClearConsole() {
  3892. this.#logCount++;
  3893. if (this.#details.autoClearConsole &&
  3894. this.#logCount > this.#details.logMaxCount) {
  3895. this.#console.clear();
  3896. this.#logCount = 0;
  3897. }
  3898. }
  3899. /**
  3900. * 输出内容
  3901. * @param msg 需要输出的内容
  3902. * @param color 颜色
  3903. * @param otherStyle 其它CSS
  3904. */
  3905. printContent(msg, color, otherStyle) {
  3906. this.checkClearConsole();
  3907. otherStyle = otherStyle || "";
  3908. let stackSplit = new Error().stack.split("\n");
  3909. stackSplit.splice(0, 2);
  3910. let { name: callerName, position: callerPosition } = this.parseErrorStack(stackSplit);
  3911. let tagName = this.tag;
  3912. let that = this;
  3913. /** tag的html输出格式 */
  3914. let tagNameHTML = `%c[${tagName}%c`;
  3915. /** 调用的函数名的html输出格式 */
  3916. let callerNameHTML = `%c${callerName}%c]%c`;
  3917. callerName.trim() !== "" && (callerNameHTML = "-" + callerNameHTML);
  3918. /**
  3919. * 输出消息到控制台
  3920. * @param message
  3921. */
  3922. function consoleMsg(message) {
  3923. if (typeof message === "string") {
  3924. that.#console.log(`${tagNameHTML}${callerNameHTML} %s`, ...that.#msgColorDetails, `color: ${color};${otherStyle}`, message);
  3925. }
  3926. else if (typeof message === "number") {
  3927. that.#console.log(`${tagNameHTML}${callerNameHTML} %d`, ...that.#msgColorDetails, `color: ${color};${otherStyle}`, message);
  3928. }
  3929. else if (typeof message === "object") {
  3930. that.#console.log(`${tagNameHTML}${callerNameHTML} %o`, ...that.#msgColorDetails, `color: ${color};${otherStyle}`, message);
  3931. }
  3932. else {
  3933. that.#console.log(message);
  3934. }
  3935. }
  3936. if (Array.isArray(msg)) {
  3937. for (let index = 0; index < msg.length; index++) {
  3938. consoleMsg(msg[index]);
  3939. }
  3940. }
  3941. else {
  3942. consoleMsg(msg);
  3943. }
  3944. if (this.#details.debug) {
  3945. /* 如果开启调试模式,输出堆栈位置 */
  3946. this.#console.log(callerPosition);
  3947. }
  3948. }
  3949. /**
  3950. * 控制台-普通输出
  3951. * @param args 需要输出的内容
  3952. * @example
  3953. * log.info("输出信息","输出信息2","输出信息3","输出")
  3954. */
  3955. info(...args) {
  3956. if (this.#disable)
  3957. return;
  3958. this.printContent(args, this.#details.infoColor);
  3959. }
  3960. /**
  3961. * 控制台-警告输出
  3962. * @param args 需要输出的内容
  3963. * @example
  3964. * log.warn("输出警告","输出警告2","输出警告3","输出警告4")
  3965. */
  3966. warn(...args) {
  3967. if (this.#disable)
  3968. return;
  3969. this.printContent(args, this.#details.warnColor, "background: #FEF6D5;padding: 4px 6px 4px 0px;");
  3970. }
  3971. /**
  3972. * 控制台-错误输出
  3973. * @param args 需要输出的内容
  3974. * @example
  3975. * log.error("输出错误","输出错误2","输出错误3","输出错误4")
  3976. */
  3977. error(...args) {
  3978. if (this.#disable)
  3979. return;
  3980. this.printContent(args, this.#details.errorColor);
  3981. }
  3982. /**
  3983. * 控制台-成功输出
  3984. * @param args 需要输出的内容
  3985. * @example
  3986. * log.success("输出成功")
  3987. */
  3988. success(...args) {
  3989. if (this.#disable)
  3990. return;
  3991. this.printContent(args, this.#details.successColor);
  3992. }
  3993. /**
  3994. * 控制台-输出表格
  3995. * @param msg 需要输出的内容
  3996. * @example
  3997. * log.table([{"名字":"example","值":"123"},{"名字":"example2","值":"345"}])
  3998. */
  3999. table(msg) {
  4000. if (this.#disable)
  4001. return;
  4002. this.checkClearConsole();
  4003. let stack = new Error().stack.split("\n");
  4004. stack.splice(0, 1);
  4005. let errorStackParse = this.parseErrorStack(stack);
  4006. /** 堆栈函数名 */
  4007. let stackFunctionName = errorStackParse.name;
  4008. /** 堆栈位置 */
  4009. let stackFunctionNamePosition = errorStackParse.position;
  4010. let callerName = stackFunctionName;
  4011. this.#console.log(`%c[${this.tag}%c-%c${callerName}%c]%c`, ...this.#msgColorDetails, `color: ${this.#details.infoColor};`);
  4012. this.#console.table(msg);
  4013. if (this.#details.debug) {
  4014. this.#console.log(stackFunctionNamePosition);
  4015. }
  4016. }
  4017. /**
  4018. * 配置Log对象的颜色
  4019. * @param paramDetails 配置信息
  4020. */
  4021. config(paramDetails) {
  4022. this.#details = Object.assign(this.#details, paramDetails);
  4023. }
  4024. /** 禁用输出 */
  4025. disable() {
  4026. this.#disable = true;
  4027. }
  4028. /** 恢复输出 */
  4029. recovery() {
  4030. this.#disable = false;
  4031. }
  4032. }
  4033.  
  4034. class Progress {
  4035. #config = {
  4036. /**
  4037. * canvas元素节点
  4038. */
  4039. canvasNode: null,
  4040. /**
  4041. * 绘制角度
  4042. */
  4043. deg: 95,
  4044. /**
  4045. * 进度
  4046. */
  4047. progress: 0,
  4048. /**
  4049. * 绘制的线宽度
  4050. */
  4051. lineWidth: 10,
  4052. /**
  4053. * 绘制的背景颜色
  4054. */
  4055. lineBgColor: "#1e637c",
  4056. /**
  4057. * 绘制的线的颜色
  4058. */
  4059. lineColor: "#25deff",
  4060. /**
  4061. * 绘制的字体颜色
  4062. */
  4063. textColor: "#000000",
  4064. /**
  4065. * 绘制的字体大小(px)
  4066. */
  4067. fontSize: 22,
  4068. /**
  4069. * 绘制的圆的半径
  4070. */
  4071. circleRadius: 50,
  4072. };
  4073. #ctx = null;
  4074. #width = null;
  4075. #height = null;
  4076. /**
  4077. *
  4078. * @param paramConfig 配置信息
  4079. */
  4080. constructor(paramConfig) {
  4081. this.#config = utils.assign(this.#config, paramConfig);
  4082. if (!(this.#config.canvasNode instanceof HTMLCanvasElement)) {
  4083. throw new Error("Utils.Progress 参数 canvasNode 必须是 HTMLCanvasElement");
  4084. }
  4085. this.init();
  4086. }
  4087. /**
  4088. * 初始化
  4089. */
  4090. init() {
  4091. /* 获取画笔 */
  4092. let ctx = this.#config.canvasNode.getContext("2d");
  4093. if (ctx == null) {
  4094. throw new Error("Utils.Progress 获取画笔失败");
  4095. }
  4096. this.#ctx = ctx;
  4097. /* 元素宽度 */
  4098. this.#width = this.#config.canvasNode.width;
  4099. /* 元素高度 */
  4100. this.#height = this.#config.canvasNode.height;
  4101. /* 清除锯齿 */
  4102. if (window.devicePixelRatio) {
  4103. this.#config.canvasNode.style.width = this.#width + "px";
  4104. this.#config.canvasNode.style.height = this.#height + "px";
  4105. this.#config.canvasNode.height = this.#height * window.devicePixelRatio;
  4106. this.#config.canvasNode.width = this.#width * window.devicePixelRatio;
  4107. this.#ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
  4108. }
  4109. /* 设置线宽 */
  4110. this.#ctx.lineWidth = this.#config.lineWidth;
  4111. }
  4112. /**
  4113. * 绘制
  4114. */
  4115. draw() {
  4116. let degActive = (this.#config.progress * 360) / 100;
  4117. /* 清除画布 */
  4118. this.#ctx.clearRect(0, 0, this.#width, this.#height);
  4119. /* 开始绘制底圆 */
  4120. this.#ctx.beginPath();
  4121. this.#ctx.arc(this.#width / 2, this.#height / 2, this.#config.circleRadius, 1, 8);
  4122. this.#ctx.strokeStyle = this.#config.lineBgColor;
  4123. this.#ctx.stroke();
  4124. /* 开始绘制动态圆 */
  4125. this.#ctx.beginPath();
  4126. this.#ctx.arc(this.#width / 2, this.#height / 2, this.#config.circleRadius, -Math.PI / 2, (degActive * Math.PI) / 180 - Math.PI / 2);
  4127. this.#ctx.strokeStyle = this.#config.lineColor;
  4128. this.#ctx.stroke();
  4129. /* 获取百分比 */
  4130. let txt = parseInt(this.#config.progress.toString()) + "%";
  4131. this.#ctx.font = this.#config.fontSize + "px SimHei";
  4132. /* 获取文本宽度 */
  4133. let w = this.#ctx.measureText(txt).width;
  4134. let h = this.#config.fontSize / 2;
  4135. this.#ctx.fillStyle = this.#config.textColor;
  4136. this.#ctx.fillText(txt, this.#width / 2 - w / 2, this.#height / 2 + h / 2);
  4137. }
  4138. }
  4139.  
  4140. const TryCatch = function (...args) {
  4141. /* 定义变量和函数 */
  4142. let callbackFunction = null;
  4143. let context = null;
  4144. let handleError = (error) => { };
  4145. let defaultDetails = {
  4146. log: true,
  4147. };
  4148. const TryCatchCore = {
  4149. /**
  4150. *
  4151. * @param paramDetails 配置
  4152. * @returns
  4153. */
  4154. config(paramDetails) {
  4155. defaultDetails = utils.assign(defaultDetails, paramDetails);
  4156. return TryCatchCore;
  4157. },
  4158. /**
  4159. * 处理错误
  4160. * @param handler
  4161. */
  4162. error(handler) {
  4163. // @ts-ignore
  4164. handleError = handler;
  4165. return TryCatchCore;
  4166. },
  4167. /**
  4168. * 执行传入的函数并捕获其可能抛出的错误,并通过传入的错误处理函数进行处理。
  4169. * @param callback 待执行函数,可以是 function 或者 string 类型。如果是 string 类型,则会被当做代码进行执行。
  4170. * @param __context__ 待执行函数的作用域,用于apply指定
  4171. * @returns 如果函数有返回值,则返回该返回值;否则返回 tryCatchObj 函数以支持链式调用。
  4172. * @throws {Error} 如果传入参数不符合要求,则会抛出相应类型的错误。
  4173. */
  4174. run(callback, __context__) {
  4175. callbackFunction = callback;
  4176. context = __context__ || this;
  4177. let result = executeTryCatch(callbackFunction, handleError, context);
  4178. // @ts-ignore
  4179. return result !== undefined ? result : TryCatchCore;
  4180. },
  4181. };
  4182. /**
  4183. * 执行传入的函数并捕获其可能抛出的错误,并通过传入的错误处理函数进行处理。
  4184. * @param callback - 待执行函数,可以是 function 或者 string 类型。如果是 string 类型,则会被当做代码进行执行。
  4185. * @param handleErrorFunc - 错误处理函数,可以是 function 或者 string 类型。如果是 string 类型,则会被当做代码进行执行。
  4186. * @param funcThis - 待执行函数的作用域,用于apply指定
  4187. * @returns 如果函数有返回值,则返回该返回值;否则返回 undefined。
  4188. */
  4189. function executeTryCatch(callback, handleErrorFunc, funcThis) {
  4190. let result = undefined;
  4191. try {
  4192. if (typeof callback === "string") {
  4193. (function () {
  4194. eval(callback);
  4195. }).apply(funcThis, args);
  4196. }
  4197. else {
  4198. result = callback.apply(funcThis, args);
  4199. }
  4200. }
  4201. catch (error) {
  4202. if (defaultDetails.log) {
  4203. callback = callback;
  4204. console.log(`%c ${callback?.name ? callback?.name : callback + "出现错误"} `, "color: #f20000");
  4205. console.log(`%c 错误原因:${error}`, "color: #f20000");
  4206. console.trace(callback);
  4207. }
  4208. if (handleErrorFunc) {
  4209. if (typeof handleErrorFunc === "string") {
  4210. result = function () {
  4211. return eval(handleErrorFunc);
  4212. // @ts-ignore
  4213. }.apply(funcThis, [...args, error]);
  4214. }
  4215. else {
  4216. result = handleErrorFunc.apply(funcThis, [...args, error]);
  4217. }
  4218. }
  4219. }
  4220. return result;
  4221. }
  4222. return TryCatchCore;
  4223. };
  4224.  
  4225. class UtilsDictionary {
  4226. items = {};
  4227. constructor(key, value) {
  4228. if (key != null) {
  4229. this.set(key, value);
  4230. }
  4231. }
  4232. /**
  4233. * 检查是否有某一个键
  4234. * @param key 键
  4235. */
  4236. has(key) {
  4237. return Reflect.has(this.items, key);
  4238. }
  4239. /**
  4240. * 检查已有的键中是否以xx开头
  4241. * @param key 需要匹配的键
  4242. */
  4243. startsWith(key) {
  4244. let allKeys = this.keys();
  4245. for (const keyName of allKeys) {
  4246. if (String(keyName).startsWith(String(key))) {
  4247. return true;
  4248. }
  4249. }
  4250. return false;
  4251. }
  4252. /**
  4253. * 获取以xx开头的键的值
  4254. * @param key 需要匹配的键
  4255. */
  4256. getStartsWith(key) {
  4257. let allKeys = this.keys();
  4258. let result = undefined;
  4259. for (const keyName of allKeys) {
  4260. if (String(keyName).startsWith(String(key))) {
  4261. result = this.get(keyName);
  4262. break;
  4263. }
  4264. }
  4265. return result;
  4266. }
  4267. /**
  4268. * 为字典添加某一个值
  4269. * @param key 键
  4270. * @param val 值,默认为""
  4271. */
  4272. set(key, val) {
  4273. if (key === undefined) {
  4274. throw new Error("Utils.Dictionary().set 参数 key 不能为空");
  4275. }
  4276. Reflect.set(this.items, key, val);
  4277. }
  4278. /**
  4279. * 删除某一个键
  4280. * @param key 键
  4281. */
  4282. delete(key) {
  4283. if (this.has(key)) {
  4284. return Reflect.deleteProperty(this.items, key);
  4285. }
  4286. return false;
  4287. }
  4288. /**
  4289. * 获取某个键的值
  4290. * https://github.com/microsoft/TypeScript/issues/9619
  4291. * 微软到现在都没有修复has和get的联动
  4292. * @param key 键
  4293. */
  4294. get(key) {
  4295. return Reflect.get(this.items, key);
  4296. }
  4297. /**
  4298. * 返回字典中的所有值
  4299. */
  4300. values() {
  4301. let resultList = [];
  4302. for (let prop in this.getItems()) {
  4303. if (this.has(prop)) {
  4304. resultList.push(this.get(prop));
  4305. }
  4306. }
  4307. return resultList;
  4308. }
  4309. /**
  4310. * 清空字典
  4311. */
  4312. clear() {
  4313. this.items = null;
  4314. this.items = {};
  4315. }
  4316. /**
  4317. * 获取字典的长度
  4318. */
  4319. size() {
  4320. return Object.keys(this.getItems()).length;
  4321. }
  4322. /**
  4323. * 获取字典所有的键
  4324. */
  4325. keys() {
  4326. return Reflect.ownKeys(this.items);
  4327. }
  4328. /**
  4329. * 返回字典本身
  4330. */
  4331. getItems() {
  4332. // @ts-ignore
  4333. return this.items;
  4334. }
  4335. /**
  4336. * 合并另一个字典
  4337. * @param data 需要合并的字典
  4338. */
  4339. concat(data) {
  4340. this.items = utils.assign(this.items, data.getItems());
  4341. }
  4342. forEach(callbackfn) {
  4343. for (const key in this.getItems()) {
  4344. callbackfn(this.get(key), key, this.getItems());
  4345. }
  4346. }
  4347. /**
  4348. * 获取字典的长度,同this.size
  4349. */
  4350. get length() {
  4351. return this.size();
  4352. }
  4353. /**
  4354. * 迭代器
  4355. */
  4356. get entries() {
  4357. let that = this;
  4358. return function* () {
  4359. let itemKeys = Object.keys(that.getItems());
  4360. for (const keyName of itemKeys) {
  4361. yield [keyName, that.get(keyName)];
  4362. }
  4363. };
  4364. }
  4365. /**
  4366. * 是否可遍历
  4367. */
  4368. get [Symbol.iterator]() {
  4369. let that = this;
  4370. return function () {
  4371. return that.entries();
  4372. };
  4373. }
  4374. }
  4375.  
  4376. class WindowApi {
  4377. /** 默认的配置 */
  4378. defaultApi = {
  4379. document: document,
  4380. window: window,
  4381. globalThis: globalThis,
  4382. self: self,
  4383. top: top,
  4384. };
  4385. /** 使用的配置 */
  4386. api;
  4387. constructor(option) {
  4388. if (option) {
  4389. if (option.globalThis == null) {
  4390. option.globalThis = option.window;
  4391. }
  4392. if (option.self == null) {
  4393. option.self = option.window;
  4394. }
  4395. }
  4396. if (!option) {
  4397. option = Object.assign({}, this.defaultApi);
  4398. }
  4399. // @ts-ignore
  4400. this.api = Object.assign({}, option);
  4401. }
  4402. get document() {
  4403. return this.api.document;
  4404. }
  4405. get window() {
  4406. return this.api.window;
  4407. }
  4408. get globalThis() {
  4409. return this.api.globalThis;
  4410. }
  4411. get self() {
  4412. return this.api.self;
  4413. }
  4414. get top() {
  4415. return this.api.top;
  4416. }
  4417. }
  4418.  
  4419. const VueUtils = {
  4420. /** 标签 */
  4421. ReactiveFlags: {
  4422. IS_REACTIVE: Symbol("isReactive"),
  4423. },
  4424. /**
  4425. * 判断是否是对象
  4426. * @param value
  4427. */
  4428. isObject(value) {
  4429. return typeof value === "object" && value !== null;
  4430. },
  4431. /**
  4432. * 判断是否是函数
  4433. * @param val
  4434. */
  4435. isFunction(val) {
  4436. return typeof val === "function";
  4437. },
  4438. /**
  4439. * 处理对象再次代理,可以直接返回
  4440. * @param value
  4441. */
  4442. isReactive(value) {
  4443. return !!(value && value[VueUtils.ReactiveFlags.IS_REACTIVE]);
  4444. },
  4445. /**
  4446. * 判断是否是数组
  4447. * @param value
  4448. */
  4449. isArray(value) {
  4450. return Array.isArray(value);
  4451. },
  4452. };
  4453. class ReactiveEffect {
  4454. deps = [];
  4455. active = true;
  4456. fn;
  4457. // @ts-ignore
  4458. scheduler;
  4459. constructor(fn, scheduler) {
  4460. this.fn = fn;
  4461. this.scheduler = scheduler;
  4462. }
  4463. run(cb) {
  4464. if (!this.active) {
  4465. this.fn();
  4466. }
  4467. try {
  4468. if (typeof cb === "function") {
  4469. cb(this);
  4470. }
  4471. return this.fn();
  4472. }
  4473. finally {
  4474. if (typeof cb === "function") {
  4475. cb(undefined);
  4476. }
  4477. }
  4478. }
  4479. }
  4480. class RefImpl {
  4481. _value;
  4482. _isRef = true;
  4483. _rawValue;
  4484. _vue;
  4485. constructor(vueIns, rawValue) {
  4486. this._vue = vueIns;
  4487. this._rawValue = rawValue;
  4488. this._value = this._vue.toReactive(rawValue);
  4489. }
  4490. get value() {
  4491. return this._value;
  4492. }
  4493. set value(newValue) {
  4494. if (newValue !== this._rawValue) {
  4495. this._value = this._vue.toReactive(newValue);
  4496. this._rawValue = newValue;
  4497. }
  4498. }
  4499. }
  4500. class ObjectRefImpl {
  4501. object;
  4502. key;
  4503. constructor(object, key) {
  4504. this.object = object;
  4505. this.key = key;
  4506. }
  4507. get value() {
  4508. return this.object[this.key];
  4509. }
  4510. set value(newValue) {
  4511. this.object[this.key] = newValue;
  4512. }
  4513. }
  4514. class Vue {
  4515. reactMap = new WeakMap();
  4516. targetMap = new WeakMap();
  4517. activeEffect = undefined;
  4518. constructor() {
  4519. // 将数据转化成响应式的数据,只能做对象的代理
  4520. }
  4521. /**
  4522. * 生成一个被代理的对象
  4523. * @param target 需要代理的对象
  4524. */
  4525. reactive(target) {
  4526. const that = this;
  4527. if (!(typeof target === "object" && target !== null)) {
  4528. // @ts-ignore
  4529. return;
  4530. }
  4531. if (VueUtils.isReactive(target)) {
  4532. return target;
  4533. }
  4534. let exisProxy = this.reactMap.get(target);
  4535. if (exisProxy) {
  4536. return exisProxy;
  4537. }
  4538. const proxy = new Proxy(target, {
  4539. get(target, key, receiver) {
  4540. if (key === VueUtils.ReactiveFlags.IS_REACTIVE) {
  4541. return true;
  4542. }
  4543. that.track(target, "get", key);
  4544. return Reflect.get(target, key, receiver);
  4545. },
  4546. set(target, key, value, receiver) {
  4547. let oldValue = target[key];
  4548. let result = Reflect.set(target, key, value, receiver);
  4549. if (oldValue !== value) {
  4550. that.trigger(target, "set", key, oldValue, value);
  4551. }
  4552. return result;
  4553. },
  4554. });
  4555. that.reactMap.set(target, proxy);
  4556. return proxy;
  4557. }
  4558. /**
  4559. * 观察被reactive的对象值改变
  4560. * @param source 被观察的对象,这里采用函数返回对象
  4561. * @param changeCallBack 值改变的回调
  4562. */
  4563. watch(source, changeCallBack) {
  4564. let getter;
  4565. if (VueUtils.isReactive(source)) {
  4566. getter = () => this.traversal(source);
  4567. }
  4568. else if (VueUtils.isFunction(source)) {
  4569. getter = source;
  4570. }
  4571. else {
  4572. return;
  4573. }
  4574. let oldValue;
  4575. const job = () => {
  4576. const newValue = effect.run((activeEffect) => {
  4577. this.activeEffect = activeEffect;
  4578. });
  4579. changeCallBack(newValue, oldValue);
  4580. oldValue = newValue;
  4581. };
  4582. const effect = new ReactiveEffect(getter, job);
  4583. oldValue = effect.run((activeEffect) => {
  4584. this.activeEffect = activeEffect;
  4585. });
  4586. }
  4587. toReactive(value) {
  4588. return VueUtils.isObject(value) ? this.reactive(value) : value;
  4589. }
  4590. ref(value) {
  4591. return new RefImpl(this, value);
  4592. }
  4593. toRef(object, key) {
  4594. return new ObjectRefImpl(object, key);
  4595. }
  4596. toRefs(object) {
  4597. const result = VueUtils.isArray(object) ? new Array(object.length) : {};
  4598. for (let key in object) {
  4599. // @ts-ignore
  4600. result[key] = this.toRef(object, key);
  4601. }
  4602. return result;
  4603. }
  4604. trigger(target, type, key, oldValue, value) {
  4605. const depsMap = this.targetMap.get(target);
  4606. if (!depsMap)
  4607. return;
  4608. const effects = depsMap.get(key);
  4609. this.triggerEffect(effects, "effects");
  4610. }
  4611. triggerEffect(effects, name) {
  4612. effects &&
  4613. effects.forEach((effect) => {
  4614. if (effect.scheduler) {
  4615. effect.scheduler();
  4616. }
  4617. else {
  4618. effect.run();
  4619. }
  4620. });
  4621. }
  4622. track(target, type, key) {
  4623. if (!this.activeEffect)
  4624. return;
  4625. let depsMap = this.targetMap.get(target);
  4626. if (!depsMap) {
  4627. this.targetMap.set(target, (depsMap = new Map()));
  4628. }
  4629. let dep = depsMap.get(key);
  4630. if (!dep) {
  4631. depsMap.set(key, (dep = new Set()));
  4632. }
  4633. this.trackEffect(dep);
  4634. }
  4635. trackEffect(dep) {
  4636. if (this.activeEffect) {
  4637. let shouldTrack = !dep.has(this.activeEffect);
  4638. if (shouldTrack) {
  4639. dep.add(this.activeEffect);
  4640. this.activeEffect.deps.push(dep);
  4641. }
  4642. }
  4643. }
  4644. traversal(value, set = new Set()) {
  4645. if (!VueUtils.isObject(value))
  4646. return value;
  4647. if (set.has(value)) {
  4648. return value;
  4649. }
  4650. set.add(value);
  4651. for (let key in value) {
  4652. this.traversal(value[key], set);
  4653. }
  4654. return value;
  4655. }
  4656. }
  4657.  
  4658. // ==UserScript==
  4659. // @name ModuleRaid.js
  4660. // @namespace http://tampermonkey.net/
  4661. // @version 6.2.0
  4662. // @description 检索调用webpackJsonp模块,可指定检索的window
  4663. // @author empyrealtear
  4664. // @license MIT
  4665. // @original-script https://github.com/pixeldesu/moduleRaid
  4666. // ==/UserScript==
  4667.  
  4668.  
  4669. /**
  4670. * Main moduleRaid class
  4671. * @link https://scriptcat.org/zh-CN/script-show-page/2628
  4672. */
  4673. class ModuleRaid {
  4674. /**
  4675. * moduleRaid constructor
  4676. *
  4677. * @example
  4678. * Constructing an instance without any arguments:
  4679. * ```ts
  4680. * const mR = new ModuleRaid()
  4681. * ```
  4682. *
  4683. * Constructing an instance with the optional `opts` object:
  4684. * ```ts
  4685. * const mR = new ModuleRaid({ entrypoint: 'webpackChunk_custom_name' })
  4686. * ```
  4687. *
  4688. * @param opts a object containing options to initialize moduleRaid with
  4689. * - **opts:**
  4690. * - _target_: the window object being searched for
  4691. * - _entrypoint_: the Webpack entrypoint present on the global window object
  4692. * - _debug_: whether debug mode is enabled or not
  4693. * - _strict_: whether strict mode is enabled or not
  4694. */
  4695. constructor(opts) {
  4696. /**
  4697. * A random generated module ID we use for injecting into Webpack
  4698. */
  4699. this.moduleID = Math.random().toString(36).substring(7);
  4700. /**
  4701. * An array containing different argument injection methods for
  4702. * Webpack (before version 4), and subsequently pulling out methods and modules
  4703. * @internal
  4704. */
  4705. this.functionArguments = [
  4706. [
  4707. [0],
  4708. [
  4709. (_e, _t, i) => {
  4710. this.modules = i.c;
  4711. this.constructors = i.m;
  4712. this.get = i;
  4713. },
  4714. ],
  4715. ],
  4716. [
  4717. [1e3],
  4718. {
  4719. [this.moduleID]: (_e, _t, i) => {
  4720. this.modules = i.c;
  4721. this.constructors = i.m;
  4722. this.get = i;
  4723. },
  4724. },
  4725. [[this.moduleID]],
  4726. ],
  4727. ];
  4728. /**
  4729. * An array containing different argument injection methods for
  4730. * Webpack (after version 4), and subsequently pulling out methods and modules
  4731. * @internal
  4732. */
  4733. this.arrayArguments = [
  4734. [
  4735. [this.moduleID],
  4736. {},
  4737. (e) => {
  4738. const mCac = e.m;
  4739. Object.keys(mCac).forEach((mod) => {
  4740. try {
  4741. this.modules[mod] = e(mod);
  4742. }
  4743. catch (err) {
  4744. this.log(`[arrayArguments/1] Failed to require(${mod}) with error:\n${err}\n${err.stack}`);
  4745. }
  4746. });
  4747. this.get = e;
  4748. },
  4749. ],
  4750. this.functionArguments[1],
  4751. ];
  4752. /**
  4753. * Storage for the modules we extracted from Webpack
  4754. */
  4755. this.modules = {};
  4756. /**
  4757. * Storage for the constructors we extracted from Webpack
  4758. */
  4759. this.constructors = [];
  4760. let options = {
  4761. target: window,
  4762. entrypoint: 'webpackJsonp',
  4763. debug: false,
  4764. strict: false,
  4765. };
  4766. if (typeof opts === 'object') {
  4767. options = Object.assign(Object.assign({}, options), opts);
  4768. }
  4769. this.target = options.target;
  4770. this.entrypoint = options.entrypoint;
  4771. this.debug = options.debug;
  4772. this.strict = options.strict;
  4773. this.detectEntrypoint();
  4774. this.fillModules();
  4775. this.replaceGet();
  4776. this.setupPushEvent();
  4777. }
  4778. /**
  4779. * Debug logging method, outputs to the console when {@link ModuleRaid.debug} is true
  4780. *
  4781. * @param {*} message The message to be logged
  4782. * @internal
  4783. */
  4784. log(message) {
  4785. if (this.debug) {
  4786. console.warn(`[moduleRaid] ${message}`);
  4787. }
  4788. }
  4789. /**
  4790. * Method to set an alternative getter if we weren't able to extract __webpack_require__
  4791. * from Webpack
  4792. * @internal
  4793. */
  4794. replaceGet() {
  4795. if (this.get === null) {
  4796. this.get = (key) => this.modules[key];
  4797. }
  4798. }
  4799. /**
  4800. * Method that will try to inject a module into Webpack or get modules
  4801. * depending on it's success it might be more or less brute about it
  4802. * @internal
  4803. */
  4804. fillModules() {
  4805. if (typeof this.target[this.entrypoint] === 'function') {
  4806. this.functionArguments.forEach((argument, index) => {
  4807. try {
  4808. if (this.modules && Object.keys(this.modules).length > 0)
  4809. return;
  4810. this.target[this.entrypoint](...argument);
  4811. }
  4812. catch (err) {
  4813. this.log(`moduleRaid.functionArguments[${index}] failed:\n${err}\n${err.stack}`);
  4814. }
  4815. });
  4816. }
  4817. else {
  4818. this.arrayArguments.forEach((argument, index) => {
  4819. try {
  4820. if (this.modules && Object.keys(this.modules).length > 0)
  4821. return;
  4822. this.target[this.entrypoint].push(argument);
  4823. }
  4824. catch (err) {
  4825. this.log(`Pushing moduleRaid.arrayArguments[${index}] into ${this.entrypoint} failed:\n${err}\n${err.stack}`);
  4826. }
  4827. });
  4828. }
  4829. if (this.modules && Object.keys(this.modules).length == 0) {
  4830. let moduleEnd = false;
  4831. let moduleIterator = 0;
  4832. if (typeof this.target[this.entrypoint] != 'function' || !this.target[this.entrypoint]([], [], [moduleIterator])) {
  4833. throw Error('Unknown Webpack structure');
  4834. }
  4835. while (!moduleEnd) {
  4836. try {
  4837. this.modules[moduleIterator] = this.target[this.entrypoint]([], [], [moduleIterator]);
  4838. moduleIterator++;
  4839. }
  4840. catch (err) {
  4841. moduleEnd = true;
  4842. }
  4843. }
  4844. }
  4845. }
  4846. /**
  4847. * Method to hook into `window[this.entrypoint].push` adding a listener for new
  4848. * chunks being pushed into Webpack
  4849. *
  4850. * @example
  4851. * You can listen for newly pushed packages using the `moduleraid:webpack-push` event
  4852. * on `document`
  4853. *
  4854. * ```ts
  4855. * document.addEventListener('moduleraid:webpack-push', (e) => {
  4856. * // e.detail contains the arguments push() was called with
  4857. * console.log(e.detail)
  4858. * })
  4859. * ```
  4860. * @internal
  4861. */
  4862. setupPushEvent() {
  4863. const originalPush = this.target[this.entrypoint].push;
  4864. this.target[this.entrypoint].push = (...args) => {
  4865. const result = Reflect.apply(originalPush, this.target[this.entrypoint], args);
  4866. document.dispatchEvent(new CustomEvent('moduleraid:webpack-push', { detail: args }));
  4867. return result;
  4868. };
  4869. }
  4870. /**
  4871. * Method to try autodetecting a Webpack JSONP entrypoint based on common naming
  4872. *
  4873. * If the default entrypoint, or the entrypoint that's passed to the moduleRaid constructor
  4874. * already matches, the method exits early
  4875. *
  4876. * If `options.strict` has been set in the constructor and the initial entrypoint cannot
  4877. * be found, this method will error, demanding a strictly set entrypoint
  4878. * @internal
  4879. */
  4880. detectEntrypoint() {
  4881. if (this.target[this.entrypoint] != undefined) {
  4882. return;
  4883. }
  4884. if (this.strict) {
  4885. throw Error(`Strict mode is enabled and entrypoint at window.${this.entrypoint} couldn't be found. Please specify the correct one!`);
  4886. }
  4887. let windowObjects = Object.keys(this.target);
  4888. windowObjects = windowObjects
  4889. .filter((object) => object.toLowerCase().includes('chunk') || object.toLowerCase().includes('webpack'))
  4890. .filter((object) => typeof this.target[object] === 'function' || Array.isArray(this.target[object]));
  4891. if (windowObjects.length > 1) {
  4892. throw Error(`Multiple possible endpoints have been detected, please create a new moduleRaid instance with a specific one:\n${windowObjects.join(', ')}`);
  4893. }
  4894. if (windowObjects.length === 0) {
  4895. throw Error('No Webpack JSONP entrypoints could be detected');
  4896. }
  4897. this.log(`Entrypoint has been detected at window.${windowObjects[0]} and set for injection`);
  4898. this.entrypoint = windowObjects[0];
  4899. }
  4900. /**
  4901. * Recursive object-search function for modules
  4902. *
  4903. * @param object the object to search through
  4904. * @param query the query the object keys/values are searched for
  4905. * @returns boolean state of `object` containing `query` somewhere in it
  4906. * @internal
  4907. */
  4908. searchObject(object, query) {
  4909. for (const key in object) {
  4910. const value = object[key];
  4911. const lowerCaseQuery = query.toLowerCase();
  4912. if (typeof value != 'object') {
  4913. const lowerCaseKey = key.toString().toLowerCase();
  4914. if (lowerCaseKey.includes(lowerCaseQuery))
  4915. return true;
  4916. if (typeof value != 'object') {
  4917. const lowerCaseValue = value.toString().toLowerCase();
  4918. if (lowerCaseValue.includes(lowerCaseQuery))
  4919. return true;
  4920. }
  4921. else {
  4922. if (this.searchObject(value, query))
  4923. return true;
  4924. }
  4925. }
  4926. }
  4927. return false;
  4928. }
  4929. /**
  4930. * Method to search through the module object, searching for the fitting content
  4931. * if a string is supplied
  4932. *
  4933. * If query is supplied as a function, everything that returns true when passed
  4934. * to the query function will be returned
  4935. *
  4936. * @example
  4937. * With a string as query argument:
  4938. * ```ts
  4939. * const results = mR.findModule('feature')
  4940. * // => Array of module results
  4941. * ```
  4942. *
  4943. * With a function as query argument:
  4944. * ```ts
  4945. * const results = mR.findModule((module) => { typeof module === 'function' })
  4946. * // => Array of module results
  4947. * ```
  4948. *
  4949. * @param query query to search the module list for
  4950. * @return a list of modules fitting the query
  4951. */
  4952. findModule(query) {
  4953. const results = [];
  4954. const modules = Object.keys(this.modules);
  4955. if (modules.length === 0) {
  4956. throw new Error('There are no modules to search through!');
  4957. }
  4958. modules.forEach((key) => {
  4959. const module = this.modules[key.toString()];
  4960. if (module === undefined)
  4961. return;
  4962. try {
  4963. if (typeof query === 'string') {
  4964. query = query.toLowerCase();
  4965. switch (typeof module) {
  4966. case 'string':
  4967. if (module.toLowerCase().includes(query))
  4968. results.push(module);
  4969. break;
  4970. case 'function':
  4971. if (module.toString().toLowerCase().includes(query))
  4972. results.push(module);
  4973. break;
  4974. case 'object':
  4975. if (this.searchObject(module, query))
  4976. results.push(module);
  4977. break;
  4978. }
  4979. }
  4980. else if (typeof query === 'function') {
  4981. if (query(module))
  4982. results.push(module);
  4983. }
  4984. else {
  4985. throw new TypeError(`findModule can only find via string and function, ${typeof query} was passed`);
  4986. }
  4987. }
  4988. catch (err) {
  4989. this.log(`There was an error while searching through module '${key}':\n${err}\n${err.stack}`);
  4990. }
  4991. });
  4992. return results;
  4993. }
  4994. /**
  4995. * Method to search through the constructor array, searching for the fitting content
  4996. * if a string is supplied
  4997. *
  4998. * If query is supplied as a function, everything that returns true when passed
  4999. * to the query function will be returned
  5000. *
  5001. * @example
  5002. * With a string as query argument:
  5003. * ```ts
  5004. * const results = mR.findConstructor('feature')
  5005. * // => Array of constructor/module tuples
  5006. * ```
  5007. *
  5008. * With a function as query argument:
  5009. * ```ts
  5010. * const results = mR.findConstructor((constructor) => { constructor.prototype.value !== undefined })
  5011. * // => Array of constructor/module tuples
  5012. * ```
  5013. *
  5014. * Accessing the resulting data:
  5015. * ```ts
  5016. * // With array destructuring (ES6)
  5017. * const [constructor, module] = results[0]
  5018. *
  5019. * // ...or...
  5020. *
  5021. * // regular access
  5022. * const constructor = results[0][0]
  5023. * const module = results[0][1]
  5024. * ```
  5025. *
  5026. * @param query query to search the constructor list for
  5027. * @returns a list of constructor/module tuples fitting the query
  5028. */
  5029. findConstructor(query) {
  5030. const results = [];
  5031. const constructors = Object.keys(this.constructors);
  5032. if (constructors.length === 0) {
  5033. throw new Error('There are no constructors to search through!');
  5034. }
  5035. constructors.forEach((key) => {
  5036. const constructor = this.constructors[key];
  5037. try {
  5038. if (typeof query === 'string') {
  5039. query = query.toLowerCase();
  5040. if (constructor.toString().toLowerCase().includes(query))
  5041. results.push([this.constructors[key], this.modules[key]]);
  5042. }
  5043. else if (typeof query === 'function') {
  5044. if (query(constructor))
  5045. results.push([this.constructors[key], this.modules[key]]);
  5046. }
  5047. }
  5048. catch (err) {
  5049. this.log(`There was an error while searching through constructor '${key}':\n${err}\n${err.stack}`);
  5050. }
  5051. });
  5052. return results;
  5053. }
  5054. }
  5055.  
  5056. class Utils {
  5057. windowApi;
  5058. constructor(option) {
  5059. this.windowApi = new WindowApi(option);
  5060. }
  5061. /** 版本号 */
  5062. version = "2025.3.25";
  5063. addStyle(cssText) {
  5064. if (typeof cssText !== "string") {
  5065. throw new Error("Utils.addStyle 参数cssText 必须为String类型");
  5066. }
  5067. let cssNode = this.windowApi.document.createElement("style");
  5068. cssNode.setAttribute("type", "text/css");
  5069. cssNode.innerHTML = cssText;
  5070. if (this.windowApi.document.head) {
  5071. /* 插入head最后 */
  5072. this.windowApi.document.head.appendChild(cssNode);
  5073. }
  5074. else if (this.windowApi.document.body) {
  5075. /* 插入body后 */
  5076. this.windowApi.document.body.appendChild(cssNode);
  5077. }
  5078. else if (this.windowApi.document.documentElement.childNodes.length === 0) {
  5079. /* 插入#html第一个元素后 */
  5080. this.windowApi.document.documentElement.appendChild(cssNode);
  5081. }
  5082. else {
  5083. /* 插入head前面 */
  5084. this.windowApi.document.documentElement.insertBefore(cssNode, this.windowApi.document.documentElement.childNodes[0]);
  5085. }
  5086. return cssNode;
  5087. }
  5088. assign(target = {}, source = {}, isAdd = false) {
  5089. let UtilsContext = this;
  5090. if (Array.isArray(source)) {
  5091. let canTraverse = source.filter((item) => {
  5092. return typeof item === "object";
  5093. });
  5094. if (!canTraverse.length) {
  5095. return source;
  5096. }
  5097. }
  5098. if (source == null) {
  5099. return target;
  5100. }
  5101. if (target == null) {
  5102. target = {};
  5103. }
  5104. if (isAdd) {
  5105. for (const sourceKeyName in source) {
  5106. const targetKeyName = sourceKeyName;
  5107. let targetValue = target[targetKeyName];
  5108. let sourceValue = source[sourceKeyName];
  5109. if (typeof sourceValue === "object" &&
  5110. sourceValue != null &&
  5111. sourceKeyName in target &&
  5112. !UtilsContext.isDOM(sourceValue)) {
  5113. /* 源端的值是object类型,且不是元素节点 */
  5114. target[sourceKeyName] = UtilsContext.assign(targetValue, sourceValue, isAdd);
  5115. continue;
  5116. }
  5117. target[sourceKeyName] = sourceValue;
  5118. }
  5119. }
  5120. else {
  5121. for (const targetKeyName in target) {
  5122. if (targetKeyName in source) {
  5123. let targetValue = target[targetKeyName];
  5124. let sourceValue = source[targetKeyName];
  5125. if (typeof sourceValue === "object" &&
  5126. sourceValue != null &&
  5127. !UtilsContext.isDOM(sourceValue) &&
  5128. Object.keys(sourceValue).length) {
  5129. /* 源端的值是object类型,且不是元素节点 */
  5130. target[targetKeyName] = UtilsContext.assign(targetValue, sourceValue, isAdd);
  5131. continue;
  5132. }
  5133. /* 直接赋值 */
  5134. target[targetKeyName] = sourceValue;
  5135. }
  5136. }
  5137. }
  5138. return target;
  5139. }
  5140. async asyncReplaceAll(string, pattern, asyncFn) {
  5141. let UtilsContext = this;
  5142. if (typeof string !== "string") {
  5143. throw new TypeError("string必须是字符串");
  5144. }
  5145. if (typeof asyncFn !== "function") {
  5146. throw new TypeError("asyncFn必须是函数");
  5147. }
  5148. let reg;
  5149. if (typeof pattern === "string") {
  5150. reg = new RegExp(UtilsContext.parseStringToRegExpString(pattern), "g");
  5151. }
  5152. else if (pattern instanceof RegExp) {
  5153. if (!pattern.global) {
  5154. throw new TypeError("pattern必须是全局匹配");
  5155. }
  5156. reg = new RegExp(pattern);
  5157. }
  5158. else {
  5159. throw new TypeError("pattern必须是正则对象");
  5160. }
  5161. let result = [];
  5162. let match;
  5163. let lastIndex = 0;
  5164. while ((match = reg.exec(string)) !== null) {
  5165. /* 异步获取匹配对应的字符串 */
  5166. const item = asyncFn(match[0]);
  5167. /* 获取该匹配项和上一个匹配项的中间的字符串 */
  5168. const prefix = string.slice(lastIndex, match.index);
  5169. lastIndex = match.index + match[0].length;
  5170. result.push(item);
  5171. result.push(prefix);
  5172. }
  5173. result.push(string.slice(lastIndex));
  5174. /* 等待所有异步完成 */
  5175. result = await Promise.all(result);
  5176. return result.join("");
  5177. }
  5178. /**
  5179. * ajax劫持库,支持xhr和fetch劫持。
  5180. * + 来源:https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
  5181. * + 作者:cxxjackie
  5182. * + 版本:1.4.4
  5183. * + 旧版本:1.2.4
  5184. * + 文档:https://scriptcat.org/zh-CN/script-show-page/637/
  5185. * @param useOldVersion 是否使用旧版本,默认false
  5186. */
  5187. ajaxHooker = (useOldVersion = false) => {
  5188. if (useOldVersion) {
  5189. return AjaxHooker1_2_4();
  5190. }
  5191. else {
  5192. return AjaxHooker();
  5193. }
  5194. };
  5195. canvasClickByPosition(canvasElement, clientX = 0, clientY = 0, view = globalThis) {
  5196. if (!(canvasElement instanceof HTMLCanvasElement)) {
  5197. throw new Error("Utils.canvasClickByPosition 参数canvasElement必须是canvas元素");
  5198. }
  5199. clientX = parseInt(clientX.toString());
  5200. clientY = parseInt(clientY.toString());
  5201. const eventInit = {
  5202. cancelBubble: true,
  5203. cancelable: true,
  5204. clientX: clientX,
  5205. clientY: clientY,
  5206. // @ts-ignore
  5207. view: view,
  5208. detail: 1,
  5209. };
  5210. canvasElement.dispatchEvent(new MouseEvent("mousedown", eventInit));
  5211. canvasElement.dispatchEvent(new MouseEvent("mouseup", eventInit));
  5212. }
  5213. checkUserClickInNode(element) {
  5214. let UtilsContext = this;
  5215. if (!UtilsContext.isDOM(element)) {
  5216. throw new Error("Utils.checkUserClickInNode 参数 targetNode 必须为 Element|Node 类型");
  5217. }
  5218. let clickEvent = UtilsContext.windowApi.window.event;
  5219. let touchEvent = UtilsContext.windowApi.window.event;
  5220. let $click = clickEvent?.composedPath()?.[0];
  5221. // 点击的x坐标
  5222. let clickPosX = clickEvent?.clientX != null
  5223. ? clickEvent.clientX
  5224. : touchEvent.touches[0].clientX;
  5225. // 点击的y坐标
  5226. let clickPosY = clickEvent?.clientY != null
  5227. ? clickEvent.clientY
  5228. : touchEvent.touches[0].clientY;
  5229. let {
  5230. /* 要检测的元素的相对屏幕的横坐标最左边 */
  5231. left: elementPosXLeft,
  5232. /* 要检测的元素的相对屏幕的横坐标最右边 */
  5233. right: elementPosXRight,
  5234. /* 要检测的元素的相对屏幕的纵坐标最上边 */
  5235. top: elementPosYTop,
  5236. /* 要检测的元素的相对屏幕的纵坐标最下边 */
  5237. bottom: elementPosYBottom, } = element.getBoundingClientRect();
  5238. if (clickPosX >= elementPosXLeft &&
  5239. clickPosX <= elementPosXRight &&
  5240. clickPosY >= elementPosYTop &&
  5241. clickPosY <= elementPosYBottom) {
  5242. return true;
  5243. }
  5244. else if (($click && element.contains($click)) || $click == element) {
  5245. /* 这种情况是应对在界面中隐藏的元素,getBoundingClientRect获取的都是0 */
  5246. return true;
  5247. }
  5248. else {
  5249. return false;
  5250. }
  5251. }
  5252. /**
  5253. * 复制formData数据
  5254. * @param formData 需要clone的数据
  5255. */
  5256. cloneFormData(formData, filterFn) {
  5257. let clonedFormData = new FormData();
  5258. for (let [key, value] of formData.entries()) {
  5259. let isFilter = typeof filterFn === "function" ? filterFn(key, value) : false;
  5260. if (typeof isFilter === "boolean" && isFilter) {
  5261. continue;
  5262. }
  5263. clonedFormData.append(key, value);
  5264. }
  5265. return clonedFormData;
  5266. }
  5267. createOverload() {
  5268. let fnMap = new Map();
  5269. function overload(...args) {
  5270. let key = args.map((it) => typeof it).join(",");
  5271. let fn = fnMap.get(key);
  5272. if (!fn) {
  5273. throw new TypeError("没有找到对应的实现");
  5274. }
  5275. return fn.apply(this, args);
  5276. }
  5277. overload.addImpl = function (...args) {
  5278. let fn = args.pop();
  5279. if (typeof fn !== "function") {
  5280. throw new TypeError("最后一个参数必须是函数");
  5281. }
  5282. let key = args.join(",");
  5283. fnMap.set(key, fn);
  5284. };
  5285. return overload;
  5286. }
  5287. /**
  5288. * 颜色转换
  5289. * @returns
  5290. */
  5291. ColorConversion = ColorConversion;
  5292. deepClone(obj) {
  5293. let UtilsContext = this;
  5294. if (obj === undefined)
  5295. return undefined;
  5296. if (obj === null)
  5297. return null;
  5298. let clone = obj instanceof Array ? [] : {};
  5299. for (const [key, value] of Object.entries(obj)) {
  5300. clone[key] =
  5301. typeof value === "object" ? UtilsContext.deepClone(value) : value;
  5302. }
  5303. return clone;
  5304. }
  5305. debounce(fn, delay = 0) {
  5306. let timer = null;
  5307. const context = this;
  5308. return function (...args) {
  5309. clearTimeout(timer);
  5310. timer = setTimeout(function () {
  5311. fn.apply(context, args);
  5312. }, delay);
  5313. };
  5314. }
  5315. deleteParentNode(element, targetSelector) {
  5316. let UtilsContext = this;
  5317. if (element == null) {
  5318. return;
  5319. }
  5320. if (!UtilsContext.isDOM(element)) {
  5321. throw new Error("Utils.deleteParentNode 参数 target 必须为 Node|HTMLElement 类型");
  5322. }
  5323. if (typeof targetSelector !== "string") {
  5324. throw new Error("Utils.deleteParentNode 参数 targetSelector 必须为 string 类型");
  5325. }
  5326. let result = false;
  5327. let needRemoveDOM = element.closest(targetSelector);
  5328. if (needRemoveDOM) {
  5329. needRemoveDOM.remove();
  5330. result = true;
  5331. }
  5332. return result;
  5333. }
  5334. /**
  5335. * 字典
  5336. * @example
  5337. * let dictionary = new Utils.Dictionary();
  5338. * let dictionary2 = new Utils.Dictionary();
  5339. * dictionary.set("test","111");
  5340. * dictionary.get("test");
  5341. * > '111'
  5342. * dictionary.has("test");
  5343. * > true
  5344. * dictionary.concat(dictionary2);
  5345. **/
  5346. Dictionary = UtilsDictionary;
  5347. dispatchEvent(element, eventName, details) {
  5348. let eventNameList = [];
  5349. if (typeof eventName === "string") {
  5350. eventNameList = [eventName];
  5351. }
  5352. if (Array.isArray(eventName)) {
  5353. eventNameList = [...eventName];
  5354. }
  5355. eventNameList.forEach((_eventName_) => {
  5356. let event = new Event(_eventName_);
  5357. if (details) {
  5358. Object.assign(event, details);
  5359. }
  5360. element.dispatchEvent(event);
  5361. });
  5362. }
  5363. downloadBase64(base64Data, fileName, isIFrame = false) {
  5364. if (typeof base64Data !== "string") {
  5365. throw new Error("Utils.downloadBase64 参数 base64Data 必须为 string 类型");
  5366. }
  5367. if (typeof fileName !== "string") {
  5368. throw new Error("Utils.downloadBase64 参数 fileName 必须为 string 类型");
  5369. }
  5370. if (isIFrame) {
  5371. /* 使用iframe */
  5372. const iframeElement = this.windowApi.document.createElement("iframe");
  5373. iframeElement.style.display = "none";
  5374. iframeElement.src = base64Data;
  5375. this.windowApi.document.body.appendChild(iframeElement);
  5376. setTimeout(() => {
  5377. iframeElement.contentWindow.document.execCommand("SaveAs", true, fileName);
  5378. this.windowApi.document.body.removeChild(iframeElement);
  5379. }, 100);
  5380. }
  5381. else {
  5382. /* 使用A标签 */
  5383. const linkElement = this.windowApi.document.createElement("a");
  5384. linkElement.setAttribute("target", "_blank");
  5385. linkElement.download = fileName;
  5386. linkElement.href = base64Data;
  5387. linkElement.click();
  5388. }
  5389. }
  5390. findWebPageVisibleText(str = "", caseSensitive = false) {
  5391. let TRange = null;
  5392. let strFound;
  5393. if (this.windowApi.globalThis.find) {
  5394. /* CODE FOR BROWSERS THAT SUPPORT window.find */
  5395. let windowFind = this.windowApi.self.find;
  5396. strFound = windowFind(str, caseSensitive, true, true, false);
  5397. if (strFound &&
  5398. this.windowApi.self.getSelection &&
  5399. !this.windowApi.self.getSelection().anchorNode) {
  5400. strFound = windowFind(str, caseSensitive, true, true, false);
  5401. }
  5402. if (!strFound) {
  5403. strFound = windowFind(str, 0, 1);
  5404. while (windowFind(str, 0, 1))
  5405. continue;
  5406. }
  5407. }
  5408. else if (navigator.appName.indexOf("Microsoft") != -1) {
  5409. /* EXPLORER-SPECIFIC CODE */
  5410. if (TRange != null) {
  5411. TRange = TRange;
  5412. TRange.collapse(false);
  5413. strFound = TRange.findText(str);
  5414. if (strFound)
  5415. TRange.select();
  5416. }
  5417. if (TRange == null || strFound == 0) {
  5418. TRange = this.windowApi.self.document.body.createTextRange();
  5419. strFound = TRange.findText(str);
  5420. if (strFound)
  5421. TRange.select();
  5422. }
  5423. }
  5424. else if (navigator.appName == "Opera") {
  5425. alert("Opera browsers not supported, sorry...");
  5426. return;
  5427. }
  5428. return strFound ? true : false;
  5429. }
  5430. *findElementsWithText(element, text, filter) {
  5431. let that = this;
  5432. if (element.outerHTML.includes(text)) {
  5433. if (element.children.length === 0) {
  5434. let filterResult = typeof filter === "function" ? filter(element) : false;
  5435. if (!filterResult) {
  5436. yield element;
  5437. }
  5438. }
  5439. else {
  5440. let textElement = Array.from(element.childNodes).filter((ele) => ele.nodeType === Node.TEXT_NODE);
  5441. for (let ele of textElement) {
  5442. if (ele.textContent.includes(text)) {
  5443. let filterResult = typeof filter === "function" ? filter(element) : false;
  5444. if (!filterResult) {
  5445. yield ele;
  5446. }
  5447. }
  5448. }
  5449. }
  5450. }
  5451. for (let index = 0; index < element.children.length; index++) {
  5452. let childElement = element.children[index];
  5453. yield* that.findElementsWithText(childElement, text, filter);
  5454. }
  5455. }
  5456. /**
  5457. * 判断该元素是否可见,如果不可见,向上找它的父元素直至找到可见的元素
  5458. * @param element
  5459. * @example
  5460. * let visibleElement = Utils.findVisibleElement(document.querySelector("a.xx"));
  5461. * > <HTMLElement>
  5462. */
  5463. findVisibleElement(element) {
  5464. let currentElement = element;
  5465. while (currentElement) {
  5466. let elementRect = currentElement.getBoundingClientRect();
  5467. if (Boolean(elementRect.length)) {
  5468. return currentElement;
  5469. }
  5470. currentElement = currentElement.parentElement;
  5471. }
  5472. return null;
  5473. }
  5474. formatByteToSize(byteSize, addType = true) {
  5475. byteSize = parseInt(byteSize.toString());
  5476. if (isNaN(byteSize)) {
  5477. throw new Error("Utils.formatByteToSize 参数 byteSize 格式不正确");
  5478. }
  5479. let result = 0;
  5480. let resultType = "KB";
  5481. let sizeData = {};
  5482. sizeData.B = 1;
  5483. sizeData.KB = 1024;
  5484. sizeData.MB = sizeData.KB * sizeData.KB;
  5485. sizeData.GB = sizeData.MB * sizeData.KB;
  5486. sizeData.TB = sizeData.GB * sizeData.KB;
  5487. sizeData.PB = sizeData.TB * sizeData.KB;
  5488. sizeData.EB = sizeData.PB * sizeData.KB;
  5489. sizeData.ZB = sizeData.EB * sizeData.KB;
  5490. sizeData.YB = sizeData.ZB * sizeData.KB;
  5491. sizeData.BB = sizeData.YB * sizeData.KB;
  5492. sizeData.NB = sizeData.BB * sizeData.KB;
  5493. sizeData.DB = sizeData.NB * sizeData.KB;
  5494. for (let key in sizeData) {
  5495. result = byteSize / sizeData[key];
  5496. resultType = key;
  5497. if (sizeData.KB >= result) {
  5498. break;
  5499. }
  5500. }
  5501. result = result.toFixed(2);
  5502. result = addType
  5503. ? result + resultType.toString()
  5504. : parseFloat(result.toString());
  5505. return result;
  5506. }
  5507. getNodeListValue(...args) {
  5508. let resultArray = [];
  5509. for (let arg of args) {
  5510. let value = arg;
  5511. if (typeof arg === "function") {
  5512. /* 方法 */
  5513. value = arg();
  5514. }
  5515. if (value.length !== 0) {
  5516. resultArray = [...value];
  5517. break;
  5518. }
  5519. }
  5520. return resultArray;
  5521. }
  5522. getNonNullValue(...args) {
  5523. let resultValue = args[args.length - 1];
  5524. let UtilsContext = this;
  5525. for (const argValue of args) {
  5526. if (UtilsContext.isNotNull(argValue)) {
  5527. resultValue = argValue;
  5528. break;
  5529. }
  5530. }
  5531. return resultValue;
  5532. }
  5533. formatTime(text = new Date(), formatType = "yyyy-MM-dd HH:mm:ss") {
  5534. let time = text == null ? new Date() : new Date(text);
  5535. /**
  5536. * 校验时间补0
  5537. * @param timeNum
  5538. * @returns
  5539. */
  5540. function checkTime(timeNum) {
  5541. if (timeNum < 10)
  5542. return "0" + timeNum;
  5543. return timeNum;
  5544. }
  5545. /**
  5546. * 时间制修改 24小时制转12小时制
  5547. * @param hourNum 小时
  5548. * @returns
  5549. */
  5550. function timeSystemChange(hourNum) {
  5551. return hourNum > 12 ? hourNum - 12 : hourNum;
  5552. }
  5553. let timeRegexp = {
  5554. yyyy: time.getFullYear(),
  5555. /* 年 */
  5556. MM: checkTime(time.getMonth() + 1),
  5557. /* 月 */
  5558. dd: checkTime(time.getDate()),
  5559. /* 日 */
  5560. HH: checkTime(time.getHours()),
  5561. /* 时 (24小时制) */
  5562. hh: checkTime(timeSystemChange(time.getHours())),
  5563. /* 时 (12小时制) */
  5564. mm: checkTime(time.getMinutes()),
  5565. /* 分 */
  5566. ss: checkTime(time.getSeconds()),
  5567. /* 秒 */
  5568. };
  5569. Object.keys(timeRegexp).forEach(function (key) {
  5570. let replaecRegexp = new RegExp(key, "g");
  5571. formatType = formatType.replace(replaecRegexp, timeRegexp[key]);
  5572. });
  5573. return formatType;
  5574. }
  5575. formatToTimeStamp(text) {
  5576. /* 把字符串格式的时间(完整,包括日期和时间)格式化成时间 */
  5577. if (typeof text !== "string") {
  5578. throw new Error("Utils.formatToTimeStamp 参数 text 必须为 string 类型");
  5579. }
  5580. if (text.length === 8) {
  5581. /* 该字符串只有时分秒 */
  5582. let today = new Date();
  5583. text =
  5584. today.getFullYear() +
  5585. "-" +
  5586. (today.getMonth() + 1) +
  5587. "-" +
  5588. today.getDate() +
  5589. " " +
  5590. text;
  5591. }
  5592. text = text.substring(0, 19);
  5593. text = text.replace(/-/g, "/");
  5594. let timestamp = new Date(text).getTime();
  5595. return timestamp;
  5596. }
  5597. /**
  5598. * gbk格式的url编码,来自https://gf.qytechs.cn/zh-CN/scripts/427726-gbk-url-js
  5599. * @example
  5600. * let gbkEncoder = new Utils.GBKEncoder();
  5601. * gbkEncoder.encode("测试");
  5602. * > '%B2%E2%CA%D4'
  5603. * gbkEncoder.decode("%B2%E2%CA%D4");
  5604. * > 测试
  5605. */
  5606. GBKEncoder = GBKEncoder;
  5607. /**
  5608. * 获取 transitionend 的在各个浏览器的兼容名
  5609. */
  5610. getTransitionEndNameList() {
  5611. return [
  5612. "webkitTransitionEnd",
  5613. "mozTransitionEnd",
  5614. "MSTransitionEnd",
  5615. "otransitionend",
  5616. "transitionend",
  5617. ];
  5618. }
  5619. /**
  5620. * 获取 animationend 的在各个浏览器的兼容名
  5621. */
  5622. getAnimationEndNameList() {
  5623. return [
  5624. "webkitAnimationEnd",
  5625. "mozAnimationEnd",
  5626. "MSAnimationEnd",
  5627. "oanimationend",
  5628. "animationend",
  5629. ];
  5630. }
  5631. getArrayLastValue(targetObj) {
  5632. return targetObj[targetObj.length - 1];
  5633. }
  5634. getArrayRealValue(...args) {
  5635. let result = null;
  5636. for (let arg of args) {
  5637. if (typeof arg === "function") {
  5638. /* 方法 */
  5639. arg = arg();
  5640. }
  5641. if (arg != null) {
  5642. result = arg;
  5643. break;
  5644. }
  5645. }
  5646. return result;
  5647. }
  5648. getDaysDifference(timestamp1 = Date.now(), timestamp2 = Date.now(), type = "天") {
  5649. type = type.trim();
  5650. if (timestamp1.toString().length === 10) {
  5651. timestamp1 = timestamp1 * 1000;
  5652. }
  5653. if (timestamp2.toString().length === 10) {
  5654. timestamp2 = timestamp2 * 1000;
  5655. }
  5656. let smallTimeStamp = timestamp1 > timestamp2 ? timestamp2 : timestamp1;
  5657. let bigTimeStamp = timestamp1 > timestamp2 ? timestamp1 : timestamp2;
  5658. let oneSecond = 1000; /* 一秒的毫秒数 */
  5659. let oneMinute = 60 * oneSecond; /* 一分钟的毫秒数 */
  5660. let oneHour = 60 * oneMinute; /* 一小时的毫秒数 */
  5661. let oneDay = 24 * oneHour; /* 一天的毫秒数 */
  5662. let oneMonth = 30 * oneDay; /* 一个月的毫秒数(30天) */
  5663. let oneYear = 12 * oneMonth; /* 一年的毫秒数 */
  5664. let bigDate = new Date(bigTimeStamp);
  5665. let smallDate = new Date(smallTimeStamp);
  5666. let remainderValue = 1;
  5667. if (type === "年") {
  5668. remainderValue = oneYear;
  5669. }
  5670. else if (type === "月") {
  5671. remainderValue = oneMonth;
  5672. }
  5673. else if (type === "天") {
  5674. remainderValue = oneDay;
  5675. }
  5676. else if (type === "时") {
  5677. remainderValue = oneHour;
  5678. }
  5679. else if (type === "分") {
  5680. remainderValue = oneMinute;
  5681. }
  5682. else if (type === "秒") {
  5683. remainderValue = oneSecond;
  5684. }
  5685. let diffValue = Math.round(Math.abs((bigDate - smallDate) / remainderValue));
  5686. if (type === "auto") {
  5687. let timeDifference = bigTimeStamp - smallTimeStamp;
  5688. diffValue = Math.floor(timeDifference / (24 * 3600 * 1000));
  5689. if (diffValue > 0) {
  5690. diffValue = diffValue + "天";
  5691. }
  5692. else {
  5693. /* 计算出小时数 */
  5694. let leave1 = timeDifference % (24 * 3600 * 1000); /* 计算天数后剩余的毫秒数 */
  5695. let hours = Math.floor(leave1 / (3600 * 1000));
  5696. if (hours > 0) {
  5697. diffValue = hours + "小时";
  5698. }
  5699. else {
  5700. /* 计算相差分钟数 */
  5701. let leave2 = leave1 % (3600 * 1000); /* 计算小时数后剩余的毫秒数 */
  5702. let minutes = Math.floor(leave2 / (60 * 1000));
  5703. if (minutes > 0) {
  5704. diffValue = minutes + "分钟";
  5705. }
  5706. else {
  5707. /* 计算相差秒数 */
  5708. let leave3 = leave2 % (60 * 1000); /* 计算分钟数后剩余的毫秒数 */
  5709. let seconds = Math.round(leave3 / 1000);
  5710. diffValue = seconds + "秒";
  5711. }
  5712. }
  5713. }
  5714. }
  5715. return diffValue;
  5716. }
  5717. getElementSelector(element) {
  5718. let UtilsContext = this;
  5719. // @ts-ignore
  5720. if (!element)
  5721. return;
  5722. // @ts-ignore
  5723. if (!element.parentElement)
  5724. return;
  5725. /* 如果元素有id属性,则直接返回id选择器 */
  5726. if (element.id)
  5727. return "#" + element.id;
  5728. /* 递归地获取父元素的选择器 */
  5729. let selector = UtilsContext.getElementSelector(element.parentElement);
  5730. if (!selector) {
  5731. return element.tagName.toLowerCase();
  5732. }
  5733. /* 如果有多个相同类型的兄弟元素,则需要添加索引 */
  5734. if (element.parentElement.querySelectorAll(element.tagName).length > 1) {
  5735. let index = Array.prototype.indexOf.call(element.parentElement.children, element) +
  5736. 1;
  5737. selector +=
  5738. " > " + element.tagName.toLowerCase() + ":nth-child(" + index + ")";
  5739. }
  5740. else {
  5741. selector += " > " + element.tagName.toLowerCase();
  5742. }
  5743. return selector;
  5744. }
  5745. /**
  5746. * 获取最大值
  5747. * @example
  5748. * Utils.getMaxValue([{1:123},{2:345},{3:456}],(index,value)=>{return parseInt(index)})
  5749. * > 2
  5750. */
  5751. getMaxValue(...args) {
  5752. let result = [...args];
  5753. let newResult = [];
  5754. if (result.length === 0) {
  5755. // @ts-ignore
  5756. return;
  5757. }
  5758. if (result.length > 1) {
  5759. if (result.length === 2 &&
  5760. typeof result[0] === "object" &&
  5761. typeof result[1] === "function") {
  5762. let data = result[0];
  5763. let handleDataFunc = result[1];
  5764. Object.keys(data).forEach((keyName) => {
  5765. newResult = [...newResult, handleDataFunc(keyName, data[keyName])];
  5766. });
  5767. }
  5768. else {
  5769. result.forEach((item) => {
  5770. if (!isNaN(parseFloat(item))) {
  5771. newResult = [...newResult, parseFloat(item)];
  5772. }
  5773. });
  5774. }
  5775. return Math.max(...newResult);
  5776. }
  5777. else {
  5778. result[0].forEach((item) => {
  5779. if (!isNaN(parseFloat(item))) {
  5780. newResult = [...newResult, parseFloat(item)];
  5781. }
  5782. });
  5783. return Math.max(...newResult);
  5784. }
  5785. }
  5786. getMaxZIndexNodeInfo(deviation = 1, target = this.windowApi.document, ignoreCallBack) {
  5787. deviation = Number.isNaN(deviation) ? 1 : deviation;
  5788. const UtilsContext = this;
  5789. // 最大值 2147483647
  5790. // const maxZIndex = Math.pow(2, 31) - 1;
  5791. // 比较值 2000000000
  5792. const maxZIndexCompare = 2 * Math.pow(10, 9);
  5793. // 当前页面最大的z-index
  5794. let zIndex = 0;
  5795. // 当前的最大z-index的元素,调试使用
  5796. // @ts-ignore
  5797. let maxZIndexNode = null;
  5798. /**
  5799. * 元素是否可见
  5800. * @param $css
  5801. */
  5802. function isVisibleNode($css) {
  5803. return $css.position !== "static" && $css.display !== "none";
  5804. }
  5805. /**
  5806. * 查询元素的z-index
  5807. * 并比较值是否是已获取的最大值
  5808. * @param $ele
  5809. */
  5810. function queryMaxZIndex($ele) {
  5811. if (typeof ignoreCallBack === "function") {
  5812. let ignoreResult = ignoreCallBack($ele);
  5813. if (typeof ignoreResult === "boolean" && !ignoreResult) {
  5814. return;
  5815. }
  5816. }
  5817. /** 元素的样式 */
  5818. const nodeStyle = UtilsContext.windowApi.window.getComputedStyle($ele);
  5819. /* 不对position为static和display为none的元素进行获取它们的z-index */
  5820. if (isVisibleNode(nodeStyle)) {
  5821. let nodeZIndex = parseInt(nodeStyle.zIndex);
  5822. if (!isNaN(nodeZIndex)) {
  5823. if (nodeZIndex > zIndex) {
  5824. // 赋值到全局
  5825. zIndex = nodeZIndex;
  5826. maxZIndexNode = $ele;
  5827. }
  5828. }
  5829. // 判断shadowRoot
  5830. if ($ele.shadowRoot != null && $ele instanceof ShadowRoot) {
  5831. $ele.shadowRoot.querySelectorAll("*").forEach(($shadowEle) => {
  5832. queryMaxZIndex($shadowEle);
  5833. });
  5834. }
  5835. }
  5836. }
  5837. target.querySelectorAll("*").forEach(($ele, index) => {
  5838. queryMaxZIndex($ele);
  5839. });
  5840. zIndex += deviation;
  5841. if (zIndex >= maxZIndexCompare) {
  5842. // 最好不要超过最大值
  5843. zIndex = maxZIndexCompare;
  5844. }
  5845. return {
  5846. node: maxZIndexNode,
  5847. zIndex: zIndex,
  5848. };
  5849. }
  5850. getMaxZIndex(deviation = 1, target = this.windowApi.document, ignoreCallBack) {
  5851. return this.getMaxZIndexNodeInfo(deviation, target, ignoreCallBack).zIndex;
  5852. }
  5853. getMinValue(...args) {
  5854. let result = [...args];
  5855. let newResult = [];
  5856. if (result.length === 0) {
  5857. // @ts-ignore
  5858. return;
  5859. }
  5860. if (result.length > 1) {
  5861. if (result.length === 2 &&
  5862. typeof result[0] === "object" &&
  5863. typeof result[1] === "function") {
  5864. let data = result[0];
  5865. let handleDataFunc = result[1];
  5866. Object.keys(data).forEach((keyName) => {
  5867. newResult = [...newResult, handleDataFunc(keyName, data[keyName])];
  5868. });
  5869. }
  5870. else {
  5871. result.forEach((item) => {
  5872. if (!isNaN(parseFloat(item))) {
  5873. newResult = [...newResult, parseFloat(item)];
  5874. }
  5875. });
  5876. }
  5877. return Math.min(...newResult);
  5878. }
  5879. else {
  5880. result[0].forEach((item) => {
  5881. if (!isNaN(parseFloat(item))) {
  5882. newResult = [...newResult, parseFloat(item)];
  5883. }
  5884. });
  5885. return Math.min(...newResult);
  5886. }
  5887. }
  5888. /**
  5889. * 获取随机的安卓手机User-Agent
  5890. * @example
  5891. * Utils.getRandomAndroidUA();
  5892. * > 'Mozilla/5.0 (Linux; Android 10; MI 13 Build/OPR1.170623.027; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.3490.40 Mobile Safari/537.36'
  5893. **/
  5894. getRandomAndroidUA() {
  5895. let UtilsContext = this;
  5896. let mobileNameList = [
  5897. "LDN-LX3",
  5898. "RNE-L03",
  5899. "ASUS_X00ID Build/NMF26F",
  5900. "WAS-LX3",
  5901. "PRA-LX3",
  5902. "MYA-L03",
  5903. "Moto G Play",
  5904. "Moto C Build/NRD90M.063",
  5905. "Redmi Note 4 Build/NRD90M",
  5906. "HUAWEI VNS-L21 Build/HUAWEIVNS-L21",
  5907. "VTR-L09",
  5908. "TRT-LX3",
  5909. "M2003J15SC Build/RP1A.200720.011; wv",
  5910. "MI 13 Build/OPR1.170623.027; wv",
  5911. ];
  5912. /* 安卓版本 */
  5913. let androidVersion = UtilsContext.getRandomValue(12, 14);
  5914. /* 手机型号 */
  5915. let randomMobile = UtilsContext.getRandomValue(mobileNameList);
  5916. /* chrome大版本号 */
  5917. let chromeVersion1 = UtilsContext.getRandomValue(120, 132);
  5918. let chromeVersion2 = UtilsContext.getRandomValue(0, 0);
  5919. let chromeVersion3 = UtilsContext.getRandomValue(2272, 6099);
  5920. let chromeVersion4 = UtilsContext.getRandomValue(1, 218);
  5921. return `Mozilla/5.0 (Linux; Android ${androidVersion}; ${randomMobile}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion1}.${chromeVersion2}.${chromeVersion3}.${chromeVersion4} Mobile Safari/537.36`;
  5922. }
  5923. /**
  5924. * 获取随机的电脑端User-Agent
  5925. * + Mozilla/5.0:以前用于Netscape浏览器,目前大多数浏览器UA都会带有
  5926. * + Windows NT 13:代表Window11系统
  5927. * + Windows NT 10.0:代表Window10系统
  5928. * + Windows NT 6.1:代表windows7系统
  5929. * + WOW64:Windows-on-Windows 64-bit,32位的应用程序运行于此64位处理器上
  5930. * + Win64:64位
  5931. * + AppleWebKit/537.36:浏览器内核
  5932. * + KHTML:HTML排版引擎
  5933. * + like Gecko:这不是Geckeo 浏览器,但是运行起来像Geckeo浏览器
  5934. * + Chrome/106.0.5068.19:Chrome版本号
  5935. * + Safari/537.36:宣称自己是Safari?
  5936. * @returns 返回随机字符串
  5937. * @example
  5938. * Utils.getRandomPCUA();
  5939. * > 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.5068.19 Safari/537.36'
  5940. **/
  5941. getRandomPCUA() {
  5942. let UtilsContext = this;
  5943. /* chrome大版本号 */
  5944. let chromeVersion1 = UtilsContext.getRandomValue(120, 132);
  5945. let chromeVersion2 = UtilsContext.getRandomValue(0, 0);
  5946. let chromeVersion3 = UtilsContext.getRandomValue(2272, 6099);
  5947. let chromeVersion4 = UtilsContext.getRandomValue(1, 218);
  5948. return `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion1}.${chromeVersion2}.${chromeVersion3}.${chromeVersion4} Safari/537.36`;
  5949. }
  5950. getRandomValue(...args) {
  5951. let result = [...args];
  5952. if (result.length > 1) {
  5953. if (result.length === 2 &&
  5954. typeof result[0] === "number" &&
  5955. typeof result[1] === "number") {
  5956. let leftNumber = result[0] > result[1] ? result[1] : result[0];
  5957. let rightNumber = result[0] > result[1] ? result[0] : result[1];
  5958. return (Math.round(Math.random() * (rightNumber - leftNumber)) + leftNumber);
  5959. }
  5960. else {
  5961. return result[Math.floor(Math.random() * result.length)];
  5962. }
  5963. }
  5964. else if (result.length === 1) {
  5965. let paramData = result[0];
  5966. if (Array.isArray(paramData)) {
  5967. return paramData[Math.floor(Math.random() * paramData.length)];
  5968. }
  5969. else if (typeof paramData === "object" &&
  5970. Object.keys(paramData).length > 0) {
  5971. let paramObjDataKey = Object.keys(paramData)[Math.floor(Math.random() * Object.keys(paramData).length)];
  5972. return paramData[paramObjDataKey];
  5973. }
  5974. else {
  5975. return paramData;
  5976. }
  5977. }
  5978. }
  5979. /**
  5980. * 获取元素上的使用React框架的实例属性,目前包括reactFiber、reactProps、reactEvents、reactEventHandlers、reactInternalInstance
  5981. * @param element 需要获取的目标元素
  5982. * @returns
  5983. * @example
  5984. * Utils.getReactObj(document.querySelector("input"))?.reactProps?.onChange({target:{value:"123"}});
  5985. */
  5986. getReactObj(element) {
  5987. let result = {};
  5988. Object.keys(element).forEach((domPropsName) => {
  5989. if (domPropsName.startsWith("__react")) {
  5990. let propsName = domPropsName.replace(/__(.+)\$.+/i, "$1");
  5991. if (propsName in result) ;
  5992. else {
  5993. result[propsName] = element[domPropsName];
  5994. }
  5995. }
  5996. });
  5997. return result;
  5998. }
  5999. /**
  6000. * 获取对象上的Symbol属性,如果没设置keyName,那么返回一个对象,对象是所有遍历到的Symbol对象
  6001. * @param target 目标对象
  6002. * @param keyName (可选)Symbol名或者Symbol对象
  6003. */
  6004. getSymbol(target, keyName) {
  6005. if (typeof target !== "object") {
  6006. throw new TypeError("target不是一个对象");
  6007. }
  6008. let objectsSymbols = Object.getOwnPropertySymbols(target);
  6009. if (typeof keyName === "string") {
  6010. let findSymbol = objectsSymbols.find((key) => {
  6011. return key.toString() === keyName;
  6012. });
  6013. if (findSymbol) {
  6014. return target[findSymbol];
  6015. }
  6016. }
  6017. else if (typeof keyName === "symbol") {
  6018. let findSymbol = objectsSymbols.find((key) => {
  6019. return key === keyName;
  6020. });
  6021. if (findSymbol) {
  6022. return target[findSymbol];
  6023. }
  6024. }
  6025. else {
  6026. let result = {};
  6027. objectsSymbols.forEach((item) => {
  6028. result[item] = target[item];
  6029. });
  6030. return result;
  6031. }
  6032. }
  6033. /**
  6034. * 获取文本的字符长度
  6035. * @param text
  6036. * @example
  6037. * Utils.getTextLength("测试文本")
  6038. * > 12
  6039. */
  6040. getTextLength(text) {
  6041. let encoder = new TextEncoder();
  6042. let bytes = encoder.encode(text);
  6043. return bytes.length;
  6044. }
  6045. getTextStorageSize(text, addType = true) {
  6046. let UtilsContext = this;
  6047. return UtilsContext.formatByteToSize(UtilsContext.getTextLength(text), addType);
  6048. }
  6049. getThunderUrl(url) {
  6050. if (url == null) {
  6051. throw new TypeError("url不能为空");
  6052. }
  6053. if (typeof url !== "string") {
  6054. throw new TypeError("url必须是string类型");
  6055. }
  6056. if (url.trim() === "") {
  6057. throw new TypeError("url不能为空字符串或纯空格");
  6058. }
  6059. return `thunder://${this.windowApi.globalThis.btoa("AA" + url + "ZZ")}`;
  6060. }
  6061. /**
  6062. * 对于GM_cookie的兼容写法,当无法使用GM_cookie时可以使用这个,但是并不完全兼容,有些写不出来且限制了httponly是无法访问的
  6063. * @example
  6064. let GM_cookie = new Utils.GM_Cookie();
  6065. GM_cookie.list({name:"xxx_cookie_xxx"},function(cookies,error){
  6066. if (!error) {
  6067. console.log(cookies);
  6068. console.log(cookies.value);
  6069. } else {
  6070. console.error(error);
  6071. }
  6072. });
  6073. GM_cookie.set({name:"xxx_cookie_test_xxx",value:"这是Cookie测试值"},function(error){
  6074. if (error) {
  6075. console.error(error);
  6076. } else {
  6077. console.log('Cookie set successfully.');
  6078. }
  6079. })
  6080. GM_cookie.delete({name:"xxx_cookie_test_xxx"},function(error){
  6081. if (error) {
  6082. console.error(error);
  6083. } else {
  6084. console.log('Cookie set successfully.');
  6085. }
  6086. })
  6087. **/
  6088. GM_Cookie = UtilsGMCookie;
  6089. /**
  6090. * 注册(不可用)油猴菜单,要求本地存储的键名不能存在其它键名`GM_Menu_Local_Map`会冲突/覆盖
  6091. * @example
  6092. let GM_Menu = new Utils.GM_Menu({
  6093. data: [
  6094. {
  6095. menu_key: "menu_key",
  6096. text: "测试按钮",
  6097. enable: true,
  6098. accessKey: "a",
  6099. autoClose: false,
  6100. showText(text, enable) {
  6101. return "[" + (enable ? "√" : "×") + "]" + text;
  6102. },
  6103. callback(data) {
  6104. console.log("点击菜单,值修改为", data.enable);
  6105. },
  6106. },
  6107. ],
  6108. autoReload: false,
  6109. GM_getValue,
  6110. GM_setValue,
  6111. GM_registerMenuCommand,
  6112. GM_unregisterMenuCommand,
  6113. });
  6114. // 获取某个菜单项的值
  6115. GM_Menu.get("menu_key");
  6116. > true
  6117. // 获取某个菜单项的开启/关闭后显示的文本
  6118. GM_Menu.getShowTextValue("menu_key");
  6119. > √测试按钮
  6120. // 添加键为menu_key2的菜单项
  6121. GM_Menu.add({
  6122. key:"menu_key2",
  6123. text: "测试按钮2",
  6124. enable: false,
  6125. showText(text,enable){
  6126. return "[" + (enable ? "√" : "×") + "]" + text;
  6127. },
  6128. callback(data){
  6129. console.log("点击菜单,值修改为",data.enable);
  6130. }
  6131. });
  6132. // 使用数组的方式添加多个菜单,如menu_key3、menu_key4
  6133. GM_Menu.add([
  6134. {
  6135. key:"menu_key3",
  6136. text: "测试按钮3",
  6137. enable: false,
  6138. showText(text,enable){
  6139. return "[" + (enable ? "√" : "×") + "]" + text;
  6140. },
  6141. callback(data){
  6142. console.log("点击菜单,值修改为",data.enable);
  6143. }
  6144. },
  6145. {
  6146. key:"menu_key4",
  6147. text: "测试按钮4",
  6148. enable: false,
  6149. showText(text,enable){
  6150. return "[" + (enable ? "√" : "×") + "]" + text;
  6151. },
  6152. callback(data){
  6153. console.log("点击菜单,值修改为",data.enable);
  6154. }
  6155. }
  6156. ]);
  6157. // 更新键为menu_key的显示文字和点击回调
  6158. GM_Menu.update({
  6159. menu_key:{
  6160. text: "更新后的测试按钮",
  6161. enable: true,
  6162. showText(text,enable){
  6163. return "[" + (enable ? "√" : "×") + "]" + text;
  6164. },
  6165. callback(data){
  6166. console.log("点击菜单更新后的测试按钮,新值修改为",data.enable);
  6167. }
  6168. }
  6169. });
  6170. // 删除键为menu_key的菜单
  6171. GM_Menu.delete("menu_key");
  6172. **/
  6173. GM_Menu = GMMenu;
  6174. /**
  6175. * 基于Function prototype,能够勾住和释放任何函数
  6176. *
  6177. * .hook
  6178. * + realFunc {string} 用于保存原始函数的函数名称,用于unHook
  6179. * + hookFunc {string} 替换的hook函数
  6180. * + context {object} 目标函数所在对象,用于hook非window对象下的函数,如String.protype.slice,carInstance1
  6181. * + methodName {string} 匿名函数需显式传入目标函数名eg:this.Begin = function(){....};}
  6182. *
  6183. * .unhook
  6184. * + realFunc {string} 用于保存原始函数的函数名称,用于unHook
  6185. * + funcName {string} 被Hook的函数名称
  6186. * + context {object} 目标函数所在对象,用于hook非window对象下的函数,如String.protype.slice,carInstance1
  6187. * @example
  6188. let hook = new Utils.Hooks();
  6189. hook.initEnv();
  6190. function myFunction(){
  6191. console.log("我自己需要执行的函数");
  6192. }
  6193. function testFunction(){
  6194. console.log("正常执行的函数");
  6195. }
  6196. testFunction.hook(testFunction,myFunction,window);
  6197. **/
  6198. Hooks = Hooks;
  6199. /**
  6200. * 为减少代码量和回调,把GM_xmlhttpRequest封装
  6201. * 文档地址: https://www.tampermonkey.net/documentation.php?ext=iikm
  6202. * 其中onloadstart、onprogress、onreadystatechange是回调形式,onabort、ontimeout、onerror可以设置全局回调函数
  6203. * @param _GM_xmlHttpRequest_ 油猴中的GM_xmlhttpRequest
  6204. * @example
  6205. let httpx = new Utils.Httpx(GM_xmlhttpRequest);
  6206. let postResp = await httpx.post({
  6207. url:url,
  6208. data:JSON.stringify({
  6209. test:1
  6210. }),
  6211. timeout: 5000
  6212. });
  6213. console.log(postResp);
  6214. > {
  6215. status: true,
  6216. data: {responseText: "...", response: xxx,...},
  6217. msg: "请求完毕",
  6218. type: "onload",
  6219. }
  6220. if(postResp === "onload" && postResp.status){
  6221. // onload
  6222. }else if(postResp === "ontimeout"){
  6223. // ontimeout
  6224. }
  6225. * @example
  6226. // 也可以先配置全局参数
  6227. let httpx = new Utils.Httpx(GM_xmlhttpRequest);
  6228. httpx.config({
  6229. timeout: 5000,
  6230. async: false,
  6231. responseType: "html",
  6232. redirect: "follow",
  6233. })
  6234. // 优先级为 默认details < 全局details < 单独的details
  6235. */
  6236. Httpx = Httpx;
  6237. /**
  6238. * 浏览器端的indexedDB操作封装
  6239. * @example
  6240. let db = new Utils.indexedDB('web_DB', 'nav_text')
  6241. let data = {name:'管理员', roleId: 1, type: 1};
  6242. db.save('list',data).then((resolve)=>{
  6243. console.log(resolve,'存储成功')
  6244. })
  6245. db.get('list').then((resolve)=>{
  6246. console.log(resolve,'查询成功')
  6247. })
  6248. db.getPaging('list',20,10).then((resolve)=>{
  6249. console.log(resolve,'查询分页偏移第20,一共10行成功');
  6250. })
  6251. db.delete('list').then(resolve=>{
  6252. console.log(resolve,'删除成功---->>>>>>name')
  6253. })
  6254. db.deleteAll().then(resolve=>{
  6255. console.log(resolve,'清除数据库---->>>>>>name')
  6256. })
  6257. **/
  6258. indexedDB = indexedDB;
  6259. isNativeFunc(target) {
  6260. return Boolean(target.toString().match(/^function .*\(\) { \[native code\] }$/));
  6261. }
  6262. isNearBottom(...args) {
  6263. let nearBottomHeight = 50;
  6264. let checkWindow = () => {
  6265. // 已滚动的距离
  6266. let scrollTop = this.windowApi.window.pageYOffset ||
  6267. this.windowApi.document.documentElement.scrollTop;
  6268. // 视窗高度
  6269. let viewportHeight = this.windowApi.window.innerHeight ||
  6270. this.windowApi.document.documentElement.clientHeight;
  6271. // 最大滚动距离
  6272. let maxScrollHeight = this.windowApi.document.documentElement.scrollHeight - nearBottomHeight;
  6273. return scrollTop + viewportHeight >= maxScrollHeight;
  6274. };
  6275. let checkNode = ($ele) => {
  6276. // 已滚动的距离
  6277. let scrollTop = $ele.scrollTop;
  6278. // 视窗高度
  6279. let viewportHeight = $ele.clientHeight;
  6280. // 最大滚动距离
  6281. let maxScrollHeight = $ele.scrollHeight - viewportHeight - nearBottomHeight;
  6282. return scrollTop >= maxScrollHeight;
  6283. };
  6284. let firstArg = args[0];
  6285. if (args.length === 0 || typeof args[0] === "number") {
  6286. // nearBottomHeight
  6287. //
  6288. return checkWindow();
  6289. }
  6290. else if (typeof args[0] === "object" && args[0] instanceof HTMLElement) {
  6291. // target
  6292. // target,nearBottomHeight
  6293. if (typeof args[1] === "number" && !Number.isNaN(args[1])) {
  6294. nearBottomHeight = args[1];
  6295. }
  6296. return checkNode(args[0]);
  6297. }
  6298. else {
  6299. throw new TypeError("参数1类型错误" + typeof firstArg);
  6300. }
  6301. }
  6302. isDOM(target) {
  6303. return target instanceof Node;
  6304. }
  6305. isFullscreenEnabled() {
  6306. return !!(this.windowApi.document.fullscreenEnabled ||
  6307. this.windowApi.document.webkitFullScreenEnabled ||
  6308. this.windowApi.document.mozFullScreenEnabled ||
  6309. this.windowApi.document.msFullScreenEnabled);
  6310. }
  6311. isJQuery(target) {
  6312. let result = false;
  6313. // @ts-ignore
  6314. if (typeof jQuery === "object" && target instanceof jQuery) {
  6315. result = true;
  6316. }
  6317. if (target == null) {
  6318. return false;
  6319. }
  6320. if (typeof target === "object") {
  6321. /* 也有种可能,这个jQuery对象是1.8.3版本的,页面中的jQuery是3.4.1版本的 */
  6322. let jQueryProps = [
  6323. "add",
  6324. "addBack",
  6325. "addClass",
  6326. "after",
  6327. "ajaxComplete",
  6328. "ajaxError",
  6329. "ajaxSend",
  6330. "ajaxStart",
  6331. "ajaxStop",
  6332. "ajaxSuccess",
  6333. "animate",
  6334. "append",
  6335. "appendTo",
  6336. "attr",
  6337. "before",
  6338. "bind",
  6339. "blur",
  6340. "change",
  6341. "children",
  6342. "clearQueue",
  6343. "click",
  6344. "clone",
  6345. "closest",
  6346. "constructor",
  6347. "contents",
  6348. "contextmenu",
  6349. "css",
  6350. "data",
  6351. "dblclick",
  6352. "delay",
  6353. "delegate",
  6354. "dequeue",
  6355. "each",
  6356. "empty",
  6357. "end",
  6358. "eq",
  6359. "extend",
  6360. "fadeIn",
  6361. "fadeOut",
  6362. "fadeTo",
  6363. "fadeToggle",
  6364. "filter",
  6365. "find",
  6366. "first",
  6367. "focus",
  6368. "focusin",
  6369. "focusout",
  6370. "get",
  6371. "has",
  6372. "hasClass",
  6373. "height",
  6374. "hide",
  6375. "hover",
  6376. "html",
  6377. "index",
  6378. "init",
  6379. "innerHeight",
  6380. "innerWidth",
  6381. "insertAfter",
  6382. "insertBefore",
  6383. "is",
  6384. "jquery",
  6385. "keydown",
  6386. "keypress",
  6387. "keyup",
  6388. "last",
  6389. "load",
  6390. "map",
  6391. "mousedown",
  6392. "mouseenter",
  6393. "mouseleave",
  6394. "mousemove",
  6395. "mouseout",
  6396. "mouseover",
  6397. "mouseup",
  6398. "next",
  6399. "nextAll",
  6400. "not",
  6401. "off",
  6402. "offset",
  6403. "offsetParent",
  6404. "on",
  6405. "one",
  6406. "outerHeight",
  6407. "outerWidth",
  6408. "parent",
  6409. "parents",
  6410. "position",
  6411. "prepend",
  6412. "prependTo",
  6413. "prev",
  6414. "prevAll",
  6415. "prevUntil",
  6416. "promise",
  6417. "prop",
  6418. "pushStack",
  6419. "queue",
  6420. "ready",
  6421. "remove",
  6422. "removeAttr",
  6423. "removeClass",
  6424. "removeData",
  6425. "removeProp",
  6426. "replaceAll",
  6427. "replaceWith",
  6428. "resize",
  6429. "scroll",
  6430. "scrollLeft",
  6431. "scrollTop",
  6432. "select",
  6433. "show",
  6434. "siblings",
  6435. "slice",
  6436. "slideDown",
  6437. "slideToggle",
  6438. "slideUp",
  6439. "sort",
  6440. "splice",
  6441. "text",
  6442. "toArray",
  6443. "toggle",
  6444. "toggleClass",
  6445. "trigger",
  6446. "triggerHandler",
  6447. "unbind",
  6448. "width",
  6449. "wrap",
  6450. ];
  6451. for (const jQueryPropsName of jQueryProps) {
  6452. if (!(jQueryPropsName in target)) {
  6453. result = false;
  6454. /* console.log(jQueryPropsName); */
  6455. break;
  6456. }
  6457. else {
  6458. result = true;
  6459. }
  6460. }
  6461. }
  6462. return result;
  6463. }
  6464. isPhone(userAgent = navigator.userAgent) {
  6465. return Boolean(/(iPhone|iPad|iPod|iOS|Android|Mobile)/i.test(userAgent));
  6466. }
  6467. isSameChars(targetStr, coefficient = 1) {
  6468. if (typeof targetStr !== "string") {
  6469. throw new TypeError("参数 str 必须是 string 类型");
  6470. }
  6471. if (targetStr.length < 2) {
  6472. return false;
  6473. }
  6474. targetStr = targetStr.toLowerCase();
  6475. const targetCharMap = {};
  6476. let targetStrLength = 0;
  6477. for (const char of targetStr) {
  6478. if (Reflect.has(targetCharMap, char)) {
  6479. targetCharMap[char]++;
  6480. }
  6481. else {
  6482. targetCharMap[char] = 1;
  6483. }
  6484. targetStrLength++;
  6485. }
  6486. let result = false;
  6487. for (const char in targetCharMap) {
  6488. if (targetCharMap[char] / targetStrLength >= coefficient) {
  6489. result = true;
  6490. break;
  6491. }
  6492. }
  6493. return result;
  6494. }
  6495. isNotNull(...args) {
  6496. let UtilsContext = this;
  6497. return !UtilsContext.isNull.apply(this, args);
  6498. }
  6499. isNull(...args) {
  6500. let result = true;
  6501. let checkList = [...args];
  6502. for (const objItem of checkList) {
  6503. let itemResult = false;
  6504. if (objItem === null || objItem === undefined) {
  6505. itemResult = true;
  6506. }
  6507. else {
  6508. switch (typeof objItem) {
  6509. case "object":
  6510. if (typeof objItem[Symbol.iterator] === "function") {
  6511. /* 可迭代 */
  6512. itemResult = objItem.length === 0;
  6513. }
  6514. else {
  6515. itemResult = Object.keys(objItem).length === 0;
  6516. }
  6517. break;
  6518. case "number":
  6519. itemResult = objItem === 0;
  6520. break;
  6521. case "string":
  6522. itemResult =
  6523. objItem.trim() === "" ||
  6524. objItem === "null" ||
  6525. objItem === "undefined";
  6526. break;
  6527. case "boolean":
  6528. itemResult = !objItem;
  6529. break;
  6530. case "function":
  6531. let funcStr = objItem.toString().replace(/\s/g, "");
  6532. /* 排除()=>{}、(xxx="")=>{}、function(){}、function(xxx=""){} */
  6533. itemResult = Boolean(funcStr.match(/^\(.*?\)=>\{\}$|^function.*?\(.*?\)\{\}$/));
  6534. break;
  6535. }
  6536. }
  6537. result = result && itemResult;
  6538. }
  6539. return result;
  6540. }
  6541. isThemeDark() {
  6542. return this.windowApi.globalThis.matchMedia("(prefers-color-scheme: dark)")
  6543. .matches;
  6544. }
  6545. /**
  6546. * 判断元素是否在页面中可见
  6547. * @param element 需要检查的元素,可以是普通元素|数组形式的元素|通过querySelectorAll获取的元素数组
  6548. * @param inView
  6549. * + true 在窗口可视区域
  6550. * + false 不在窗口可视区域
  6551. * @returns
  6552. * + true 可见
  6553. * + false 不可见
  6554. * @example
  6555. * Utils.isVisible(document.documentElement)
  6556. * > true
  6557. */
  6558. isVisible(element, inView = false) {
  6559. let needCheckDomList = [];
  6560. if (element instanceof Array || element instanceof NodeList) {
  6561. element = element;
  6562. needCheckDomList = [...element];
  6563. }
  6564. else {
  6565. needCheckDomList = [element];
  6566. }
  6567. let result = true;
  6568. for (const domItem of needCheckDomList) {
  6569. let domDisplay = this.windowApi.window.getComputedStyle(domItem);
  6570. if (domDisplay.display === "none") {
  6571. result = false;
  6572. }
  6573. else {
  6574. let domClientRect = domItem.getBoundingClientRect();
  6575. if (inView) {
  6576. let viewportWidth = this.windowApi.window.innerWidth ||
  6577. this.windowApi.document.documentElement.clientWidth;
  6578. let viewportHeight = this.windowApi.window.innerHeight ||
  6579. this.windowApi.document.documentElement.clientHeight;
  6580. result = !(domClientRect.right < 0 ||
  6581. domClientRect.left > viewportWidth ||
  6582. domClientRect.bottom < 0 ||
  6583. domClientRect.top > viewportHeight);
  6584. }
  6585. else {
  6586. result = Boolean(domItem.getClientRects().length);
  6587. }
  6588. }
  6589. if (!result) {
  6590. /* 有一个不可见就退出循环 */
  6591. break;
  6592. }
  6593. }
  6594. return result;
  6595. }
  6596. isWebView_Via() {
  6597. let result = true;
  6598. let UtilsContext = this;
  6599. if (typeof this.windowApi.top.window.via === "object") {
  6600. for (const key in Object.values(this.windowApi.top.window.via)) {
  6601. if (Reflect.has(this.windowApi.top.window.via, key)) {
  6602. let objValueFunc = this.windowApi.top.window.via[key];
  6603. if (typeof objValueFunc === "function" &&
  6604. UtilsContext.isNativeFunc(objValueFunc)) {
  6605. result = true;
  6606. }
  6607. else {
  6608. result = false;
  6609. break;
  6610. }
  6611. }
  6612. }
  6613. }
  6614. else {
  6615. result = false;
  6616. }
  6617. return result;
  6618. }
  6619. isWebView_X() {
  6620. let result = true;
  6621. let UtilsContext = this;
  6622. if (typeof this.windowApi.top.window.mbrowser === "object") {
  6623. for (const key in Object.values(this.windowApi.top.window.mbrowser)) {
  6624. if (Reflect.has(this.windowApi.top.window.mbrowser, key)) {
  6625. let objValueFunc = this.windowApi.top.window.mbrowser[key];
  6626. if (typeof objValueFunc === "function" &&
  6627. UtilsContext.isNativeFunc(objValueFunc)) {
  6628. result = true;
  6629. }
  6630. else {
  6631. result = false;
  6632. break;
  6633. }
  6634. }
  6635. }
  6636. }
  6637. else {
  6638. result = false;
  6639. }
  6640. return result;
  6641. }
  6642. parseObjectToArray(target) {
  6643. if (typeof target !== "object") {
  6644. throw new Error("Utils.parseObjectToArray 参数 target 必须为 object 类型");
  6645. }
  6646. let result = [];
  6647. Object.keys(target).forEach(function (keyName) {
  6648. result = result.concat(target[keyName]);
  6649. });
  6650. return result;
  6651. }
  6652. /**
  6653. * 自动锁对象,用于循环判断运行的函数,在循环外new后使用,注意,如果函数内部存在异步操作,需要使用await
  6654. * @example
  6655. let lock = new Utils.LockFunction(()=>{console.log(1)}))
  6656. lock.run();
  6657. > 1
  6658. * @example
  6659. let lock = new Utils.LockFunction(()=>{console.log(1)}),true) -- 异步操作
  6660. await lock.run();
  6661. > 1
  6662. **/
  6663. LockFunction = LockFunction;
  6664. /**
  6665. * 日志对象
  6666. * @param _GM_info_ 油猴管理器的API GM_info,或者是一个对象,如{"script":{name:"Utils.Log"}}
  6667. * @example
  6668. let log = new Utils.Log(GM_info);
  6669. log.info("普通输出");
  6670. > 普通输出
  6671. log.success("成功输出");
  6672. > 成功输出
  6673. log.error("错误输出");
  6674. > 错误输出
  6675. log.warn("警告输出");
  6676. > 警告输出
  6677. log.tag = "自定义tag信息";
  6678. log.info("自定义info的颜色","#e0e0e0");
  6679. > 自定义info的颜色
  6680. log.config({
  6681. successColor: "#31dc02",
  6682. errorColor: "#e02d2d",
  6683. infoColor: "black",
  6684. })
  6685. log.success("颜色为#31dc02");
  6686. > 颜色为#31dc02
  6687. */
  6688. Log = Log;
  6689. mergeArrayToString(data, handleFunc) {
  6690. if (!(data instanceof Array)) {
  6691. throw new Error("Utils.mergeArrayToString 参数 data 必须为 Array 类型");
  6692. }
  6693. let content = "";
  6694. if (typeof handleFunc === "function") {
  6695. data.forEach((item) => {
  6696. content += handleFunc(item);
  6697. });
  6698. }
  6699. else if (typeof handleFunc === "string") {
  6700. data.forEach((item) => {
  6701. content += item[handleFunc];
  6702. });
  6703. }
  6704. else {
  6705. data.forEach((item) => {
  6706. Object.values(item)
  6707. .filter((item2) => typeof item2 === "string")
  6708. .forEach((item3) => {
  6709. content += item3;
  6710. });
  6711. });
  6712. }
  6713. return content;
  6714. }
  6715. mutationObserver(target, observer_config) {
  6716. let UtilsContext = this;
  6717. let default_obverser_config = {
  6718. /* 监听到元素有反馈,需执行的函数 */
  6719. callback: () => { },
  6720. config: {
  6721. /**
  6722. * + true 监听以 target 为根节点的整个子树。包括子树中所有节点的属性,而不仅仅是针对 target
  6723. * + false (默认) 不生效
  6724. */
  6725. subtree: undefined,
  6726. /**
  6727. * + true 监听 target 节点中发生的节点的新增与删除(同时,如果 subtree 为 true,会针对整个子树生效)
  6728. * + false (默认) 不生效
  6729. */
  6730. childList: undefined,
  6731. /**
  6732. * + true 观察所有监听的节点属性值的变化。默认值为 true,当声明了 attributeFilter 或 attributeOldValue
  6733. * + false (默认) 不生效
  6734. */
  6735. attributes: undefined,
  6736. /**
  6737. * 一个用于声明哪些属性名会被监听的数组。如果不声明该属性,所有属性的变化都将触发通知
  6738. */
  6739. attributeFilter: undefined,
  6740. /**
  6741. * + true 记录上一次被监听的节点的属性变化;可查阅 MutationObserver 中的 Monitoring attribute values 了解关于观察属性变化和属性值记录的详情
  6742. * + false (默认) 不生效
  6743. */
  6744. attributeOldValue: undefined,
  6745. /**
  6746. * + true 监听声明的 target 节点上所有字符的变化。默认值为 true,如果声明了 characterDataOldValue
  6747. * + false (默认) 不生效
  6748. */
  6749. characterData: undefined,
  6750. /**
  6751. * + true 记录前一个被监听的节点中发生的文本变化
  6752. * + false (默认) 不生效
  6753. */
  6754. characterDataOldValue: undefined,
  6755. },
  6756. immediate: false,
  6757. };
  6758. observer_config = UtilsContext.assign(default_obverser_config, observer_config);
  6759. let windowMutationObserver = this.windowApi.window.MutationObserver ||
  6760. this.windowApi.window.webkitMutationObserver ||
  6761. this.windowApi.window.MozMutationObserver;
  6762. // 观察者对象
  6763. let mutationObserver = new windowMutationObserver(function (mutations, observer) {
  6764. if (typeof observer_config.callback === "function") {
  6765. observer_config.callback(mutations, observer);
  6766. }
  6767. });
  6768. if (Array.isArray(target) || target instanceof NodeList) {
  6769. // 传入的是数组或者元素数组
  6770. target.forEach((item) => {
  6771. mutationObserver.observe(item, observer_config.config);
  6772. });
  6773. }
  6774. else if (UtilsContext.isJQuery(target)) {
  6775. /* 传入的参数是jQuery对象 */
  6776. target.each((index, item) => {
  6777. mutationObserver.observe(item, observer_config.config);
  6778. });
  6779. }
  6780. else {
  6781. mutationObserver.observe(target, observer_config.config);
  6782. }
  6783. if (observer_config.immediate) {
  6784. /* 主动触发一次 */
  6785. if (typeof observer_config.callback === "function") {
  6786. observer_config.callback([], mutationObserver);
  6787. }
  6788. }
  6789. return mutationObserver;
  6790. }
  6791. /**
  6792. * 使用观察器观察元素出现在视图内,出现的话触发回调
  6793. * @param target 目标元素
  6794. * @param callback 触发的回调
  6795. * @param options 观察器配置
  6796. * @example
  6797. * Utils.mutationVisible(document.querySelector("div.xxxx"),(entries,observer)=>{
  6798. * console.log("该元素出现在视图内");
  6799. * }))
  6800. */
  6801. mutationVisible(target, callback, options) {
  6802. if (typeof IntersectionObserver === "undefined") {
  6803. throw new TypeError("IntersectionObserver is not defined");
  6804. }
  6805. if (target == null) {
  6806. throw new TypeError("mutatuinVisible target is null");
  6807. }
  6808. let defaultOptions = {
  6809. root: null,
  6810. rootMargin: "0px 0px 0px 0px",
  6811. threshold: [0.01, 0.99],
  6812. };
  6813. defaultOptions = this.assign(defaultOptions, options || {});
  6814. let intersectionObserver = new IntersectionObserver((entries, observer) => {
  6815. if (entries[0].isIntersecting) {
  6816. if (typeof callback === "function") {
  6817. callback(entries, observer);
  6818. }
  6819. }
  6820. }, defaultOptions);
  6821. if (Array.isArray(target)) {
  6822. target.forEach((item) => {
  6823. intersectionObserver.observe(item);
  6824. });
  6825. }
  6826. else {
  6827. intersectionObserver.observe(target);
  6828. }
  6829. }
  6830. /**
  6831. * 去除全局window下的Utils,返回控制权
  6832. * @example
  6833. * let utils = Utils.noConflict();
  6834. * > ...
  6835. */
  6836. noConflict() {
  6837. if (this.windowApi.window.Utils) {
  6838. Reflect.deleteProperty(this.windowApi.window, "Utils");
  6839. }
  6840. this.windowApi.window.Utils = utils;
  6841. return utils;
  6842. }
  6843. noConflictFunc(needReleaseObject, needReleaseName, functionNameList = [], release = true) {
  6844. let UtilsContext = this;
  6845. if (typeof needReleaseObject !== "object") {
  6846. throw new Error("Utils.noConflictFunc 参数 needReleaseObject 必须为 object 类型");
  6847. }
  6848. if (typeof needReleaseName !== "string") {
  6849. throw new Error("Utils.noConflictFunc 参数 needReleaseName 必须为 string 类型");
  6850. }
  6851. if (!Array.isArray(functionNameList)) {
  6852. throw new Error("Utils.noConflictFunc 参数 functionNameList 必须为 Array 类型");
  6853. }
  6854. let needReleaseKey = "__" + needReleaseName;
  6855. /**
  6856. * 释放所有
  6857. */
  6858. function releaseAll() {
  6859. if (typeof UtilsContext.windowApi.window[needReleaseKey] !==
  6860. "undefined") {
  6861. /* 已存在 */
  6862. return;
  6863. }
  6864. UtilsContext.windowApi.window[needReleaseKey] =
  6865. UtilsContext.deepClone(needReleaseObject);
  6866. Object.values(needReleaseObject).forEach((value) => {
  6867. if (typeof value === "function") {
  6868. needReleaseObject[value.name] = () => { };
  6869. }
  6870. });
  6871. }
  6872. /**
  6873. * 释放单个
  6874. */
  6875. function releaseOne() {
  6876. Array.from(functionNameList).forEach((item) => {
  6877. Object.values(needReleaseObject).forEach((value) => {
  6878. if (typeof value === "function") {
  6879. if (typeof UtilsContext.windowApi.window[needReleaseKey] ===
  6880. "undefined") {
  6881. UtilsContext.windowApi.window[needReleaseKey] = {};
  6882. }
  6883. if (item === value.name) {
  6884. UtilsContext.windowApi.window[needReleaseKey][value.name] = needReleaseObject[value.name];
  6885. needReleaseObject[value.name] = () => { };
  6886. }
  6887. }
  6888. });
  6889. });
  6890. }
  6891. /**
  6892. * 恢复所有
  6893. */
  6894. function recoveryAll() {
  6895. if (typeof UtilsContext.windowApi.window[needReleaseKey] ===
  6896. "undefined") {
  6897. /* 未存在 */
  6898. return;
  6899. }
  6900. Object.assign(needReleaseObject, UtilsContext.windowApi.window[needReleaseKey]);
  6901. Reflect.deleteProperty(UtilsContext.windowApi.window, "needReleaseKey");
  6902. }
  6903. /**
  6904. * 恢复单个
  6905. */
  6906. function recoveryOne() {
  6907. if (typeof UtilsContext.windowApi.window[needReleaseKey] ===
  6908. "undefined") {
  6909. /* 未存在 */
  6910. return;
  6911. }
  6912. Array.from(functionNameList).forEach((item) => {
  6913. if (UtilsContext.windowApi.window[needReleaseKey][item]) {
  6914. needReleaseObject[item] = UtilsContext.windowApi.window[needReleaseKey][item];
  6915. Reflect.deleteProperty(UtilsContext.windowApi.window[needReleaseKey], item);
  6916. if (Object.keys(UtilsContext.windowApi.window[needReleaseKey])
  6917. .length === 0) {
  6918. Reflect.deleteProperty(window, needReleaseKey);
  6919. }
  6920. }
  6921. });
  6922. }
  6923. if (release) {
  6924. /* 释放 */
  6925. if (functionNameList.length === 0) {
  6926. releaseAll();
  6927. }
  6928. else {
  6929. /* 对单个进行操作 */
  6930. releaseOne();
  6931. }
  6932. }
  6933. else {
  6934. /* 恢复 */
  6935. if (functionNameList.length === 0) {
  6936. recoveryAll();
  6937. }
  6938. else {
  6939. /* 对单个进行操作 */
  6940. recoveryOne();
  6941. }
  6942. }
  6943. }
  6944. parseBase64ToBlob(dataUri) {
  6945. if (typeof dataUri !== "string") {
  6946. throw new Error("Utils.parseBase64ToBlob 参数 dataUri 必须为 string 类型");
  6947. }
  6948. let dataUriSplit = dataUri.split(","), dataUriMime = dataUriSplit[0].match(/:(.*?);/)[1], dataUriBase64Str = atob(dataUriSplit[1]), dataUriLength = dataUriBase64Str.length, u8arr = new Uint8Array(dataUriLength);
  6949. while (dataUriLength--) {
  6950. u8arr[dataUriLength] = dataUriBase64Str.charCodeAt(dataUriLength);
  6951. }
  6952. return new Blob([u8arr], {
  6953. type: dataUriMime,
  6954. });
  6955. }
  6956. parseBase64ToFile(dataUri, fileName = "example") {
  6957. if (typeof dataUri !== "string") {
  6958. throw new Error("Utils.parseBase64ToFile 参数 dataUri 必须为 string 类型");
  6959. }
  6960. if (typeof fileName !== "string") {
  6961. throw new Error("Utils.parseBase64ToFile 参数 fileName 必须为 string 类型");
  6962. }
  6963. let dataUriSplit = dataUri.split(","), dataUriMime = dataUriSplit[0].match(/:(.*?);/)[1], dataUriBase64Str = atob(dataUriSplit[1]), dataUriLength = dataUriBase64Str.length, u8arr = new Uint8Array(dataUriLength);
  6964. while (dataUriLength--) {
  6965. u8arr[dataUriLength] = dataUriBase64Str.charCodeAt(dataUriLength);
  6966. }
  6967. return new File([u8arr], fileName, {
  6968. type: dataUriMime,
  6969. });
  6970. }
  6971. parseInt(matchList = [], defaultValue = 0) {
  6972. if (matchList == null) {
  6973. return parseInt(defaultValue.toString());
  6974. }
  6975. let parseValue = parseInt(matchList[matchList.length - 1]);
  6976. if (isNaN(parseValue)) {
  6977. parseValue = parseInt(defaultValue.toString());
  6978. }
  6979. return parseValue;
  6980. }
  6981. async parseBlobToFile(blobUrl, fileName = "example") {
  6982. return new Promise((resolve, reject) => {
  6983. fetch(blobUrl)
  6984. .then((response) => response.blob())
  6985. .then((blob) => {
  6986. const file = new File([blob], fileName, { type: blob.type });
  6987. resolve(file);
  6988. })
  6989. .catch((error) => {
  6990. console.error("Error:", error);
  6991. reject(error);
  6992. });
  6993. });
  6994. }
  6995. parseCDATA(text = "") {
  6996. let result = "";
  6997. let cdataRegexp = /<\!\[CDATA\[([\s\S]*)\]\]>/;
  6998. let cdataMatch = cdataRegexp.exec(text.trim());
  6999. if (cdataMatch && cdataMatch.length > 1) {
  7000. result = cdataMatch[cdataMatch.length - 1];
  7001. }
  7002. return result;
  7003. }
  7004. async parseFileToBase64(fileObj) {
  7005. let reader = new FileReader();
  7006. reader.readAsDataURL(fileObj);
  7007. return new Promise((resolve) => {
  7008. reader.onload = function (event) {
  7009. resolve(event.target.result);
  7010. };
  7011. });
  7012. }
  7013. parseFromString(text, mimeType = "text/html") {
  7014. let parser = new DOMParser();
  7015. return parser.parseFromString(text, mimeType);
  7016. }
  7017. parseStringToRegExpString(text) {
  7018. if (typeof text !== "string") {
  7019. throw new TypeError("string必须是字符串");
  7020. }
  7021. let regString = text.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
  7022. return regString;
  7023. }
  7024. preventEvent(element, eventNameList = [], capture) {
  7025. function stopEvent(event) {
  7026. /* 阻止事件的默认行为发生。例如,当点击一个链接时,浏览器会默认打开链接的URL */
  7027. event?.preventDefault();
  7028. /* 停止事件的传播,阻止它继续向更上层的元素冒泡,事件将不会再传播给其他的元素 */
  7029. event?.stopPropagation();
  7030. /* 阻止事件传播,并且还能阻止元素上的其他事件处理程序被触发 */
  7031. event?.stopImmediatePropagation();
  7032. return false;
  7033. }
  7034. if (arguments.length === 1) {
  7035. /* 直接阻止事件 */
  7036. return stopEvent(arguments[0]);
  7037. }
  7038. else {
  7039. /* 添加对应的事件来阻止触发 */
  7040. if (typeof eventNameList === "string") {
  7041. eventNameList = [eventNameList];
  7042. }
  7043. eventNameList.forEach((eventName) => {
  7044. element.addEventListener(eventName, stopEvent, {
  7045. capture: Boolean(capture),
  7046. });
  7047. });
  7048. }
  7049. }
  7050. /**
  7051. * 在canvas元素节点上绘制进度圆圈
  7052. * @example
  7053. let progress = new Utils.Process({canvasNode:document.querySelector("canvas")});
  7054. progress.draw();
  7055. * **/
  7056. Progress = Progress;
  7057. registerTrustClickEvent(isTrustValue = true, filter) {
  7058. function trustEvent(event) {
  7059. return new Proxy(event, {
  7060. get: function (target, property) {
  7061. if (property === "isTrusted") {
  7062. return isTrustValue;
  7063. }
  7064. else {
  7065. return Reflect.get(target, property);
  7066. }
  7067. },
  7068. });
  7069. }
  7070. if (filter == null) {
  7071. filter = function (typeName) {
  7072. return typeName === "click";
  7073. };
  7074. }
  7075. const originalListener = EventTarget.prototype.addEventListener;
  7076. EventTarget.prototype.addEventListener = function (...args) {
  7077. let type = args[0];
  7078. let callback = args[1];
  7079. // @ts-ignore
  7080. args[2];
  7081. if (filter(type)) {
  7082. if (typeof callback === "function") {
  7083. args[1] = function (event) {
  7084. callback.call(this, trustEvent(event));
  7085. };
  7086. }
  7087. else if (typeof callback === "object" &&
  7088. "handleEvent" in callback) {
  7089. let oldHandleEvent = callback["handleEvent"];
  7090. args[1]["handleEvent"] = function (event) {
  7091. if (event == null) {
  7092. return;
  7093. }
  7094. try {
  7095. /* Proxy对象使用instanceof会报错 */
  7096. event instanceof Proxy;
  7097. oldHandleEvent.call(this, trustEvent(event));
  7098. }
  7099. catch (error) {
  7100. // @ts-ignore
  7101. event["isTrusted"] = isTrustValue;
  7102. }
  7103. };
  7104. }
  7105. }
  7106. return originalListener.apply(this, args);
  7107. };
  7108. }
  7109. reverseNumber(num) {
  7110. let reversedNum = 0;
  7111. let isNegative = false;
  7112. if (num < 0) {
  7113. isNegative = true;
  7114. num = Math.abs(num);
  7115. }
  7116. while (num > 0) {
  7117. reversedNum = reversedNum * 10 + (num % 10);
  7118. num = Math.floor(num / 10);
  7119. }
  7120. return isNegative ? -reversedNum : reversedNum;
  7121. }
  7122. selectElementText(element, childTextNode, startIndex, endIndex) {
  7123. let range = this.windowApi.document.createRange();
  7124. range.selectNodeContents(element);
  7125. if (childTextNode) {
  7126. if (childTextNode.nodeType !== Node.TEXT_NODE) {
  7127. throw new TypeError("childTextNode必须是#text元素");
  7128. }
  7129. if (startIndex != null && endIndex != null) {
  7130. range.setStart(childTextNode, startIndex);
  7131. range.setEnd(childTextNode, endIndex);
  7132. }
  7133. }
  7134. let selection = this.windowApi.globalThis.getSelection();
  7135. if (selection) {
  7136. selection.removeAllRanges();
  7137. selection.addRange(range);
  7138. }
  7139. }
  7140. setClip(data, info = {
  7141. type: "text",
  7142. mimetype: "text/plain",
  7143. }) {
  7144. if (typeof data === "object") {
  7145. if (data instanceof Element) {
  7146. data = data.outerHTML;
  7147. }
  7148. else {
  7149. data = JSON.stringify(data);
  7150. }
  7151. }
  7152. else if (typeof data !== "string") {
  7153. data = data.toString();
  7154. }
  7155. let textType = typeof info === "object" ? info.type : info;
  7156. if (textType.includes("html")) {
  7157. textType = "text/html";
  7158. }
  7159. else {
  7160. textType = "text/plain";
  7161. }
  7162. let UtilsContext = this;
  7163. class UtilsClipboard {
  7164. #resolve;
  7165. #copyData;
  7166. #copyDataType;
  7167. constructor(resolve, copyData, copyDataType) {
  7168. this.#resolve = resolve;
  7169. this.#copyData = copyData;
  7170. this.#copyDataType = copyDataType;
  7171. }
  7172. async init() {
  7173. let copyStatus = false;
  7174. // @ts-ignore
  7175. await this.requestClipboardPermission();
  7176. if (this.hasClipboard() &&
  7177. (this.hasClipboardWrite() || this.hasClipboardWriteText())) {
  7178. try {
  7179. copyStatus = await this.copyDataByClipboard();
  7180. }
  7181. catch (error) {
  7182. console.error("复制失败,使用第二种方式,error👉", error);
  7183. copyStatus = this.copyTextByTextArea();
  7184. }
  7185. }
  7186. else {
  7187. copyStatus = this.copyTextByTextArea();
  7188. }
  7189. this.#resolve(copyStatus);
  7190. this.destroy();
  7191. }
  7192. destroy() {
  7193. // @ts-ignore
  7194. this.#resolve = null;
  7195. // @ts-ignore
  7196. this.#copyData = null;
  7197. // @ts-ignore
  7198. this.#copyDataType = null;
  7199. }
  7200. isText() {
  7201. return this.#copyDataType.includes("text");
  7202. }
  7203. hasClipboard() {
  7204. return navigator?.clipboard != null;
  7205. }
  7206. hasClipboardWrite() {
  7207. return navigator?.clipboard?.write != null;
  7208. }
  7209. hasClipboardWriteText() {
  7210. return navigator?.clipboard?.writeText != null;
  7211. }
  7212. /**
  7213. * 使用textarea和document.execCommand("copy")来复制文字
  7214. */
  7215. copyTextByTextArea() {
  7216. try {
  7217. let copyElement = UtilsContext.windowApi.document.createElement("textarea");
  7218. copyElement.value = this.#copyData;
  7219. copyElement.setAttribute("type", "text");
  7220. copyElement.setAttribute("style", "opacity:0;position:absolute;");
  7221. copyElement.setAttribute("readonly", "readonly");
  7222. UtilsContext.windowApi.document.body.appendChild(copyElement);
  7223. copyElement.select();
  7224. UtilsContext.windowApi.document.execCommand("copy");
  7225. UtilsContext.windowApi.document.body.removeChild(copyElement);
  7226. return true;
  7227. }
  7228. catch (error) {
  7229. console.error("复制失败,error👉", error);
  7230. return false;
  7231. }
  7232. }
  7233. /**
  7234. * 申请剪贴板权限
  7235. */
  7236. requestClipboardPermission() {
  7237. return new Promise((resolve, reject) => {
  7238. if (navigator.permissions && navigator.permissions.query) {
  7239. navigator.permissions
  7240. .query({
  7241. // @ts-ignore
  7242. name: "clipboard-write",
  7243. })
  7244. .then((permissionStatus) => {
  7245. resolve(true);
  7246. })
  7247. .catch((error) => {
  7248. console.error([
  7249. "申请剪贴板权限失败,尝试直接写入👉",
  7250. error.message ?? error.name ?? error.stack,
  7251. ]);
  7252. resolve(false);
  7253. });
  7254. }
  7255. else {
  7256. resolve(false);
  7257. }
  7258. });
  7259. }
  7260. /**
  7261. * 使用clipboard直接写入数据到剪贴板
  7262. */
  7263. copyDataByClipboard() {
  7264. return new Promise((resolve, reject) => {
  7265. if (this.isText()) {
  7266. /* 只复制文字 */
  7267. navigator.clipboard
  7268. .writeText(this.#copyData)
  7269. .then(() => {
  7270. resolve(true);
  7271. })
  7272. .catch((error) => {
  7273. reject(error);
  7274. });
  7275. }
  7276. else {
  7277. /* 可复制对象 */
  7278. let textBlob = new Blob([this.#copyData], {
  7279. type: this.#copyDataType,
  7280. });
  7281. navigator.clipboard
  7282. .write([
  7283. new ClipboardItem({
  7284. [this.#copyDataType]: textBlob,
  7285. }),
  7286. ])
  7287. .then(() => {
  7288. resolve(true);
  7289. })
  7290. .catch((error) => {
  7291. reject(error);
  7292. });
  7293. }
  7294. });
  7295. }
  7296. }
  7297. return new Promise((resolve) => {
  7298. const utilsClipboard = new UtilsClipboard(resolve, data, textType);
  7299. if (UtilsContext.windowApi.document.hasFocus()) {
  7300. utilsClipboard.init();
  7301. }
  7302. else {
  7303. UtilsContext.windowApi.window.addEventListener("focus", () => {
  7304. utilsClipboard.init();
  7305. }, { once: true });
  7306. }
  7307. });
  7308. }
  7309. setTimeout(callback, delayTime = 0) {
  7310. let UtilsContext = this;
  7311. if (typeof callback !== "function" && typeof callback !== "string") {
  7312. throw new TypeError("Utils.setTimeout 参数 callback 必须为 function|string 类型");
  7313. }
  7314. if (typeof delayTime !== "number") {
  7315. throw new TypeError("Utils.setTimeout 参数 delayTime 必须为 number 类型");
  7316. }
  7317. return new Promise((resolve) => {
  7318. setTimeout(() => {
  7319. resolve(UtilsContext.tryCatch().run(callback));
  7320. }, delayTime);
  7321. });
  7322. }
  7323. sleep(delayTime = 0) {
  7324. if (typeof delayTime !== "number") {
  7325. throw new Error("Utils.sleep 参数 delayTime 必须为 number 类型");
  7326. }
  7327. return new Promise((resolve) => {
  7328. setTimeout(() => {
  7329. resolve(undefined);
  7330. }, delayTime);
  7331. });
  7332. }
  7333. dragSlider(selector, offsetX = this.windowApi.window.innerWidth) {
  7334. let UtilsContext = this;
  7335. function initMouseEvent(eventName, offSetX, offSetY) {
  7336. // @ts-ignore
  7337. let win = typeof unsafeWindow === "undefined" ? globalThis : unsafeWindow;
  7338. let mouseEvent = UtilsContext.windowApi.document.createEvent("MouseEvents");
  7339. mouseEvent.initMouseEvent(eventName, true, true, win, 0, offSetX, offSetY, offSetX, offSetY, false, false, false, false, 0, null);
  7340. return mouseEvent;
  7341. }
  7342. let sliderElement = typeof selector === "string"
  7343. ? this.windowApi.document.querySelector(selector)
  7344. : selector;
  7345. if (!(sliderElement instanceof Node) ||
  7346. !(sliderElement instanceof Element)) {
  7347. throw new Error("Utils.dragSlider 参数selector 必须为Node/Element类型");
  7348. }
  7349. let rect = sliderElement.getBoundingClientRect(), x0 = rect.x || rect.left, y0 = rect.y || rect.top, x1 = x0 + offsetX, y1 = y0;
  7350. sliderElement.dispatchEvent(initMouseEvent("mousedown", x0, y0));
  7351. sliderElement.dispatchEvent(initMouseEvent("mousemove", x1, y1));
  7352. sliderElement.dispatchEvent(initMouseEvent("mouseleave", x1, y1));
  7353. sliderElement.dispatchEvent(initMouseEvent("mouseout", x1, y1));
  7354. }
  7355. enterFullScreen(element = this.windowApi.document.documentElement, options) {
  7356. try {
  7357. if (element.requestFullscreen) {
  7358. element.requestFullscreen(options);
  7359. }
  7360. else if (element.webkitRequestFullScreen) {
  7361. element.webkitRequestFullScreen();
  7362. }
  7363. else if (element.mozRequestFullScreen) {
  7364. element.mozRequestFullScreen();
  7365. }
  7366. else if (element.msRequestFullscreen) {
  7367. element.msRequestFullscreen();
  7368. }
  7369. else {
  7370. throw new TypeError("该浏览器不支持全屏API");
  7371. }
  7372. }
  7373. catch (err) {
  7374. console.error(err);
  7375. }
  7376. }
  7377. exitFullScreen(element = this.windowApi.document.documentElement) {
  7378. if (this.windowApi.document.exitFullscreen) {
  7379. return this.windowApi.document.exitFullscreen();
  7380. }
  7381. else if (this.windowApi.document.msExitFullscreen) {
  7382. return this.windowApi.document.msExitFullscreen();
  7383. }
  7384. else if (this.windowApi.document.mozCancelFullScreen) {
  7385. return this.windowApi.document.mozCancelFullScreen();
  7386. }
  7387. else if (this.windowApi.document.webkitCancelFullScreen) {
  7388. return this.windowApi.document.webkitCancelFullScreen();
  7389. }
  7390. else {
  7391. return new Promise((resolve, reject) => {
  7392. reject(new TypeError("该浏览器不支持全屏API"));
  7393. });
  7394. }
  7395. }
  7396. sortListByProperty(data, getPropertyValueFunc, sortByDesc = true) {
  7397. let UtilsContext = this;
  7398. if (typeof getPropertyValueFunc !== "function" &&
  7399. typeof getPropertyValueFunc !== "string") {
  7400. throw new Error("Utils.sortListByProperty 参数 getPropertyValueFunc 必须为 function|string 类型");
  7401. }
  7402. if (typeof sortByDesc !== "boolean") {
  7403. throw new Error("Utils.sortListByProperty 参数 sortByDesc 必须为 boolean 类型");
  7404. }
  7405. let getObjValue = function (obj) {
  7406. return typeof getPropertyValueFunc === "string"
  7407. ? obj[getPropertyValueFunc]
  7408. : getPropertyValueFunc(obj);
  7409. };
  7410. /**
  7411. * 排序方法
  7412. * @param {any} after_obj
  7413. * @param {any} before_obj
  7414. * @returns
  7415. */
  7416. let sortFunc = function (after_obj, before_obj) {
  7417. let beforeValue = getObjValue(before_obj); /* 前 */
  7418. let afterValue = getObjValue(after_obj); /* 后 */
  7419. if (sortByDesc) {
  7420. if (afterValue > beforeValue) {
  7421. return -1;
  7422. }
  7423. else if (afterValue < beforeValue) {
  7424. return 1;
  7425. }
  7426. else {
  7427. return 0;
  7428. }
  7429. }
  7430. else {
  7431. if (afterValue < beforeValue) {
  7432. return -1;
  7433. }
  7434. else if (afterValue > beforeValue) {
  7435. return 1;
  7436. }
  7437. else {
  7438. return 0;
  7439. }
  7440. }
  7441. };
  7442. /**
  7443. * 排序元素方法
  7444. * @param nodeList 元素列表
  7445. * @param getNodeListFunc 获取元素列表的函数
  7446. */
  7447. let sortNodeFunc = function (nodeList, getNodeListFunc) {
  7448. let nodeListLength = nodeList.length;
  7449. for (let i = 0; i < nodeListLength - 1; i++) {
  7450. for (let j = 0; j < nodeListLength - 1 - i; j++) {
  7451. let beforeNode = nodeList[j];
  7452. let afterNode = nodeList[j + 1];
  7453. let beforeValue = getObjValue(beforeNode); /* 前 */
  7454. let afterValue = getObjValue(afterNode); /* 后 */
  7455. if ((sortByDesc == true && beforeValue < afterValue) ||
  7456. (sortByDesc == false && beforeValue > afterValue)) {
  7457. /* 升序/降序 */
  7458. /* 相邻元素两两对比 */
  7459. let temp = beforeNode.nextElementSibling;
  7460. afterNode.after(beforeNode);
  7461. if (temp == null) {
  7462. /* 如果为空,那么是最后一个元素,使用append */
  7463. temp.parentNode.appendChild(afterNode);
  7464. }
  7465. else {
  7466. /* 不为空,使用before */
  7467. temp.before(afterNode);
  7468. }
  7469. nodeList = getNodeListFunc();
  7470. }
  7471. }
  7472. }
  7473. };
  7474. let result = data;
  7475. let getDataFunc = null;
  7476. if (data instanceof Function) {
  7477. getDataFunc = data;
  7478. data = data();
  7479. }
  7480. if (Array.isArray(data)) {
  7481. data.sort(sortFunc);
  7482. }
  7483. else if (data instanceof NodeList ||
  7484. UtilsContext.isJQuery(data)) {
  7485. sortNodeFunc(data, getDataFunc);
  7486. result = getDataFunc();
  7487. }
  7488. else {
  7489. throw new Error("Utils.sortListByProperty 参数 data 必须为 Array|NodeList|jQuery 类型");
  7490. }
  7491. return result;
  7492. }
  7493. stringToRegular(targetString, flags = "ig") {
  7494. let reg;
  7495. // @ts-ignore
  7496. flags = flags.toLowerCase();
  7497. if (typeof targetString === "string") {
  7498. reg = new RegExp(targetString.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"), flags);
  7499. }
  7500. else if (targetString instanceof RegExp) {
  7501. reg = targetString;
  7502. }
  7503. else {
  7504. throw new Error("Utils.stringToRegular 参数targetString必须是string|Regexp类型");
  7505. }
  7506. return reg;
  7507. }
  7508. stringTitleToUpperCase(targetString, otherStrToLowerCase = false) {
  7509. let newTargetString = targetString.slice(0, 1).toUpperCase();
  7510. if (otherStrToLowerCase) {
  7511. newTargetString = newTargetString + targetString.slice(1).toLowerCase();
  7512. }
  7513. else {
  7514. newTargetString = newTargetString + targetString.slice(1);
  7515. }
  7516. return newTargetString;
  7517. }
  7518. startsWith(target, searchString, position = 0) {
  7519. let UtilsContext = this;
  7520. if (position > target.length) {
  7521. /* 超出目标字符串的长度 */
  7522. return false;
  7523. }
  7524. if (position !== 0) {
  7525. target = target.slice(position, target.length);
  7526. }
  7527. let searchStringRegexp = searchString;
  7528. if (typeof searchString === "string") {
  7529. searchStringRegexp = new RegExp(`^${searchString}`);
  7530. }
  7531. else if (Array.isArray(searchString)) {
  7532. let flag = false;
  7533. for (const searcStr of searchString) {
  7534. if (!UtilsContext.startsWith(target, searcStr, position)) {
  7535. flag = true;
  7536. break;
  7537. }
  7538. }
  7539. return flag;
  7540. }
  7541. return Boolean(target.match(searchStringRegexp));
  7542. }
  7543. stringTitleToLowerCase(targetString, otherStrToUpperCase = false) {
  7544. let newTargetString = targetString.slice(0, 1).toLowerCase();
  7545. if (otherStrToUpperCase) {
  7546. newTargetString = newTargetString + targetString.slice(1).toUpperCase();
  7547. }
  7548. else {
  7549. newTargetString = newTargetString + targetString.slice(1);
  7550. }
  7551. return newTargetString;
  7552. }
  7553. toJSON(data, errorCallBack) {
  7554. let UtilsContext = this;
  7555. let result = {};
  7556. if (typeof data === "object") {
  7557. return data;
  7558. }
  7559. UtilsContext.tryCatch()
  7560. .config({ log: false })
  7561. .error((error) => {
  7562. UtilsContext.tryCatch()
  7563. .error(() => {
  7564. try {
  7565. result = UtilsContext.windowApi.window.eval("(" + data + ")");
  7566. }
  7567. catch (error2) {
  7568. if (typeof errorCallBack === "function") {
  7569. errorCallBack(error2);
  7570. }
  7571. }
  7572. })
  7573. .run(() => {
  7574. if (data &&
  7575. /^[\],:{}\s]*$/.test(data
  7576. .replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
  7577. .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
  7578. .replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
  7579. result = new Function("return " + data)();
  7580. }
  7581. else {
  7582. if (typeof errorCallBack === "function") {
  7583. errorCallBack(new Error("target is not a JSON"));
  7584. }
  7585. }
  7586. });
  7587. })
  7588. .run(() => {
  7589. data = data.trim();
  7590. result = JSON.parse(data);
  7591. });
  7592. return result;
  7593. }
  7594. toSearchParamsStr(obj, addPrefix) {
  7595. let UtilsContext = this;
  7596. let searhParamsStr = "";
  7597. if (Array.isArray(obj)) {
  7598. obj.forEach((item) => {
  7599. if (searhParamsStr === "") {
  7600. searhParamsStr += UtilsContext.toSearchParamsStr(item);
  7601. }
  7602. else {
  7603. searhParamsStr += "&" + UtilsContext.toSearchParamsStr(item);
  7604. }
  7605. });
  7606. }
  7607. else {
  7608. searhParamsStr = new URLSearchParams(Object.entries(obj)).toString();
  7609. }
  7610. if (addPrefix && !searhParamsStr.startsWith("?")) {
  7611. searhParamsStr = "?" + searhParamsStr;
  7612. }
  7613. return searhParamsStr;
  7614. }
  7615. /**
  7616. * 将UrlSearchParams格式的字符串转为对象
  7617. */
  7618. searchParamStrToObj(searhParamsStr) {
  7619. if (typeof searhParamsStr !== "string") {
  7620. // @ts-ignore
  7621. return {};
  7622. }
  7623. // @ts-ignore
  7624. return Object.fromEntries(new URLSearchParams(searhParamsStr));
  7625. }
  7626. /**
  7627. * 提供一个封装了 try-catch 的函数,可以执行传入的函数并捕获其可能抛出的错误,并通过传入的错误处理函数进行处理。
  7628. * @example
  7629. * Utils.tryCatch().error().run(()=>{console.log(1)});
  7630. * > 1
  7631. * @example
  7632. * Utils.tryCatch().config({log:true}).error((error)=>{console.log(error)}).run(()=>{throw new Error('测试错误')});
  7633. * > ()=>{throw new Error('测试错误')}出现错误
  7634. */
  7635. tryCatch = TryCatch;
  7636. uniqueArray(uniqueArrayData = [], compareArrayData, compareFun = (item, item2) => {
  7637. return item === item2;
  7638. }) {
  7639. if (typeof compareArrayData === "function") {
  7640. const compareFn = compareArrayData;
  7641. const seen = new Set();
  7642. const result = [];
  7643. for (const item of uniqueArrayData) {
  7644. // 使用compareFn函数来获取当前对象的唯一标识
  7645. const identfier = compareFn(item);
  7646. // 如果Set中还没有这个标识,则添加到结果数组中,并将其标识存入Set
  7647. if (!seen.has(identfier)) {
  7648. seen.add(identfier);
  7649. result.push(item);
  7650. }
  7651. }
  7652. return result;
  7653. }
  7654. else {
  7655. return Array.from(uniqueArrayData).filter((item) => !Array.from(compareArrayData).some(function (item2) {
  7656. return compareFun(item, item2);
  7657. }));
  7658. }
  7659. }
  7660. waitArrayLoopToEnd(data, handleFunc) {
  7661. let UtilsContext = this;
  7662. if (typeof handleFunc !== "function" && typeof handleFunc !== "string") {
  7663. throw new Error("Utils.waitArrayLoopToEnd 参数 handleDataFunction 必须为 function|string 类型");
  7664. }
  7665. return Promise.all(Array.from(data).map(async (item, index) => {
  7666. await UtilsContext.tryCatch(index, item).run(handleFunc);
  7667. }));
  7668. }
  7669. wait(checkFn, timeout, parent) {
  7670. const UtilsContext = this;
  7671. let __timeout__ = typeof timeout === "number" ? timeout : 0;
  7672. return new Promise((resolve) => {
  7673. let observer = UtilsContext.mutationObserver(parent || UtilsContext.windowApi.document, {
  7674. config: {
  7675. subtree: true,
  7676. childList: true,
  7677. attributes: true,
  7678. },
  7679. immediate: true,
  7680. callback(mutations, __observer__) {
  7681. let result = checkFn();
  7682. if (result.success) {
  7683. // 取消观察器
  7684. if (typeof __observer__?.disconnect === "function") {
  7685. __observer__.disconnect();
  7686. }
  7687. resolve(result.data);
  7688. }
  7689. },
  7690. });
  7691. if (__timeout__ > 0) {
  7692. setTimeout(() => {
  7693. // 取消观察器
  7694. if (typeof observer?.disconnect === "function") {
  7695. observer.disconnect();
  7696. }
  7697. resolve(null);
  7698. }, __timeout__);
  7699. }
  7700. });
  7701. }
  7702. waitNode(...args) {
  7703. // 过滤掉undefined
  7704. args = args.filter((arg) => arg !== undefined);
  7705. let UtilsContext = this;
  7706. // 选择器
  7707. let selector = args[0];
  7708. // 父元素(监听的元素)
  7709. let parent = UtilsContext.windowApi.document;
  7710. // 超时时间
  7711. let timeout = 0;
  7712. if (typeof args[0] !== "string" &&
  7713. !Array.isArray(args[0]) &&
  7714. typeof args[0] !== "function") {
  7715. throw new TypeError("Utils.waitNode 第一个参数必须是string|string[]|Function");
  7716. }
  7717. if (args.length === 1) ;
  7718. else if (args.length === 2) {
  7719. let secondParam = args[1];
  7720. if (typeof secondParam === "number") {
  7721. // "div",10000
  7722. timeout = secondParam;
  7723. }
  7724. else if (typeof secondParam === "object" &&
  7725. secondParam instanceof Node) {
  7726. // "div",document
  7727. parent = secondParam;
  7728. }
  7729. else {
  7730. throw new TypeError("Utils.waitNode 第二个参数必须是number|Node");
  7731. }
  7732. }
  7733. else if (args.length === 3) {
  7734. // "div",document,10000
  7735. // 第二个参数,parent
  7736. let secondParam = args[1];
  7737. // 第三个参数,timeout
  7738. let thirdParam = args[2];
  7739. if (typeof secondParam === "object" && secondParam instanceof Node) {
  7740. parent = secondParam;
  7741. if (typeof thirdParam === "number") {
  7742. timeout = thirdParam;
  7743. }
  7744. else {
  7745. throw new TypeError("Utils.waitNode 第三个参数必须是number");
  7746. }
  7747. }
  7748. else {
  7749. throw new TypeError("Utils.waitNode 第二个参数必须是Node");
  7750. }
  7751. }
  7752. else {
  7753. throw new TypeError("Utils.waitNode 参数个数错误");
  7754. }
  7755. function getNode() {
  7756. if (Array.isArray(selector)) {
  7757. let result = [];
  7758. for (let index = 0; index < selector.length; index++) {
  7759. let node = parent.querySelector(selector[index]);
  7760. if (node) {
  7761. result.push(node);
  7762. }
  7763. }
  7764. if (result.length === selector.length) {
  7765. return result;
  7766. }
  7767. }
  7768. else if (typeof selector === "function") {
  7769. return selector();
  7770. }
  7771. else {
  7772. return parent.querySelector(selector);
  7773. }
  7774. }
  7775. return UtilsContext.wait(() => {
  7776. let node = getNode();
  7777. if (node) {
  7778. return {
  7779. success: true,
  7780. data: node,
  7781. };
  7782. }
  7783. else {
  7784. return {
  7785. success: false,
  7786. data: node,
  7787. };
  7788. }
  7789. }, timeout, parent);
  7790. }
  7791. waitAnyNode(...args) {
  7792. // 过滤掉undefined
  7793. args = args.filter((arg) => arg !== undefined);
  7794. let UtilsContext = this;
  7795. // 选择器
  7796. let selectorList = args[0];
  7797. // 父元素(监听的元素)
  7798. let parent = UtilsContext.windowApi.document;
  7799. // 超时时间
  7800. let timeout = 0;
  7801. if (typeof args[0] !== "object" && !Array.isArray(args[0])) {
  7802. throw new TypeError("Utils.waitAnyNode 第一个参数必须是string[]");
  7803. }
  7804. if (args.length === 1) ;
  7805. else if (args.length === 2) {
  7806. let secondParam = args[1];
  7807. if (typeof secondParam === "number") {
  7808. // "div",10000
  7809. timeout = secondParam;
  7810. }
  7811. else if (typeof secondParam === "object" &&
  7812. secondParam instanceof Node) {
  7813. // "div",document
  7814. parent = secondParam;
  7815. }
  7816. else {
  7817. throw new TypeError("Utils.waitAnyNode 第二个参数必须是number|Node");
  7818. }
  7819. }
  7820. else if (args.length === 3) {
  7821. // "div",document,10000
  7822. // 第二个参数,parent
  7823. let secondParam = args[1];
  7824. // 第三个参数,timeout
  7825. let thirdParam = args[2];
  7826. if (typeof secondParam === "object" && secondParam instanceof Node) {
  7827. parent = secondParam;
  7828. if (typeof thirdParam === "number") {
  7829. timeout = thirdParam;
  7830. }
  7831. else {
  7832. throw new TypeError("Utils.waitAnyNode 第三个参数必须是number");
  7833. }
  7834. }
  7835. else {
  7836. throw new TypeError("Utils.waitAnyNode 第二个参数必须是Node");
  7837. }
  7838. }
  7839. else {
  7840. throw new TypeError("Utils.waitAnyNode 参数个数错误");
  7841. }
  7842. let promiseList = selectorList.map((selector) => {
  7843. return UtilsContext.waitNode(selector, parent, timeout);
  7844. });
  7845. return Promise.any(promiseList);
  7846. }
  7847. waitNodeList(...args) {
  7848. // 过滤掉undefined
  7849. args = args.filter((arg) => arg !== undefined);
  7850. let UtilsContext = this;
  7851. // 选择器数组
  7852. let selector = args[0];
  7853. // 父元素(监听的元素)
  7854. let parent = UtilsContext.windowApi.document;
  7855. // 超时时间
  7856. let timeout = 0;
  7857. if (typeof args[0] !== "string" && !Array.isArray(args[0])) {
  7858. throw new TypeError("Utils.waitNodeList 第一个参数必须是string|string[]");
  7859. }
  7860. if (args.length === 1) ;
  7861. else if (args.length === 2) {
  7862. let secondParam = args[1];
  7863. if (typeof secondParam === "number") {
  7864. // "div",10000
  7865. timeout = secondParam;
  7866. }
  7867. else if (typeof secondParam === "object" &&
  7868. secondParam instanceof Node) {
  7869. // "div",document
  7870. parent = secondParam;
  7871. }
  7872. else {
  7873. throw new TypeError("Utils.waitNodeList 第二个参数必须是number|Node");
  7874. }
  7875. }
  7876. else if (args.length === 3) {
  7877. // "div",document,10000
  7878. // 第二个参数,parent
  7879. let secondParam = args[1];
  7880. // 第三个参数,timeout
  7881. let thirdParam = args[2];
  7882. if (typeof secondParam === "object" && secondParam instanceof Node) {
  7883. parent = secondParam;
  7884. if (typeof thirdParam === "number") {
  7885. timeout = thirdParam;
  7886. }
  7887. else {
  7888. throw new TypeError("Utils.waitNodeList 第三个参数必须是number");
  7889. }
  7890. }
  7891. else {
  7892. throw new TypeError("Utils.waitNodeList 第二个参数必须是Node");
  7893. }
  7894. }
  7895. else {
  7896. throw new TypeError("Utils.waitNodeList 参数个数错误");
  7897. }
  7898. function getNodeList() {
  7899. if (Array.isArray(selector)) {
  7900. let result = [];
  7901. for (let index = 0; index < selector.length; index++) {
  7902. let nodeList = parent.querySelectorAll(selector[index]);
  7903. if (nodeList.length) {
  7904. result.push(nodeList);
  7905. }
  7906. }
  7907. if (result.length === selector.length) {
  7908. return result;
  7909. }
  7910. }
  7911. else {
  7912. let nodeList = parent.querySelectorAll(selector);
  7913. if (nodeList.length) {
  7914. return nodeList;
  7915. }
  7916. }
  7917. }
  7918. return UtilsContext.wait(() => {
  7919. let node = getNodeList();
  7920. if (node) {
  7921. return {
  7922. success: true,
  7923. data: node,
  7924. };
  7925. }
  7926. else {
  7927. return {
  7928. success: false,
  7929. data: node,
  7930. };
  7931. }
  7932. }, timeout, parent);
  7933. }
  7934. waitAnyNodeList(...args) {
  7935. // 过滤掉undefined
  7936. args = args.filter((arg) => arg !== undefined);
  7937. let UtilsContext = this;
  7938. // 选择器数组
  7939. let selectorList = args[0];
  7940. // 父元素(监听的元素)
  7941. let parent = UtilsContext.windowApi.document;
  7942. // 超时时间
  7943. let timeout = 0;
  7944. if (!Array.isArray(args[0])) {
  7945. throw new TypeError("Utils.waitAnyNodeList 第一个参数必须是string[]");
  7946. }
  7947. if (args.length === 1) ;
  7948. else if (args.length === 2) {
  7949. let secondParam = args[1];
  7950. if (typeof secondParam === "number") {
  7951. // "div",10000
  7952. timeout = secondParam;
  7953. }
  7954. else if (typeof secondParam === "object" &&
  7955. secondParam instanceof Node) {
  7956. // "div",document
  7957. parent = secondParam;
  7958. }
  7959. else {
  7960. throw new TypeError("Utils.waitAnyNodeList 第二个参数必须是number|Node");
  7961. }
  7962. }
  7963. else if (args.length === 3) {
  7964. // "div",document,10000
  7965. // 第二个参数,parent
  7966. let secondParam = args[1];
  7967. // 第三个参数,timeout
  7968. let thirdParam = args[2];
  7969. if (typeof secondParam === "object" && secondParam instanceof Node) {
  7970. parent = secondParam;
  7971. if (typeof thirdParam === "number") {
  7972. timeout = thirdParam;
  7973. }
  7974. else {
  7975. throw new TypeError("Utils.waitAnyNodeList 第三个参数必须是number");
  7976. }
  7977. }
  7978. else {
  7979. throw new TypeError("Utils.waitAnyNodeList 第二个参数必须是Node");
  7980. }
  7981. }
  7982. else {
  7983. throw new TypeError("Utils.waitAnyNodeList 参数个数错误");
  7984. }
  7985. let promiseList = selectorList.map((selector) => {
  7986. return UtilsContext.waitNodeList(selector, parent, timeout);
  7987. });
  7988. return Promise.any(promiseList);
  7989. }
  7990. waitProperty(checkObj, checkPropertyName) {
  7991. return new Promise((resolve) => {
  7992. let obj = checkObj;
  7993. if (typeof checkObj === "function") {
  7994. obj = checkObj();
  7995. }
  7996. if (Reflect.has(obj, checkPropertyName)) {
  7997. resolve(obj[checkPropertyName]);
  7998. }
  7999. else {
  8000. Object.defineProperty(obj, checkPropertyName, {
  8001. set: function (value) {
  8002. try {
  8003. resolve(value);
  8004. }
  8005. catch (error) {
  8006. console.error("Error setting property:", error);
  8007. }
  8008. },
  8009. });
  8010. }
  8011. });
  8012. }
  8013. waitPropertyByInterval(checkObj, checkPropertyName, intervalTimer = 250, maxTime = -1) {
  8014. if (checkObj == null) {
  8015. throw new TypeError("checkObj 不能为空对象 ");
  8016. }
  8017. let isResolve = false;
  8018. return new Promise((resolve, reject) => {
  8019. let interval = setInterval(() => {
  8020. let obj = checkObj;
  8021. if (typeof checkObj === "function") {
  8022. obj = checkObj();
  8023. }
  8024. if (typeof obj !== "object") {
  8025. return;
  8026. }
  8027. if (obj == null) {
  8028. return;
  8029. }
  8030. if ((typeof checkPropertyName === "function" && checkPropertyName(obj)) ||
  8031. Reflect.has(obj, checkPropertyName)) {
  8032. isResolve = true;
  8033. clearInterval(interval);
  8034. resolve(obj[checkPropertyName]);
  8035. }
  8036. }, intervalTimer);
  8037. if (maxTime !== -1) {
  8038. setTimeout(() => {
  8039. if (!isResolve) {
  8040. clearInterval(interval);
  8041. reject();
  8042. }
  8043. }, maxTime);
  8044. }
  8045. });
  8046. }
  8047. async waitVueByInterval(element, propertyName, timer = 250, maxTime = -1, vueName = "__vue__") {
  8048. if (element == null) {
  8049. throw new Error("Utils.waitVueByInterval 参数element 不能为空");
  8050. }
  8051. let flag = false;
  8052. let UtilsContext = this;
  8053. try {
  8054. await UtilsContext.waitPropertyByInterval(element, function (targetElement) {
  8055. if (targetElement == null) {
  8056. return false;
  8057. }
  8058. if (!(vueName in targetElement)) {
  8059. return false;
  8060. }
  8061. if (propertyName == null) {
  8062. return true;
  8063. }
  8064. let vueObject = targetElement[vueName];
  8065. if (typeof propertyName === "string") {
  8066. if (propertyName in vueObject) {
  8067. flag = true;
  8068. return true;
  8069. }
  8070. }
  8071. else {
  8072. /* Function */
  8073. if (propertyName(vueObject)) {
  8074. flag = true;
  8075. return true;
  8076. }
  8077. }
  8078. return false;
  8079. }, timer, maxTime);
  8080. }
  8081. catch (error) {
  8082. return flag;
  8083. }
  8084. return flag;
  8085. }
  8086. watchObject(target, propertyName, getCallBack, setCallBack) {
  8087. if (typeof getCallBack !== "function" &&
  8088. typeof setCallBack !== "function") {
  8089. return;
  8090. }
  8091. if (typeof getCallBack === "function") {
  8092. Object.defineProperty(target, propertyName, {
  8093. get() {
  8094. if (typeof getCallBack === "function") {
  8095. return getCallBack(target[propertyName]);
  8096. }
  8097. else {
  8098. return target[propertyName];
  8099. }
  8100. },
  8101. });
  8102. }
  8103. else if (typeof setCallBack === "function") {
  8104. Object.defineProperty(target, propertyName, {
  8105. set(value) {
  8106. if (typeof setCallBack === "function") {
  8107. setCallBack(value);
  8108. }
  8109. },
  8110. });
  8111. }
  8112. else {
  8113. Object.defineProperty(target, propertyName, {
  8114. get() {
  8115. if (typeof getCallBack === "function") {
  8116. return getCallBack(target[propertyName]);
  8117. }
  8118. else {
  8119. return target[propertyName];
  8120. }
  8121. },
  8122. set(value) {
  8123. if (typeof setCallBack === "function") {
  8124. setCallBack(value);
  8125. }
  8126. },
  8127. });
  8128. }
  8129. }
  8130. /**
  8131. * 深度获取对象属性
  8132. * @param target 待获取的对象
  8133. * @param handler 获取属性的回调
  8134. */
  8135. queryProperty(target, handler) {
  8136. if (target == null) {
  8137. return;
  8138. }
  8139. let handleResult = handler(target);
  8140. if (handleResult &&
  8141. typeof handleResult.isFind === "boolean" &&
  8142. handleResult.isFind) {
  8143. return handleResult.data;
  8144. }
  8145. return this.queryProperty(handleResult.data, handler);
  8146. }
  8147. /**
  8148. * 创建一个新的Utils实例
  8149. * @param option
  8150. * @returns
  8151. */
  8152. createUtils(option) {
  8153. return new Utils(option);
  8154. }
  8155. /**
  8156. * 将对象转换为FormData
  8157. * @param data 待转换的对象
  8158. * @param isEncode 是否对值为string进行编码转换(encodeURIComponent),默认false
  8159. * @param valueAutoParseToStr 是否对值强制使用JSON.stringify()转换,默认false
  8160. * @example
  8161. * Utils.toFormData({
  8162. * test: "1",
  8163. * 666: 666,
  8164. * })
  8165. */
  8166. toFormData(data, isEncode = false, valueAutoParseToStr = false) {
  8167. const formData = new FormData();
  8168. Object.keys(data).forEach((key) => {
  8169. let value = data[key];
  8170. if (valueAutoParseToStr) {
  8171. value = JSON.stringify(value);
  8172. }
  8173. if (typeof value === "number") {
  8174. value = value.toString();
  8175. }
  8176. if (isEncode && typeof value === "string") {
  8177. value = encodeURIComponent(value);
  8178. }
  8179. if (value instanceof File) {
  8180. formData.append(key, value, value.name);
  8181. }
  8182. else {
  8183. formData.append(key, value);
  8184. }
  8185. });
  8186. return formData;
  8187. }
  8188. /**
  8189. * 将链接转为URL对象,自动补充URL的protocol或者origin
  8190. * @param text 需要转换的链接字符串
  8191. * @example
  8192. * Utils.toUrl("//www.baidu.com/s?word=666");
  8193. * Utils.toUrl("/s?word=666");
  8194. */
  8195. toUrl(text) {
  8196. if (typeof text !== "string") {
  8197. throw new TypeError("toUrl: text must be string");
  8198. }
  8199. text = text.trim();
  8200. if (text === "") {
  8201. throw new TypeError("toUrl: text must not be empty");
  8202. }
  8203. if (text.startsWith("//")) {
  8204. /* //www.baidu.com/xxxxxxx */
  8205. /* 没有protocol,加上 */
  8206. text = this.windowApi.globalThis.location.protocol + text;
  8207. }
  8208. else if (text.startsWith("/")) {
  8209. /* /xxx/info?xxx=xxx */
  8210. /* 没有Origin,加上 */
  8211. text = this.windowApi.globalThis.location.origin + text;
  8212. }
  8213. return new URL(text);
  8214. }
  8215. /**
  8216. * 生成uuid
  8217. * @example
  8218. * Utils.generateUUID()
  8219. */
  8220. generateUUID = GenerateUUID;
  8221. /**
  8222. * 自定义的动态响应对象
  8223. * @example
  8224. * let vue = new Utils.Vue();
  8225. * let reactive = new vue.reactive({});
  8226. * vue.watch(()=>reactive["name"], (newValue, oldValue)=>{
  8227. * console.log("newValue ==> " + newValue);
  8228. * console.log("oldValue ==> " + oldValue);
  8229. * })
  8230. * vue["name"] = "测试";
  8231. * > "测试"
  8232. */
  8233. Vue = Vue;
  8234. ModuleRaid = ModuleRaid;
  8235. }
  8236. let utils = new Utils();
  8237.  
  8238. return utils;
  8239.  
  8240. }));
  8241. //# sourceMappingURL=index.umd.js.map

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址