搜索引擎去广告

谷歌百度搜狗神马必应头条搜索去广告,适配电脑和手机,没去夸克,神马搜索就是夸克搜索,谷歌搜索拦截部分内容广场

目前為 2023-07-22 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name 搜索引擎去广告
  3. // @description 谷歌百度搜狗神马必应头条搜索去广告,适配电脑和手机,没去夸克,神马搜索就是夸克搜索,谷歌搜索拦截部分内容广场
  4. // @author Lemon399
  5. // @version 39
  6. // @match *://www.google.co.jp/*
  7. // @match *://www.google.com.hk/*
  8. // @match *://www.google.com/*
  9. // @match *://m.baidu.com/*
  10. // @match *://www.baidu.com/*
  11. // @match *://m.sm.cn/*
  12. // @match *://yz.m.sm.cn/*
  13. // @match *://wap.sogou.com/*
  14. // @match *://m.sogou.com/*
  15. // @match *://www.sogou.com/*
  16. // @match *://cn.bing.com/*
  17. // @match *://www.bing.com/*
  18. // @match *://so.toutiao.com/*
  19. // @grant GM_addStyle
  20. // @grant unsafeWindow
  21. // @run-at document-body
  22. // @namespace https://lemon399-bitbucket-io.vercel.app/
  23. // @source https://gitee.com/lemon399/tampermonkey-cli/tree/master/projects/abp_parse
  24. // @copyright GPL-3.0
  25. // @license GPL-3.0
  26. // ==/UserScript==
  27.  
  28. /* eslint-disable no-undef */
  29.  
  30. (function (cat) {
  31. "use strict";
  32.  
  33. function __awaiter(thisArg, _arguments, P, generator) {
  34. function adopt(value) {
  35. return value instanceof P
  36. ? value
  37. : new P(function (resolve) {
  38. resolve(value);
  39. });
  40. }
  41. return new (P || (P = Promise))(function (resolve, reject) {
  42. function fulfilled(value) {
  43. try {
  44. step(generator.next(value));
  45. } catch (e) {
  46. reject(e);
  47. }
  48. }
  49. function rejected(value) {
  50. try {
  51. step(generator["throw"](value));
  52. } catch (e) {
  53. reject(e);
  54. }
  55. }
  56. function step(result) {
  57. result.done
  58. ? resolve(result.value)
  59. : adopt(result.value).then(fulfilled, rejected);
  60. }
  61. step((generator = generator.apply(thisArg, _arguments || [])).next());
  62. });
  63. }
  64.  
  65. const userConfig = {
  66. css: " {display: none !important;width: 0 !important;height: 0 !important;} ",
  67. timeout: 10000,
  68. tryCount: 5,
  69. tryTimeout: 500,
  70. };
  71. const defaultRules = `
  72. ! 不支持的规则和开头为 ! 的行会忽略
  73. !
  74. ! 由于语法限制,此处规则中
  75. ! 一个反斜杠需要改成两个,像这样 \\
  76. www.google.com,www.google.com.hk,www.google.co.jp##DIV[data-sokoban-container]:has([href*='%E2%9C%94%EF%B8%8F%E2%96%9B']),DIV[data-sokoban-container]:has([href*='%E3%80%90%E2%9C%94%EF%B8%8F']),DIV[data-sokoban-container]:has([href*='%E2%9E%BF%E3%80%91']),DIV[data-sokoban-container]:has([href*='%E2%8F%AA%29']),DIV[data-sokoban-container]:has([href*='%E2%9A%BD%E3%80%91']),DIV[data-sokoban-container]:has([href*='-%E3%80%90']),DIV[data-sokoban-container]:has([href*='%E2%9C%94%EF%B8%8F'][href*='%E2%98%80%EF%B8%8F']),DIV[data-sokoban-container]:has([href*='-('][href*='%E2%9C%94%EF%B8%8F']),DIV[data-sokoban-container]:has([href*='%E2%9C%94%EF%B8%8F%29']),DIV[data-sokoban-container]:has([href*='-%E2%9C%94%EF%B8%8F']),DIV[data-sokoban-container]:has([href*='%E2%9C%94%EF%B8%8F']),DIV[data-sokoban-container]:has([href*='%E2%9C%85%EF%B8%8F']),DIV[data-sokoban-container]:has([href*='%E2%9E%A1%EF%B8%8F']),DIV[data-sokoban-container]:has([href*='%E2%AD%90']),DIV[data-sokoban-container]:has([href*='%E3%8A%99%EF%B8%8F'])
  77. baidu.com##.ad-wrapper
  78. baidu.com#?#.ec_wise_ad
  79. ##DIV[data-text-ad]
  80. ##.ad-block
  81. www.baidu.com##.result-op[tpl="right_game_recommend"]
  82. www.baidu.com##div[id$="_canvas"]
  83. www.baidu.com##style[id*="s-m"] + div[id^="m"]
  84. www.baidu.com#?##content_left > *:not([id]) *,[class="result c-container new-pmd"][id="1"][tpl="se_com_default"][data-click="{"]
  85. www.baidu.com#?##content_left > div:not([class]) > div[data-placeid]
  86. www.baidu.com#?##content_right > table > tbody > tr > td > div:not(#con-ar):not([class])
  87. www.baidu.com#?#div:not([id]) > style[id^="s-"] + div[id]
  88. www.baidu.com#?##content_left > [style*="important"]
  89. www.baidu.com#?#div[id$="_canvas"]
  90. www.baidu.com#?#.c-container:-abp-has(.t > a[data-landurl])
  91. baidu.com###content_left > *:not([id]) *
  92. baidu.com##[class='result c-container new-pmd'][id='1'][tpl='se_com_default'][data-click='{']
  93. baidu.com###content_right > table > tbody > tr > td > div:not(#con-ar):not([class])
  94. baidu.com##.result-op[tpl='sp_hot_sale']
  95. m.baidu.com##DIV#relativewords.se-relativewords.c-container.se-relativewords-new.c-bg-color-white
  96. m.sm.cn##DIV.ad-alert-info
  97. ##.se-recommend-word-list-container
  98. ###se-recommend-word-list-container
  99. ##[class*="ball-wrapper"]
  100. baidu.com##DIV#page-copyright.se-page-copyright[style='margin-bottom: 50px;']
  101. baidu.com##DIV[style^='position: fixed; bottom: 0px; left: 0px; z-index: 300; width: 100%; height: 52px; background: rgb(255, 255, 255);']
  102. ##[ad_dot_url*="http"]
  103. ##.dl-banner-without-logo
  104. ##.ad_result
  105. ###content_left > *:not([id]) *
  106. ##[class="result c-container new-pmd"][id="1"][tpl="se_com_default"][data-click="{"]
  107. ##.biz_sponsor
  108. ##.b_algospacing
  109. ##[onmousedown*="ad"][h*="Ads"]
  110. bing.com##DIV#bnp_container
  111. bing.com##li.b_ad
  112. bing.com##.ad_sc
  113. bing.com#?#li[class="b_algo"]:-abp-has(.b_attribution[data-partnertag]+p[class])
  114. bing.com#?##b_results > li:-abp-has(.b_adProvider)
  115. so.toutiao.com##DIV[id^='ad_']
  116. ##[href^='http://yz.m.sm.cn/adclick']
  117. `;
  118.  
  119. const CRRE =
  120. /^(\[\$domain=)?(~?[\w-]+(?:\.[\w-]+)*(?:\.[\w-]+|\.\*)(?:(?:,|\|)~?[\w-]+(?:\.[\w-]+)*(?:\.[\w-]+|\.\*))*)?(?:])?(#@?\$?\??#)([^\s^+].*)/,
  121. CRFlags = ["##", "#@#", "#?#", "#@?#", "#$#", "#@$#", "#$?#", "#@$?#"],
  122. styleBoxes = ["genHideCss", "genExtraCss", "spcHideCss", "spcExtraCss"],
  123. dataBoxes = ["selectors", "extSelectors", "styles", "extStyles"];
  124. function makeRuleBox() {
  125. return {
  126. black: [],
  127. white: [],
  128. };
  129. }
  130. function domainChecker(domains) {
  131. const results = [],
  132. invResults = [],
  133. currDomain = location.hostname,
  134. urlSuffix = /\.+?[\w-]+$/.exec(currDomain);
  135. let totalResult = [0, false],
  136. black = false,
  137. white = false,
  138. match = false;
  139. domains.forEach((domain) => {
  140. const invert = domain[0] === "~";
  141. if (invert) domain = domain.slice(1);
  142. if (domain.endsWith(".*") && Array.isArray(urlSuffix)) {
  143. domain = domain.replace(".*", urlSuffix[0]);
  144. }
  145. const result = currDomain.endsWith(domain);
  146. if (invert) {
  147. if (result) white = true;
  148. invResults.push([domain.length, !result]);
  149. } else {
  150. if (result) black = true;
  151. results.push([domain.length, result]);
  152. }
  153. });
  154. if (results.length > 0 && !black) {
  155. match = false;
  156. } else if (invResults.length > 0 && !white) {
  157. match = true;
  158. } else {
  159. results.forEach((r) => {
  160. if (r[0] >= totalResult[0] && r[1]) {
  161. totalResult = r;
  162. }
  163. });
  164. invResults.forEach((r) => {
  165. if (r[0] >= totalResult[0] && !r[1]) {
  166. totalResult = r;
  167. }
  168. });
  169. match = totalResult[1];
  170. }
  171. return [match, results.length === 0];
  172. }
  173. function hasSome(str, arr) {
  174. return arr.some((word) => str.includes(word));
  175. }
  176. function ruleSpliter(rule) {
  177. const group = rule.match(CRRE);
  178. if (group) {
  179. const [, isDomain, place = "*", flag, sel] = group,
  180. type = CRFlags.indexOf(flag),
  181. matchResult =
  182. place === "*"
  183. ? [true, true]
  184. : domainChecker(place.split(isDomain ? "|" : ","));
  185. if (sel && matchResult[0]) {
  186. return {
  187. black: type % 2 ? "white" : "black",
  188. type: Math.floor(type / 2),
  189. place: (isDomain ? "|" : "") + place,
  190. generic: matchResult[1],
  191. sel,
  192. };
  193. }
  194. }
  195. }
  196. function ruleLoader(rule) {
  197. if (
  198. hasSome(rule, [
  199. ":matches-path(",
  200. ":min-text-length(",
  201. ":watch-attr(",
  202. ":-abp-properties(",
  203. ":matches-property(",
  204. ])
  205. )
  206. return;
  207. // 去掉开头末尾空格
  208. rule = rule.trim();
  209. // 如果 #$# 不包含 {} 就排除
  210. // 可以尽量排除 Snippet Filters
  211. if (
  212. /(?:\w|\*|]|^)#\$#/.test(rule) &&
  213. !/{\s*[a-zA-Z-]+\s*:\s*.+}\s*$/.test(rule)
  214. )
  215. return;
  216. // ## -> #?#
  217. if (
  218. /(?:\w|\*|]|^)#@?\$?#/.test(rule) &&
  219. hasSome(rule, [
  220. ":has(",
  221. ":-abp-has(",
  222. "[-ext-has=",
  223. ":has-text(",
  224. ":contains(",
  225. ":-abp-contains(",
  226. "[-ext-contains=",
  227. ":matches-css(",
  228. "[-ext-matches-css=",
  229. ":matches-css-before(",
  230. "[-ext-matches-css-before=",
  231. ":matches-css-after(",
  232. "[-ext-matches-css-after=",
  233. ":matches-attr(",
  234. ":nth-ancestor(",
  235. ":upward(",
  236. ":xpath(",
  237. ":remove()",
  238. ":not(",
  239. ])
  240. ) {
  241. rule = rule.replace(/(\w|\*|]|^)#(@?\$?)#/, "$1#$2?#");
  242. }
  243. // :style(...) 转换
  244. // example.com#?##id:style(color: red)
  245. // example.com#$?##id { color: red }
  246. if (rule.includes(":style(")) {
  247. rule = rule
  248. .replace(/(\w|\*|]|^)#(@?)(\??)#/, "$1#$2$$$3#")
  249. .replace(/:style\(\s*/, " { ")
  250. .replace(/\s*\)$/, " }");
  251. }
  252. return ruleSpliter(rule);
  253. }
  254. function ruleToCss(rule, preset) {
  255. var _a, _b;
  256. const isStyle = /}\s*$/.test(rule.sel);
  257. return [
  258. `/* ${rule.type}${rule.place} */ ${
  259. rule.sel + (!isStyle ? preset : "")
  260. } \n`,
  261. isStyle
  262. ? (_b =
  263. (_a = rule.sel.match(/^(.+?)\s*{\s*[a-zA-Z-]+\s*:\s*.+}\s*$/)) ===
  264. null || _a === void 0
  265. ? void 0
  266. : _a[1]) !== null && _b !== void 0
  267. ? _b
  268. : rule.sel
  269. : rule.sel,
  270. ];
  271. }
  272.  
  273. const data = {
  274. disabled: false,
  275. saved: false,
  276. update: true,
  277. updating: false,
  278. receivedRules: "",
  279. customRules: defaultRules,
  280. allRules: "",
  281. genHideCss: "",
  282. genExtraCss: "",
  283. spcHideCss: "",
  284. spcExtraCss: "",
  285. selectors: makeRuleBox(),
  286. extSelectors: makeRuleBox(),
  287. styles: makeRuleBox(),
  288. extStyles: makeRuleBox(),
  289. bRules: [],
  290. appliedLevel: 0,
  291. appliedCount: 0,
  292. isFrame: cat.unsafeWindow.self !== cat.unsafeWindow.top,
  293. isClean: false,
  294. mutex: "__lemon__abp__parser__$__",
  295. preset: getUserConfig("css"),
  296. timeout: getUserConfig("timeout"),
  297. xTimeout: 1000,
  298. tryCount: getUserConfig("tryCount"),
  299. tryTimeout: getUserConfig("tryTimeout"),
  300. };
  301. function getUserConfig(prop) {
  302. {
  303. return userConfig[prop];
  304. }
  305. }
  306. function addStyle(css, pass = 0) {
  307. let el;
  308. if (pass >= data.tryCount) return;
  309. if (typeof cat.GM_addStyle == "function") {
  310. el = cat.GM_addStyle(css);
  311. } else {
  312. el = document.createElement("style");
  313. el.textContent = css;
  314. document.documentElement.appendChild(el);
  315. }
  316. if (!el || !document.documentElement.contains(el)) {
  317. setTimeout(() => {
  318. addStyle(css, pass + 1);
  319. }, data.tryTimeout);
  320. }
  321. }
  322.  
  323. function _defineProperty(obj, key, value) {
  324. if (key in obj) {
  325. Object.defineProperty(obj, key, {
  326. value: value,
  327. enumerable: true,
  328. configurable: true,
  329. writable: true,
  330. });
  331. } else {
  332. obj[key] = value;
  333. }
  334. return obj;
  335. }
  336. const NODE = {
  337. SELECTOR_LIST: "SelectorList",
  338. SELECTOR: "Selector",
  339. REGULAR_SELECTOR: "RegularSelector",
  340. EXTENDED_SELECTOR: "ExtendedSelector",
  341. ABSOLUTE_PSEUDO_CLASS: "AbsolutePseudoClass",
  342. RELATIVE_PSEUDO_CLASS: "RelativePseudoClass",
  343. };
  344. class AnySelectorNode {
  345. constructor(type) {
  346. _defineProperty(this, "children", []);
  347. this.type = type;
  348. }
  349. addChild(child) {
  350. this.children.push(child);
  351. }
  352. }
  353. class RegularSelectorNode extends AnySelectorNode {
  354. constructor(value) {
  355. super(NODE.REGULAR_SELECTOR);
  356. this.value = value;
  357. }
  358. }
  359. class RelativePseudoClassNode extends AnySelectorNode {
  360. constructor(name) {
  361. super(NODE.RELATIVE_PSEUDO_CLASS);
  362. this.name = name;
  363. }
  364. }
  365. class AbsolutePseudoClassNode extends AnySelectorNode {
  366. constructor(name) {
  367. super(NODE.ABSOLUTE_PSEUDO_CLASS);
  368. _defineProperty(this, "value", "");
  369. this.name = name;
  370. }
  371. }
  372. const LEFT_SQUARE_BRACKET = "[";
  373. const RIGHT_SQUARE_BRACKET = "]";
  374. const LEFT_PARENTHESIS = "(";
  375. const RIGHT_PARENTHESIS = ")";
  376. const LEFT_CURLY_BRACKET = "{";
  377. const RIGHT_CURLY_BRACKET = "}";
  378. const BRACKET = {
  379. SQUARE: {
  380. LEFT: LEFT_SQUARE_BRACKET,
  381. RIGHT: RIGHT_SQUARE_BRACKET,
  382. },
  383. PARENTHESES: {
  384. LEFT: LEFT_PARENTHESIS,
  385. RIGHT: RIGHT_PARENTHESIS,
  386. },
  387. CURLY: {
  388. LEFT: LEFT_CURLY_BRACKET,
  389. RIGHT: RIGHT_CURLY_BRACKET,
  390. },
  391. };
  392. const SLASH = "/";
  393. const BACKSLASH = "\\";
  394. const SPACE = " ";
  395. const COMMA = ",";
  396. const DOT = ".";
  397. const SEMICOLON = ";";
  398. const COLON = ":";
  399. const SINGLE_QUOTE = "'";
  400. const DOUBLE_QUOTE = '"';
  401. const CARET = "^";
  402. const DOLLAR_SIGN = "$";
  403. const EQUAL_SIGN = "=";
  404. const TAB = "\t";
  405. const CARRIAGE_RETURN = "\r";
  406. const LINE_FEED = "\n";
  407. const FORM_FEED = "\f";
  408. const WHITE_SPACE_CHARACTERS = [
  409. SPACE,
  410. TAB,
  411. CARRIAGE_RETURN,
  412. LINE_FEED,
  413. FORM_FEED,
  414. ];
  415. const ASTERISK = "*";
  416. const ID_MARKER = "#";
  417. const CLASS_MARKER = DOT;
  418. const DESCENDANT_COMBINATOR = SPACE;
  419. const CHILD_COMBINATOR = ">";
  420. const NEXT_SIBLING_COMBINATOR = "+";
  421. const SUBSEQUENT_SIBLING_COMBINATOR = "~";
  422. const COMBINATORS = [
  423. DESCENDANT_COMBINATOR,
  424. CHILD_COMBINATOR,
  425. NEXT_SIBLING_COMBINATOR,
  426. SUBSEQUENT_SIBLING_COMBINATOR,
  427. ];
  428. const SUPPORTED_SELECTOR_MARKS = [
  429. LEFT_SQUARE_BRACKET,
  430. RIGHT_SQUARE_BRACKET,
  431. LEFT_PARENTHESIS,
  432. RIGHT_PARENTHESIS,
  433. LEFT_CURLY_BRACKET,
  434. RIGHT_CURLY_BRACKET,
  435. SLASH,
  436. BACKSLASH,
  437. SEMICOLON,
  438. COLON,
  439. COMMA,
  440. SINGLE_QUOTE,
  441. DOUBLE_QUOTE,
  442. CARET,
  443. DOLLAR_SIGN,
  444. ASTERISK,
  445. ID_MARKER,
  446. CLASS_MARKER,
  447. DESCENDANT_COMBINATOR,
  448. CHILD_COMBINATOR,
  449. NEXT_SIBLING_COMBINATOR,
  450. SUBSEQUENT_SIBLING_COMBINATOR,
  451. TAB,
  452. CARRIAGE_RETURN,
  453. LINE_FEED,
  454. FORM_FEED,
  455. ];
  456. const SUPPORTED_STYLE_DECLARATION_MARKS = [
  457. COLON,
  458. SEMICOLON,
  459. SINGLE_QUOTE,
  460. DOUBLE_QUOTE,
  461. BACKSLASH,
  462. SPACE,
  463. TAB,
  464. CARRIAGE_RETURN,
  465. LINE_FEED,
  466. FORM_FEED,
  467. ];
  468. const CONTAINS_PSEUDO = "contains";
  469. const HAS_TEXT_PSEUDO = "has-text";
  470. const ABP_CONTAINS_PSEUDO = "-abp-contains";
  471. const MATCHES_CSS_PSEUDO = "matches-css";
  472. const MATCHES_CSS_BEFORE_PSEUDO = "matches-css-before";
  473. const MATCHES_CSS_AFTER_PSEUDO = "matches-css-after";
  474. const MATCHES_ATTR_PSEUDO_CLASS_MARKER = "matches-attr";
  475. const MATCHES_PROPERTY_PSEUDO_CLASS_MARKER = "matches-property";
  476. const XPATH_PSEUDO_CLASS_MARKER = "xpath";
  477. const NTH_ANCESTOR_PSEUDO_CLASS_MARKER = "nth-ancestor";
  478. const CONTAINS_PSEUDO_NAMES = [
  479. CONTAINS_PSEUDO,
  480. HAS_TEXT_PSEUDO,
  481. ABP_CONTAINS_PSEUDO,
  482. ];
  483. const UPWARD_PSEUDO_CLASS_MARKER = "upward";
  484. const REMOVE_PSEUDO_MARKER = "remove";
  485. const HAS_PSEUDO_CLASS_MARKER = "has";
  486. const ABP_HAS_PSEUDO_CLASS_MARKER = "-abp-has";
  487. const HAS_PSEUDO_CLASS_MARKERS = [
  488. HAS_PSEUDO_CLASS_MARKER,
  489. ABP_HAS_PSEUDO_CLASS_MARKER,
  490. ];
  491. const IS_PSEUDO_CLASS_MARKER = "is";
  492. const NOT_PSEUDO_CLASS_MARKER = "not";
  493. const ABSOLUTE_PSEUDO_CLASSES = [
  494. CONTAINS_PSEUDO,
  495. HAS_TEXT_PSEUDO,
  496. ABP_CONTAINS_PSEUDO,
  497. MATCHES_CSS_PSEUDO,
  498. MATCHES_CSS_BEFORE_PSEUDO,
  499. MATCHES_CSS_AFTER_PSEUDO,
  500. MATCHES_ATTR_PSEUDO_CLASS_MARKER,
  501. MATCHES_PROPERTY_PSEUDO_CLASS_MARKER,
  502. XPATH_PSEUDO_CLASS_MARKER,
  503. NTH_ANCESTOR_PSEUDO_CLASS_MARKER,
  504. UPWARD_PSEUDO_CLASS_MARKER,
  505. ];
  506. const RELATIVE_PSEUDO_CLASSES = [
  507. ...HAS_PSEUDO_CLASS_MARKERS,
  508. IS_PSEUDO_CLASS_MARKER,
  509. NOT_PSEUDO_CLASS_MARKER,
  510. ];
  511. const SUPPORTED_PSEUDO_CLASSES = [
  512. ...ABSOLUTE_PSEUDO_CLASSES,
  513. ...RELATIVE_PSEUDO_CLASSES,
  514. ];
  515. const OPTIMIZATION_PSEUDO_CLASSES = [
  516. NOT_PSEUDO_CLASS_MARKER,
  517. IS_PSEUDO_CLASS_MARKER,
  518. ];
  519. const SCOPE_CSS_PSEUDO_CLASS = ":scope";
  520. const REGULAR_PSEUDO_ELEMENTS = {
  521. AFTER: "after",
  522. BACKDROP: "backdrop",
  523. BEFORE: "before",
  524. CUE: "cue",
  525. CUE_REGION: "cue-region",
  526. FIRST_LETTER: "first-letter",
  527. FIRST_LINE: "first-line",
  528. FILE_SELECTION_BUTTON: "file-selector-button",
  529. GRAMMAR_ERROR: "grammar-error",
  530. MARKER: "marker",
  531. PART: "part",
  532. PLACEHOLDER: "placeholder",
  533. SELECTION: "selection",
  534. SLOTTED: "slotted",
  535. SPELLING_ERROR: "spelling-error",
  536. TARGET_TEXT: "target-text",
  537. };
  538. const AT_RULE_MARKER = "@";
  539. const CONTENT_CSS_PROPERTY = "content";
  540. const PSEUDO_PROPERTY_POSITIVE_VALUE = "true";
  541. const DEBUG_PSEUDO_PROPERTY_GLOBAL_VALUE = "global";
  542. const NO_SELECTOR_ERROR_PREFIX = "Selector should be defined";
  543. const STYLE_ERROR_PREFIX = {
  544. NO_STYLE: "No style declaration found",
  545. NO_SELECTOR: `${NO_SELECTOR_ERROR_PREFIX} before style declaration in stylesheet`,
  546. INVALID_STYLE: "Invalid style declaration",
  547. UNCLOSED_STYLE: "Unclosed style declaration",
  548. NO_PROPERTY: "Missing style property in declaration",
  549. NO_VALUE: "Missing style value in declaration",
  550. NO_STYLE_OR_REMOVE:
  551. "Style should be declared or :remove() pseudo-class should used",
  552. NO_COMMENT: "Comments are not supported",
  553. };
  554. const NO_AT_RULE_ERROR_PREFIX = "At-rules are not supported";
  555. const REMOVE_ERROR_PREFIX = {
  556. INVALID_REMOVE: "Invalid :remove() pseudo-class in selector",
  557. NO_TARGET_SELECTOR: `${NO_SELECTOR_ERROR_PREFIX} before :remove() pseudo-class`,
  558. MULTIPLE_USAGE: "Pseudo-class :remove() appears more than once in selector",
  559. INVALID_POSITION: "Pseudo-class :remove() should be at the end of selector",
  560. };
  561. const MATCHING_ELEMENT_ERROR_PREFIX = "Error while matching element";
  562. const MAX_STYLE_PROTECTION_COUNT = 50;
  563. const REGEXP_VALID_OLD_SYNTAX =
  564. /\[-(?:ext)-([a-z-_]+)=(["'])((?:(?=(\\?))\4.)*?)\2\]/g;
  565. const INVALID_OLD_SYNTAX_MARKER = "[-ext-";
  566. const evaluateMatch = (match, name, quoteChar, rawValue) => {
  567. const re = new RegExp(`([^\\\\]|^)\\\\${quoteChar}`, "g");
  568. const value = rawValue.replace(re, `$1${quoteChar}`);
  569. return `:${name}(${value})`;
  570. };
  571. const SCOPE_MARKER_REGEXP = /\(:scope >/g;
  572. const SCOPE_REPLACER = "(>";
  573. const MATCHES_CSS_PSEUDO_ELEMENT_REGEXP = /(:matches-css)-(before|after)\(/g;
  574. const convertMatchesCss = (
  575. match,
  576. extendedPseudoClass,
  577. regularPseudoElement
  578. ) => {
  579. return `${extendedPseudoClass}${BRACKET.PARENTHESES.LEFT}${regularPseudoElement}${COMMA}`;
  580. };
  581. const normalize = (selector) => {
  582. const normalizedSelector = selector
  583. .replace(REGEXP_VALID_OLD_SYNTAX, evaluateMatch)
  584. .replace(SCOPE_MARKER_REGEXP, SCOPE_REPLACER)
  585. .replace(MATCHES_CSS_PSEUDO_ELEMENT_REGEXP, convertMatchesCss);
  586. if (normalizedSelector.includes(INVALID_OLD_SYNTAX_MARKER)) {
  587. throw new Error(
  588. `Invalid extended-css old syntax selector: '${selector}'`
  589. );
  590. }
  591. return normalizedSelector;
  592. };
  593. const convert = (rawSelector) => {
  594. const trimmedSelector = rawSelector.trim();
  595. return normalize(trimmedSelector);
  596. };
  597. const TOKEN_TYPE = {
  598. MARK: "mark",
  599. WORD: "word",
  600. };
  601. const tokenize = (input, supportedMarks) => {
  602. let wordBuffer = "";
  603. const tokens = [];
  604. const selectorSymbols = input.split("");
  605. selectorSymbols.forEach((symbol) => {
  606. if (supportedMarks.includes(symbol)) {
  607. if (wordBuffer.length > 0) {
  608. tokens.push({
  609. type: TOKEN_TYPE.WORD,
  610. value: wordBuffer,
  611. });
  612. wordBuffer = "";
  613. }
  614. tokens.push({
  615. type: TOKEN_TYPE.MARK,
  616. value: symbol,
  617. });
  618. return;
  619. }
  620. wordBuffer += symbol;
  621. });
  622. if (wordBuffer.length > 0) {
  623. tokens.push({
  624. type: TOKEN_TYPE.WORD,
  625. value: wordBuffer,
  626. });
  627. }
  628. return tokens;
  629. };
  630. const tokenizeSelector = (rawSelector) => {
  631. const selector = convert(rawSelector);
  632. return tokenize(selector, SUPPORTED_SELECTOR_MARKS);
  633. };
  634. const tokenizeAttribute = (attribute) => {
  635. return tokenize(attribute, [...SUPPORTED_SELECTOR_MARKS, EQUAL_SIGN]);
  636. };
  637. const flatten = (input) => {
  638. const stack = [];
  639. input.forEach((el) => stack.push(el));
  640. const res = [];
  641. while (stack.length) {
  642. const next = stack.pop();
  643. if (!next) {
  644. throw new Error("Unable to make array flat");
  645. }
  646. if (Array.isArray(next)) {
  647. next.forEach((el) => stack.push(el));
  648. } else {
  649. res.push(next);
  650. }
  651. }
  652. return res.reverse();
  653. };
  654. const getFirst = (array) => {
  655. return array[0];
  656. };
  657. const getLast = (array) => {
  658. return array[array.length - 1];
  659. };
  660. const getPrevToLast = (array) => {
  661. return array[array.length - 2];
  662. };
  663. const getItemByIndex = (array, index, errorMessage) => {
  664. const indexChild = array[index];
  665. if (!indexChild) {
  666. throw new Error(errorMessage || `No array item found by index ${index}`);
  667. }
  668. return indexChild;
  669. };
  670. const NO_REGULAR_SELECTOR_ERROR =
  671. "At least one of Selector node children should be RegularSelector";
  672. const isSelectorListNode = (astNode) => {
  673. return (
  674. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  675. NODE.SELECTOR_LIST
  676. );
  677. };
  678. const isSelectorNode = (astNode) => {
  679. return (
  680. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  681. NODE.SELECTOR
  682. );
  683. };
  684. const isRegularSelectorNode = (astNode) => {
  685. return (
  686. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  687. NODE.REGULAR_SELECTOR
  688. );
  689. };
  690. const isExtendedSelectorNode = (astNode) => {
  691. return astNode.type === NODE.EXTENDED_SELECTOR;
  692. };
  693. const isAbsolutePseudoClassNode = (astNode) => {
  694. return (
  695. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  696. NODE.ABSOLUTE_PSEUDO_CLASS
  697. );
  698. };
  699. const isRelativePseudoClassNode = (astNode) => {
  700. return (
  701. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  702. NODE.RELATIVE_PSEUDO_CLASS
  703. );
  704. };
  705. const getNodeName = (astNode) => {
  706. if (astNode === null) {
  707. throw new Error("Ast node should be defined");
  708. }
  709. if (
  710. !isAbsolutePseudoClassNode(astNode) &&
  711. !isRelativePseudoClassNode(astNode)
  712. ) {
  713. throw new Error(
  714. "Only AbsolutePseudoClass or RelativePseudoClass ast node can have a name"
  715. );
  716. }
  717. if (!astNode.name) {
  718. throw new Error("Extended pseudo-class should have a name");
  719. }
  720. return astNode.name;
  721. };
  722. const getNodeValue = (astNode, errorMessage) => {
  723. if (astNode === null) {
  724. throw new Error("Ast node should be defined");
  725. }
  726. if (
  727. !isRegularSelectorNode(astNode) &&
  728. !isAbsolutePseudoClassNode(astNode)
  729. ) {
  730. throw new Error(
  731. "Only RegularSelector ot AbsolutePseudoClass ast node can have a value"
  732. );
  733. }
  734. if (!astNode.value) {
  735. throw new Error(
  736. errorMessage ||
  737. "Ast RegularSelector ot AbsolutePseudoClass node should have a value"
  738. );
  739. }
  740. return astNode.value;
  741. };
  742. const getRegularSelectorNodes = (children) => {
  743. return children.filter(isRegularSelectorNode);
  744. };
  745. const getFirstRegularChild = (children, errorMessage) => {
  746. const regularSelectorNodes = getRegularSelectorNodes(children);
  747. const firstRegularSelectorNode = getFirst(regularSelectorNodes);
  748. if (!firstRegularSelectorNode) {
  749. throw new Error(errorMessage || NO_REGULAR_SELECTOR_ERROR);
  750. }
  751. return firstRegularSelectorNode;
  752. };
  753. const getLastRegularChild = (children) => {
  754. const regularSelectorNodes = getRegularSelectorNodes(children);
  755. const lastRegularSelectorNode = getLast(regularSelectorNodes);
  756. if (!lastRegularSelectorNode) {
  757. throw new Error(NO_REGULAR_SELECTOR_ERROR);
  758. }
  759. return lastRegularSelectorNode;
  760. };
  761. const getNodeOnlyChild = (node, errorMessage) => {
  762. if (node.children.length !== 1) {
  763. throw new Error(errorMessage);
  764. }
  765. const onlyChild = getFirst(node.children);
  766. if (!onlyChild) {
  767. throw new Error(errorMessage);
  768. }
  769. return onlyChild;
  770. };
  771. const getPseudoClassNode = (extendedSelectorNode) => {
  772. return getNodeOnlyChild(
  773. extendedSelectorNode,
  774. "Extended selector should be specified"
  775. );
  776. };
  777. const getRelativeSelectorListNode = (pseudoClassNode) => {
  778. if (!isRelativePseudoClassNode(pseudoClassNode)) {
  779. throw new Error(
  780. "Only RelativePseudoClass node can have relative SelectorList node as child"
  781. );
  782. }
  783. return getNodeOnlyChild(
  784. pseudoClassNode,
  785. `Missing arg for :${getNodeName(pseudoClassNode)}() pseudo-class`
  786. );
  787. };
  788. const ATTRIBUTE_CASE_INSENSITIVE_FLAG = "i";
  789. const POSSIBLE_MARKS_BEFORE_REGEXP = {
  790. COMMON: [
  791. BRACKET.PARENTHESES.LEFT,
  792. SINGLE_QUOTE,
  793. DOUBLE_QUOTE,
  794. EQUAL_SIGN,
  795. DOT,
  796. COLON,
  797. SPACE,
  798. ],
  799. CONTAINS: [BRACKET.PARENTHESES.LEFT, SINGLE_QUOTE, DOUBLE_QUOTE],
  800. };
  801. const isSupportedPseudoClass = (tokenValue) => {
  802. return SUPPORTED_PSEUDO_CLASSES.includes(tokenValue);
  803. };
  804. const isOptimizationPseudoClass = (name) => {
  805. return OPTIMIZATION_PSEUDO_CLASSES.includes(name);
  806. };
  807. const doesRegularContinueAfterSpace = (nextTokenType, nextTokenValue) => {
  808. if (!nextTokenType || !nextTokenValue) {
  809. return false;
  810. }
  811. return (
  812. COMBINATORS.includes(nextTokenValue) ||
  813. nextTokenType === TOKEN_TYPE.WORD ||
  814. nextTokenValue === ASTERISK ||
  815. nextTokenValue === ID_MARKER ||
  816. nextTokenValue === CLASS_MARKER ||
  817. nextTokenValue === COLON ||
  818. nextTokenValue === SINGLE_QUOTE ||
  819. nextTokenValue === DOUBLE_QUOTE ||
  820. nextTokenValue === BRACKET.SQUARE.LEFT
  821. );
  822. };
  823. const isRegexpOpening = (context, prevTokenValue, bufferNodeValue) => {
  824. const lastExtendedPseudoClassName = getLast(
  825. context.extendedPseudoNamesStack
  826. );
  827. if (!lastExtendedPseudoClassName) {
  828. throw new Error(
  829. "Regexp pattern allowed only in arg of extended pseudo-class"
  830. );
  831. }
  832. if (CONTAINS_PSEUDO_NAMES.includes(lastExtendedPseudoClassName)) {
  833. return POSSIBLE_MARKS_BEFORE_REGEXP.CONTAINS.includes(prevTokenValue);
  834. }
  835. if (
  836. prevTokenValue === SLASH &&
  837. lastExtendedPseudoClassName !== XPATH_PSEUDO_CLASS_MARKER
  838. ) {
  839. const rawArgDesc = bufferNodeValue
  840. ? `in arg part: '${bufferNodeValue}'`
  841. : "arg";
  842. throw new Error(
  843. `Invalid regexp pattern for :${lastExtendedPseudoClassName}() pseudo-class ${rawArgDesc}`
  844. );
  845. }
  846. return POSSIBLE_MARKS_BEFORE_REGEXP.COMMON.includes(prevTokenValue);
  847. };
  848. const isAttributeOpening = (tokenValue, prevTokenValue) => {
  849. return tokenValue === BRACKET.SQUARE.LEFT && prevTokenValue !== BACKSLASH;
  850. };
  851. const isAttributeClosing = (context) => {
  852. var _getPrevToLast;
  853. if (!context.isAttributeBracketsOpen) {
  854. return false;
  855. }
  856. const noSpaceAttr = context.attributeBuffer.split(SPACE).join("");
  857. const attrTokens = tokenizeAttribute(noSpaceAttr);
  858. const firstAttrToken = getFirst(attrTokens);
  859. const firstAttrTokenType =
  860. firstAttrToken === null || firstAttrToken === void 0
  861. ? void 0
  862. : firstAttrToken.type;
  863. const firstAttrTokenValue =
  864. firstAttrToken === null || firstAttrToken === void 0
  865. ? void 0
  866. : firstAttrToken.value;
  867. if (
  868. firstAttrTokenType === TOKEN_TYPE.MARK &&
  869. firstAttrTokenValue !== BACKSLASH
  870. ) {
  871. throw new Error(
  872. `'[${context.attributeBuffer}]' is not a valid attribute due to '${firstAttrTokenValue}' at start of it`
  873. );
  874. }
  875. const lastAttrToken = getLast(attrTokens);
  876. const lastAttrTokenType =
  877. lastAttrToken === null || lastAttrToken === void 0
  878. ? void 0
  879. : lastAttrToken.type;
  880. const lastAttrTokenValue =
  881. lastAttrToken === null || lastAttrToken === void 0
  882. ? void 0
  883. : lastAttrToken.value;
  884. if (lastAttrTokenValue === EQUAL_SIGN) {
  885. throw new Error(
  886. `'[${context.attributeBuffer}]' is not a valid attribute due to '${EQUAL_SIGN}'`
  887. );
  888. }
  889. const equalSignIndex = attrTokens.findIndex((token) => {
  890. return token.type === TOKEN_TYPE.MARK && token.value === EQUAL_SIGN;
  891. });
  892. const prevToLastAttrTokenValue =
  893. (_getPrevToLast = getPrevToLast(attrTokens)) === null ||
  894. _getPrevToLast === void 0
  895. ? void 0
  896. : _getPrevToLast.value;
  897. if (equalSignIndex === -1) {
  898. if (lastAttrTokenType === TOKEN_TYPE.WORD) {
  899. return true;
  900. }
  901. return (
  902. prevToLastAttrTokenValue === BACKSLASH &&
  903. (lastAttrTokenValue === DOUBLE_QUOTE ||
  904. lastAttrTokenValue === SINGLE_QUOTE)
  905. );
  906. }
  907. const nextToEqualSignToken = getItemByIndex(attrTokens, equalSignIndex + 1);
  908. const nextToEqualSignTokenValue = nextToEqualSignToken.value;
  909. const isAttrValueQuote =
  910. nextToEqualSignTokenValue === SINGLE_QUOTE ||
  911. nextToEqualSignTokenValue === DOUBLE_QUOTE;
  912. if (!isAttrValueQuote) {
  913. if (lastAttrTokenType === TOKEN_TYPE.WORD) {
  914. return true;
  915. }
  916. throw new Error(
  917. `'[${context.attributeBuffer}]' is not a valid attribute`
  918. );
  919. }
  920. if (
  921. lastAttrTokenType === TOKEN_TYPE.WORD &&
  922. (lastAttrTokenValue === null || lastAttrTokenValue === void 0
  923. ? void 0
  924. : lastAttrTokenValue.toLocaleLowerCase()) ===
  925. ATTRIBUTE_CASE_INSENSITIVE_FLAG
  926. ) {
  927. return prevToLastAttrTokenValue === nextToEqualSignTokenValue;
  928. }
  929. return lastAttrTokenValue === nextToEqualSignTokenValue;
  930. };
  931. const isWhiteSpaceChar = (tokenValue) => {
  932. if (!tokenValue) {
  933. return false;
  934. }
  935. return WHITE_SPACE_CHARACTERS.includes(tokenValue);
  936. };
  937. const isAbsolutePseudoClass = (str) => {
  938. return ABSOLUTE_PSEUDO_CLASSES.includes(str);
  939. };
  940. const isRelativePseudoClass = (str) => {
  941. return RELATIVE_PSEUDO_CLASSES.includes(str);
  942. };
  943. const getBufferNode = (context) => {
  944. if (context.pathToBufferNode.length === 0) {
  945. return null;
  946. }
  947. return getLast(context.pathToBufferNode) || null;
  948. };
  949. const getBufferNodeParent = (context) => {
  950. if (context.pathToBufferNode.length < 2) {
  951. return null;
  952. }
  953. return getPrevToLast(context.pathToBufferNode) || null;
  954. };
  955. const getContextLastRegularSelectorNode = (context) => {
  956. const bufferNode = getBufferNode(context);
  957. if (!bufferNode) {
  958. throw new Error("No bufferNode found");
  959. }
  960. if (!isSelectorNode(bufferNode)) {
  961. throw new Error("Unsupported bufferNode type");
  962. }
  963. const lastRegularSelectorNode = getLastRegularChild(bufferNode.children);
  964. context.pathToBufferNode.push(lastRegularSelectorNode);
  965. return lastRegularSelectorNode;
  966. };
  967. const updateBufferNode = (context, tokenValue) => {
  968. const bufferNode = getBufferNode(context);
  969. if (bufferNode === null) {
  970. throw new Error("No bufferNode to update");
  971. }
  972. if (isAbsolutePseudoClassNode(bufferNode)) {
  973. bufferNode.value += tokenValue;
  974. } else if (isRegularSelectorNode(bufferNode)) {
  975. bufferNode.value += tokenValue;
  976. if (context.isAttributeBracketsOpen) {
  977. context.attributeBuffer += tokenValue;
  978. }
  979. } else {
  980. throw new Error(
  981. `${bufferNode.type} node cannot be updated. Only RegularSelector and AbsolutePseudoClass are supported`
  982. );
  983. }
  984. };
  985. const addSelectorListNode = (context) => {
  986. const selectorListNode = new AnySelectorNode(NODE.SELECTOR_LIST);
  987. context.ast = selectorListNode;
  988. context.pathToBufferNode.push(selectorListNode);
  989. };
  990. const addAstNodeByType = function (context, type) {
  991. let tokenValue =
  992. arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
  993. const bufferNode = getBufferNode(context);
  994. if (bufferNode === null) {
  995. throw new Error("No buffer node");
  996. }
  997. let node;
  998. if (type === NODE.REGULAR_SELECTOR) {
  999. node = new RegularSelectorNode(tokenValue);
  1000. } else if (type === NODE.ABSOLUTE_PSEUDO_CLASS) {
  1001. node = new AbsolutePseudoClassNode(tokenValue);
  1002. } else if (type === NODE.RELATIVE_PSEUDO_CLASS) {
  1003. node = new RelativePseudoClassNode(tokenValue);
  1004. } else {
  1005. node = new AnySelectorNode(type);
  1006. }
  1007. bufferNode.addChild(node);
  1008. context.pathToBufferNode.push(node);
  1009. };
  1010. const initAst = (context, tokenValue) => {
  1011. addSelectorListNode(context);
  1012. addAstNodeByType(context, NODE.SELECTOR);
  1013. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  1014. };
  1015. const initRelativeSubtree = function (context) {
  1016. let tokenValue =
  1017. arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  1018. addAstNodeByType(context, NODE.SELECTOR_LIST);
  1019. addAstNodeByType(context, NODE.SELECTOR);
  1020. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  1021. };
  1022. const upToClosest = (context, parentType) => {
  1023. for (let i = context.pathToBufferNode.length - 1; i >= 0; i -= 1) {
  1024. var _context$pathToBuffer;
  1025. if (
  1026. ((_context$pathToBuffer = context.pathToBufferNode[i]) === null ||
  1027. _context$pathToBuffer === void 0
  1028. ? void 0
  1029. : _context$pathToBuffer.type) === parentType
  1030. ) {
  1031. context.pathToBufferNode = context.pathToBufferNode.slice(0, i + 1);
  1032. break;
  1033. }
  1034. }
  1035. };
  1036. const getUpdatedBufferNode = (context) => {
  1037. const bufferNode = getBufferNode(context);
  1038. if (
  1039. bufferNode &&
  1040. isSelectorListNode(bufferNode) &&
  1041. isRelativePseudoClassNode(getBufferNodeParent(context))
  1042. ) {
  1043. return bufferNode;
  1044. }
  1045. upToClosest(context, NODE.SELECTOR);
  1046. const selectorNode = getBufferNode(context);
  1047. if (!selectorNode) {
  1048. throw new Error(
  1049. "No SelectorNode, impossible to continue selector parsing by ExtendedCss"
  1050. );
  1051. }
  1052. const lastSelectorNodeChild = getLast(selectorNode.children);
  1053. const hasExtended =
  1054. lastSelectorNodeChild &&
  1055. isExtendedSelectorNode(lastSelectorNodeChild) &&
  1056. context.standardPseudoBracketsStack.length === 0;
  1057. const supposedPseudoClassNode =
  1058. hasExtended && getFirst(lastSelectorNodeChild.children);
  1059. let newNeededBufferNode = selectorNode;
  1060. if (supposedPseudoClassNode) {
  1061. const lastExtendedPseudoName =
  1062. hasExtended && supposedPseudoClassNode.name;
  1063. const isLastExtendedNameRelative =
  1064. lastExtendedPseudoName && isRelativePseudoClass(lastExtendedPseudoName);
  1065. const isLastExtendedNameAbsolute =
  1066. lastExtendedPseudoName && isAbsolutePseudoClass(lastExtendedPseudoName);
  1067. const hasRelativeExtended =
  1068. isLastExtendedNameRelative &&
  1069. context.extendedPseudoBracketsStack.length > 0 &&
  1070. context.extendedPseudoBracketsStack.length ===
  1071. context.extendedPseudoNamesStack.length;
  1072. const hasAbsoluteExtended =
  1073. isLastExtendedNameAbsolute &&
  1074. lastExtendedPseudoName === getLast(context.extendedPseudoNamesStack);
  1075. if (hasRelativeExtended) {
  1076. context.pathToBufferNode.push(lastSelectorNodeChild);
  1077. newNeededBufferNode = supposedPseudoClassNode;
  1078. } else if (hasAbsoluteExtended) {
  1079. context.pathToBufferNode.push(lastSelectorNodeChild);
  1080. newNeededBufferNode = supposedPseudoClassNode;
  1081. }
  1082. } else if (hasExtended) {
  1083. newNeededBufferNode = selectorNode;
  1084. } else {
  1085. newNeededBufferNode = getContextLastRegularSelectorNode(context);
  1086. }
  1087. context.pathToBufferNode.push(newNeededBufferNode);
  1088. return newNeededBufferNode;
  1089. };
  1090. const handleNextTokenOnColon = (
  1091. context,
  1092. selector,
  1093. tokenValue,
  1094. nextTokenValue,
  1095. nextToNextTokenValue
  1096. ) => {
  1097. if (!nextTokenValue) {
  1098. throw new Error(
  1099. `Invalid colon ':' at the end of selector: '${selector}'`
  1100. );
  1101. }
  1102. if (!isSupportedPseudoClass(nextTokenValue.toLowerCase())) {
  1103. if (nextTokenValue.toLowerCase() === REMOVE_PSEUDO_MARKER) {
  1104. throw new Error(`${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`);
  1105. }
  1106. updateBufferNode(context, tokenValue);
  1107. if (
  1108. nextToNextTokenValue &&
  1109. nextToNextTokenValue === BRACKET.PARENTHESES.LEFT &&
  1110. !context.isAttributeBracketsOpen
  1111. ) {
  1112. context.standardPseudoNamesStack.push(nextTokenValue);
  1113. }
  1114. } else {
  1115. if (
  1116. HAS_PSEUDO_CLASS_MARKERS.includes(nextTokenValue) &&
  1117. context.standardPseudoNamesStack.length > 0
  1118. ) {
  1119. throw new Error(
  1120. `Usage of :${nextTokenValue}() pseudo-class is not allowed inside regular pseudo: '${getLast(
  1121. context.standardPseudoNamesStack
  1122. )}'`
  1123. );
  1124. } else {
  1125. upToClosest(context, NODE.SELECTOR);
  1126. addAstNodeByType(context, NODE.EXTENDED_SELECTOR);
  1127. }
  1128. }
  1129. };
  1130. const IS_OR_NOT_PSEUDO_SELECTING_ROOT = `html ${ASTERISK}`;
  1131. const hasExtendedSelector = (selectorList) => {
  1132. return selectorList.children.some((selectorNode) => {
  1133. return selectorNode.children.some((selectorNodeChild) => {
  1134. return isExtendedSelectorNode(selectorNodeChild);
  1135. });
  1136. });
  1137. };
  1138. const selectorListOfRegularsToString = (selectorList) => {
  1139. const standardCssSelectors = selectorList.children.map((selectorNode) => {
  1140. const selectorOnlyChild = getNodeOnlyChild(
  1141. selectorNode,
  1142. "Ast Selector node should have RegularSelector node"
  1143. );
  1144. return getNodeValue(selectorOnlyChild);
  1145. });
  1146. return standardCssSelectors.join(`${COMMA}${SPACE}`);
  1147. };
  1148. const updateNodeChildren = (node, newChildren) => {
  1149. node.children = newChildren;
  1150. return node;
  1151. };
  1152. const shouldOptimizeExtendedSelector = (currExtendedSelectorNode) => {
  1153. if (currExtendedSelectorNode === null) {
  1154. return false;
  1155. }
  1156. const extendedPseudoClassNode = getPseudoClassNode(
  1157. currExtendedSelectorNode
  1158. );
  1159. const pseudoName = getNodeName(extendedPseudoClassNode);
  1160. if (isAbsolutePseudoClass(pseudoName)) {
  1161. return false;
  1162. }
  1163. const relativeSelectorList = getRelativeSelectorListNode(
  1164. extendedPseudoClassNode
  1165. );
  1166. const innerSelectorNodes = relativeSelectorList.children;
  1167. if (isOptimizationPseudoClass(pseudoName)) {
  1168. const areAllSelectorNodeChildrenRegular = innerSelectorNodes.every(
  1169. (selectorNode) => {
  1170. try {
  1171. const selectorOnlyChild = getNodeOnlyChild(
  1172. selectorNode,
  1173. "Selector node should have RegularSelector"
  1174. );
  1175. return isRegularSelectorNode(selectorOnlyChild);
  1176. } catch (e) {
  1177. return false;
  1178. }
  1179. }
  1180. );
  1181. if (areAllSelectorNodeChildrenRegular) {
  1182. return true;
  1183. }
  1184. }
  1185. return innerSelectorNodes.some((selectorNode) => {
  1186. return selectorNode.children.some((selectorNodeChild) => {
  1187. if (!isExtendedSelectorNode(selectorNodeChild)) {
  1188. return false;
  1189. }
  1190. return shouldOptimizeExtendedSelector(selectorNodeChild);
  1191. });
  1192. });
  1193. };
  1194. const getOptimizedExtendedSelector = (
  1195. currExtendedSelectorNode,
  1196. prevRegularSelectorNode
  1197. ) => {
  1198. if (!currExtendedSelectorNode) {
  1199. return null;
  1200. }
  1201. const extendedPseudoClassNode = getPseudoClassNode(
  1202. currExtendedSelectorNode
  1203. );
  1204. const relativeSelectorList = getRelativeSelectorListNode(
  1205. extendedPseudoClassNode
  1206. );
  1207. const hasInnerExtendedSelector = hasExtendedSelector(relativeSelectorList);
  1208. if (!hasInnerExtendedSelector) {
  1209. const relativeSelectorListStr =
  1210. selectorListOfRegularsToString(relativeSelectorList);
  1211. const pseudoName = getNodeName(extendedPseudoClassNode);
  1212. const optimizedExtendedStr = `${COLON}${pseudoName}${BRACKET.PARENTHESES.LEFT}${relativeSelectorListStr}${BRACKET.PARENTHESES.RIGHT}`;
  1213. prevRegularSelectorNode.value = `${getNodeValue(
  1214. prevRegularSelectorNode
  1215. )}${optimizedExtendedStr}`;
  1216. return null;
  1217. }
  1218. const optimizedRelativeSelectorList =
  1219. optimizeSelectorListNode(relativeSelectorList);
  1220. const optimizedExtendedPseudoClassNode = updateNodeChildren(
  1221. extendedPseudoClassNode,
  1222. [optimizedRelativeSelectorList]
  1223. );
  1224. return updateNodeChildren(currExtendedSelectorNode, [
  1225. optimizedExtendedPseudoClassNode,
  1226. ]);
  1227. };
  1228. const optimizeCurrentRegularSelector = (current, previous) => {
  1229. previous.value = `${getNodeValue(previous)}${SPACE}${getNodeValue(
  1230. current
  1231. )}`;
  1232. };
  1233. const optimizeSelectorNode = (selectorNode) => {
  1234. const rawSelectorNodeChildren = selectorNode.children;
  1235. const optimizedChildrenList = [];
  1236. let currentIndex = 0;
  1237. while (currentIndex < rawSelectorNodeChildren.length) {
  1238. const currentChild = getItemByIndex(
  1239. rawSelectorNodeChildren,
  1240. currentIndex,
  1241. "currentChild should be specified"
  1242. );
  1243. if (currentIndex === 0) {
  1244. optimizedChildrenList.push(currentChild);
  1245. } else {
  1246. const prevRegularChild = getLastRegularChild(optimizedChildrenList);
  1247. if (isExtendedSelectorNode(currentChild)) {
  1248. let optimizedExtendedSelector = null;
  1249. let isOptimizationNeeded =
  1250. shouldOptimizeExtendedSelector(currentChild);
  1251. optimizedExtendedSelector = currentChild;
  1252. while (isOptimizationNeeded) {
  1253. optimizedExtendedSelector = getOptimizedExtendedSelector(
  1254. optimizedExtendedSelector,
  1255. prevRegularChild
  1256. );
  1257. isOptimizationNeeded = shouldOptimizeExtendedSelector(
  1258. optimizedExtendedSelector
  1259. );
  1260. }
  1261. if (optimizedExtendedSelector !== null) {
  1262. optimizedChildrenList.push(optimizedExtendedSelector);
  1263. const optimizedPseudoClass = getPseudoClassNode(
  1264. optimizedExtendedSelector
  1265. );
  1266. const optimizedPseudoName = getNodeName(optimizedPseudoClass);
  1267. if (
  1268. getNodeValue(prevRegularChild) === ASTERISK &&
  1269. isOptimizationPseudoClass(optimizedPseudoName)
  1270. ) {
  1271. prevRegularChild.value = IS_OR_NOT_PSEUDO_SELECTING_ROOT;
  1272. }
  1273. }
  1274. } else if (isRegularSelectorNode(currentChild)) {
  1275. const lastOptimizedChild = getLast(optimizedChildrenList) || null;
  1276. if (isRegularSelectorNode(lastOptimizedChild)) {
  1277. optimizeCurrentRegularSelector(currentChild, prevRegularChild);
  1278. }
  1279. }
  1280. }
  1281. currentIndex += 1;
  1282. }
  1283. return updateNodeChildren(selectorNode, optimizedChildrenList);
  1284. };
  1285. const optimizeSelectorListNode = (selectorListNode) => {
  1286. return updateNodeChildren(
  1287. selectorListNode,
  1288. selectorListNode.children.map((s) => optimizeSelectorNode(s))
  1289. );
  1290. };
  1291. const optimizeAst = (ast) => {
  1292. return optimizeSelectorListNode(ast);
  1293. };
  1294. const XPATH_PSEUDO_SELECTING_ROOT = "body";
  1295. const NO_WHITESPACE_ERROR_PREFIX =
  1296. "No white space is allowed before or after extended pseudo-class name in selector";
  1297. const parse = (selector) => {
  1298. const tokens = tokenizeSelector(selector);
  1299. const context = {
  1300. ast: null,
  1301. pathToBufferNode: [],
  1302. extendedPseudoNamesStack: [],
  1303. extendedPseudoBracketsStack: [],
  1304. standardPseudoNamesStack: [],
  1305. standardPseudoBracketsStack: [],
  1306. isAttributeBracketsOpen: false,
  1307. attributeBuffer: "",
  1308. isRegexpOpen: false,
  1309. shouldOptimize: false,
  1310. };
  1311. let i = 0;
  1312. while (i < tokens.length) {
  1313. const token = tokens[i];
  1314. if (!token) {
  1315. break;
  1316. }
  1317. const { type: tokenType, value: tokenValue } = token;
  1318. const nextToken = tokens[i + 1];
  1319. const nextTokenType =
  1320. nextToken === null || nextToken === void 0 ? void 0 : nextToken.type;
  1321. const nextTokenValue =
  1322. nextToken === null || nextToken === void 0 ? void 0 : nextToken.value;
  1323. const nextToNextToken = tokens[i + 2];
  1324. const nextToNextTokenValue =
  1325. nextToNextToken === null || nextToNextToken === void 0
  1326. ? void 0
  1327. : nextToNextToken.value;
  1328. const previousToken = tokens[i - 1];
  1329. const prevTokenType =
  1330. previousToken === null || previousToken === void 0
  1331. ? void 0
  1332. : previousToken.type;
  1333. const prevTokenValue =
  1334. previousToken === null || previousToken === void 0
  1335. ? void 0
  1336. : previousToken.value;
  1337. const previousToPreviousToken = tokens[i - 2];
  1338. const prevToPrevTokenValue =
  1339. previousToPreviousToken === null || previousToPreviousToken === void 0
  1340. ? void 0
  1341. : previousToPreviousToken.value;
  1342. let bufferNode = getBufferNode(context);
  1343. switch (tokenType) {
  1344. case TOKEN_TYPE.WORD:
  1345. if (bufferNode === null) {
  1346. initAst(context, tokenValue);
  1347. } else if (isSelectorListNode(bufferNode)) {
  1348. addAstNodeByType(context, NODE.SELECTOR);
  1349. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  1350. } else if (isRegularSelectorNode(bufferNode)) {
  1351. updateBufferNode(context, tokenValue);
  1352. } else if (isExtendedSelectorNode(bufferNode)) {
  1353. if (
  1354. isWhiteSpaceChar(nextTokenValue) &&
  1355. nextToNextTokenValue === BRACKET.PARENTHESES.LEFT
  1356. ) {
  1357. throw new Error(`${NO_WHITESPACE_ERROR_PREFIX}: '${selector}'`);
  1358. }
  1359. const lowerCaseTokenValue = tokenValue.toLowerCase();
  1360. context.extendedPseudoNamesStack.push(lowerCaseTokenValue);
  1361. if (isAbsolutePseudoClass(lowerCaseTokenValue)) {
  1362. addAstNodeByType(
  1363. context,
  1364. NODE.ABSOLUTE_PSEUDO_CLASS,
  1365. lowerCaseTokenValue
  1366. );
  1367. } else {
  1368. addAstNodeByType(
  1369. context,
  1370. NODE.RELATIVE_PSEUDO_CLASS,
  1371. lowerCaseTokenValue
  1372. );
  1373. if (isOptimizationPseudoClass(lowerCaseTokenValue)) {
  1374. context.shouldOptimize = true;
  1375. }
  1376. }
  1377. } else if (isAbsolutePseudoClassNode(bufferNode)) {
  1378. updateBufferNode(context, tokenValue);
  1379. } else if (isRelativePseudoClassNode(bufferNode)) {
  1380. initRelativeSubtree(context, tokenValue);
  1381. }
  1382. break;
  1383. case TOKEN_TYPE.MARK:
  1384. switch (tokenValue) {
  1385. case COMMA:
  1386. if (
  1387. !bufferNode ||
  1388. (typeof bufferNode !== "undefined" && !nextTokenValue)
  1389. ) {
  1390. throw new Error(`'${selector}' is not a valid selector`);
  1391. } else if (isRegularSelectorNode(bufferNode)) {
  1392. if (context.isAttributeBracketsOpen) {
  1393. updateBufferNode(context, tokenValue);
  1394. } else {
  1395. upToClosest(context, NODE.SELECTOR_LIST);
  1396. }
  1397. } else if (isAbsolutePseudoClassNode(bufferNode)) {
  1398. updateBufferNode(context, tokenValue);
  1399. } else if (isSelectorNode(bufferNode)) {
  1400. upToClosest(context, NODE.SELECTOR_LIST);
  1401. }
  1402. break;
  1403. case SPACE:
  1404. if (
  1405. isRegularSelectorNode(bufferNode) &&
  1406. !context.isAttributeBracketsOpen
  1407. ) {
  1408. bufferNode = getUpdatedBufferNode(context);
  1409. }
  1410. if (isRegularSelectorNode(bufferNode)) {
  1411. if (
  1412. !context.isAttributeBracketsOpen &&
  1413. ((prevTokenValue === COLON &&
  1414. nextTokenType === TOKEN_TYPE.WORD) ||
  1415. (prevTokenType === TOKEN_TYPE.WORD &&
  1416. nextTokenValue === BRACKET.PARENTHESES.LEFT))
  1417. ) {
  1418. throw new Error(`'${selector}' is not a valid selector`);
  1419. }
  1420. if (
  1421. !nextTokenValue ||
  1422. doesRegularContinueAfterSpace(
  1423. nextTokenType,
  1424. nextTokenValue
  1425. ) ||
  1426. context.isAttributeBracketsOpen
  1427. ) {
  1428. updateBufferNode(context, tokenValue);
  1429. }
  1430. }
  1431. if (isAbsolutePseudoClassNode(bufferNode)) {
  1432. updateBufferNode(context, tokenValue);
  1433. }
  1434. if (isRelativePseudoClassNode(bufferNode)) {
  1435. initRelativeSubtree(context);
  1436. }
  1437. if (isSelectorNode(bufferNode)) {
  1438. if (
  1439. doesRegularContinueAfterSpace(nextTokenType, nextTokenValue)
  1440. ) {
  1441. addAstNodeByType(context, NODE.REGULAR_SELECTOR);
  1442. }
  1443. }
  1444. break;
  1445. case DESCENDANT_COMBINATOR:
  1446. case CHILD_COMBINATOR:
  1447. case NEXT_SIBLING_COMBINATOR:
  1448. case SUBSEQUENT_SIBLING_COMBINATOR:
  1449. case SEMICOLON:
  1450. case SLASH:
  1451. case BACKSLASH:
  1452. case SINGLE_QUOTE:
  1453. case DOUBLE_QUOTE:
  1454. case CARET:
  1455. case DOLLAR_SIGN:
  1456. case BRACKET.CURLY.LEFT:
  1457. case BRACKET.CURLY.RIGHT:
  1458. case ASTERISK:
  1459. case ID_MARKER:
  1460. case CLASS_MARKER:
  1461. case BRACKET.SQUARE.LEFT:
  1462. if (COMBINATORS.includes(tokenValue)) {
  1463. if (bufferNode === null) {
  1464. throw new Error(`'${selector}' is not a valid selector`);
  1465. }
  1466. bufferNode = getUpdatedBufferNode(context);
  1467. }
  1468. if (bufferNode === null) {
  1469. initAst(context, tokenValue);
  1470. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  1471. context.isAttributeBracketsOpen = true;
  1472. }
  1473. } else if (isRegularSelectorNode(bufferNode)) {
  1474. if (
  1475. tokenValue === BRACKET.CURLY.LEFT &&
  1476. !(context.isAttributeBracketsOpen || context.isRegexpOpen)
  1477. ) {
  1478. throw new Error(`'${selector}' is not a valid selector`);
  1479. }
  1480. updateBufferNode(context, tokenValue);
  1481. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  1482. context.isAttributeBracketsOpen = true;
  1483. }
  1484. } else if (isAbsolutePseudoClassNode(bufferNode)) {
  1485. updateBufferNode(context, tokenValue);
  1486. if (
  1487. tokenValue === SLASH &&
  1488. context.extendedPseudoNamesStack.length > 0
  1489. ) {
  1490. if (
  1491. prevTokenValue === SLASH &&
  1492. prevToPrevTokenValue === BACKSLASH
  1493. ) {
  1494. context.isRegexpOpen = false;
  1495. } else if (prevTokenValue && prevTokenValue !== BACKSLASH) {
  1496. if (
  1497. isRegexpOpening(
  1498. context,
  1499. prevTokenValue,
  1500. getNodeValue(bufferNode)
  1501. )
  1502. ) {
  1503. context.isRegexpOpen = !context.isRegexpOpen;
  1504. } else {
  1505. context.isRegexpOpen = false;
  1506. }
  1507. }
  1508. }
  1509. } else if (isRelativePseudoClassNode(bufferNode)) {
  1510. initRelativeSubtree(context, tokenValue);
  1511. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  1512. context.isAttributeBracketsOpen = true;
  1513. }
  1514. } else if (isSelectorNode(bufferNode)) {
  1515. if (COMBINATORS.includes(tokenValue)) {
  1516. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  1517. } else if (!context.isRegexpOpen) {
  1518. bufferNode = getContextLastRegularSelectorNode(context);
  1519. updateBufferNode(context, tokenValue);
  1520. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  1521. context.isAttributeBracketsOpen = true;
  1522. }
  1523. }
  1524. } else if (isSelectorListNode(bufferNode)) {
  1525. addAstNodeByType(context, NODE.SELECTOR);
  1526. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  1527. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  1528. context.isAttributeBracketsOpen = true;
  1529. }
  1530. }
  1531. break;
  1532. case BRACKET.SQUARE.RIGHT:
  1533. if (isRegularSelectorNode(bufferNode)) {
  1534. if (
  1535. !context.isAttributeBracketsOpen &&
  1536. prevTokenValue !== BACKSLASH
  1537. ) {
  1538. throw new Error(
  1539. `'${selector}' is not a valid selector due to '${tokenValue}' after '${getNodeValue(
  1540. bufferNode
  1541. )}'`
  1542. );
  1543. }
  1544. if (isAttributeClosing(context)) {
  1545. context.isAttributeBracketsOpen = false;
  1546. context.attributeBuffer = "";
  1547. }
  1548. updateBufferNode(context, tokenValue);
  1549. }
  1550. if (isAbsolutePseudoClassNode(bufferNode)) {
  1551. updateBufferNode(context, tokenValue);
  1552. }
  1553. break;
  1554. case COLON:
  1555. if (
  1556. isWhiteSpaceChar(nextTokenValue) &&
  1557. nextToNextTokenValue &&
  1558. SUPPORTED_PSEUDO_CLASSES.includes(nextToNextTokenValue)
  1559. ) {
  1560. throw new Error(`${NO_WHITESPACE_ERROR_PREFIX}: '${selector}'`);
  1561. }
  1562. if (bufferNode === null) {
  1563. if (nextTokenValue === XPATH_PSEUDO_CLASS_MARKER) {
  1564. initAst(context, XPATH_PSEUDO_SELECTING_ROOT);
  1565. } else if (
  1566. nextTokenValue === UPWARD_PSEUDO_CLASS_MARKER ||
  1567. nextTokenValue === NTH_ANCESTOR_PSEUDO_CLASS_MARKER
  1568. ) {
  1569. throw new Error(
  1570. `${NO_SELECTOR_ERROR_PREFIX} before :${nextTokenValue}() pseudo-class`
  1571. );
  1572. } else {
  1573. initAst(context, ASTERISK);
  1574. }
  1575. bufferNode = getBufferNode(context);
  1576. }
  1577. if (isSelectorListNode(bufferNode)) {
  1578. addAstNodeByType(context, NODE.SELECTOR);
  1579. addAstNodeByType(context, NODE.REGULAR_SELECTOR);
  1580. bufferNode = getBufferNode(context);
  1581. }
  1582. if (isRegularSelectorNode(bufferNode)) {
  1583. if (
  1584. (prevTokenValue && COMBINATORS.includes(prevTokenValue)) ||
  1585. prevTokenValue === COMMA
  1586. ) {
  1587. updateBufferNode(context, ASTERISK);
  1588. }
  1589. handleNextTokenOnColon(
  1590. context,
  1591. selector,
  1592. tokenValue,
  1593. nextTokenValue,
  1594. nextToNextTokenValue
  1595. );
  1596. }
  1597. if (isSelectorNode(bufferNode)) {
  1598. if (!nextTokenValue) {
  1599. throw new Error(
  1600. `Invalid colon ':' at the end of selector: '${selector}'`
  1601. );
  1602. }
  1603. if (isSupportedPseudoClass(nextTokenValue.toLowerCase())) {
  1604. addAstNodeByType(context, NODE.EXTENDED_SELECTOR);
  1605. } else if (
  1606. nextTokenValue.toLowerCase() === REMOVE_PSEUDO_MARKER
  1607. ) {
  1608. throw new Error(
  1609. `${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`
  1610. );
  1611. } else {
  1612. bufferNode = getContextLastRegularSelectorNode(context);
  1613. handleNextTokenOnColon(
  1614. context,
  1615. selector,
  1616. tokenValue,
  1617. nextTokenType,
  1618. nextToNextTokenValue
  1619. );
  1620. }
  1621. }
  1622. if (isAbsolutePseudoClassNode(bufferNode)) {
  1623. if (
  1624. getNodeName(bufferNode) === XPATH_PSEUDO_CLASS_MARKER &&
  1625. nextTokenValue &&
  1626. SUPPORTED_PSEUDO_CLASSES.includes(nextTokenValue) &&
  1627. nextToNextTokenValue === BRACKET.PARENTHESES.LEFT
  1628. ) {
  1629. throw new Error(
  1630. `:xpath() pseudo-class should be the last in selector: '${selector}'`
  1631. );
  1632. }
  1633. updateBufferNode(context, tokenValue);
  1634. }
  1635. if (isRelativePseudoClassNode(bufferNode)) {
  1636. if (!nextTokenValue) {
  1637. throw new Error(
  1638. `Invalid pseudo-class arg at the end of selector: '${selector}'`
  1639. );
  1640. }
  1641. initRelativeSubtree(context, ASTERISK);
  1642. if (!isSupportedPseudoClass(nextTokenValue.toLowerCase())) {
  1643. updateBufferNode(context, tokenValue);
  1644. if (nextToNextTokenValue === BRACKET.PARENTHESES.LEFT) {
  1645. context.standardPseudoNamesStack.push(nextTokenValue);
  1646. }
  1647. } else {
  1648. upToClosest(context, NODE.SELECTOR);
  1649. addAstNodeByType(context, NODE.EXTENDED_SELECTOR);
  1650. }
  1651. }
  1652. break;
  1653. case BRACKET.PARENTHESES.LEFT:
  1654. if (isAbsolutePseudoClassNode(bufferNode)) {
  1655. if (
  1656. getNodeName(bufferNode) !== XPATH_PSEUDO_CLASS_MARKER &&
  1657. context.isRegexpOpen
  1658. ) {
  1659. updateBufferNode(context, tokenValue);
  1660. } else {
  1661. context.extendedPseudoBracketsStack.push(tokenValue);
  1662. if (
  1663. context.extendedPseudoBracketsStack.length >
  1664. context.extendedPseudoNamesStack.length
  1665. ) {
  1666. updateBufferNode(context, tokenValue);
  1667. }
  1668. }
  1669. }
  1670. if (isRegularSelectorNode(bufferNode)) {
  1671. if (context.standardPseudoNamesStack.length > 0) {
  1672. updateBufferNode(context, tokenValue);
  1673. context.standardPseudoBracketsStack.push(tokenValue);
  1674. }
  1675. if (context.isAttributeBracketsOpen) {
  1676. updateBufferNode(context, tokenValue);
  1677. }
  1678. }
  1679. if (isRelativePseudoClassNode(bufferNode)) {
  1680. context.extendedPseudoBracketsStack.push(tokenValue);
  1681. }
  1682. break;
  1683. case BRACKET.PARENTHESES.RIGHT:
  1684. if (isAbsolutePseudoClassNode(bufferNode)) {
  1685. if (
  1686. getNodeName(bufferNode) !== XPATH_PSEUDO_CLASS_MARKER &&
  1687. context.isRegexpOpen
  1688. ) {
  1689. updateBufferNode(context, tokenValue);
  1690. } else {
  1691. context.extendedPseudoBracketsStack.pop();
  1692. if (getNodeName(bufferNode) !== XPATH_PSEUDO_CLASS_MARKER) {
  1693. context.extendedPseudoNamesStack.pop();
  1694. if (
  1695. context.extendedPseudoBracketsStack.length >
  1696. context.extendedPseudoNamesStack.length
  1697. ) {
  1698. updateBufferNode(context, tokenValue);
  1699. } else if (
  1700. context.extendedPseudoBracketsStack.length >= 0 &&
  1701. context.extendedPseudoNamesStack.length >= 0
  1702. ) {
  1703. upToClosest(context, NODE.SELECTOR);
  1704. }
  1705. } else {
  1706. if (
  1707. context.extendedPseudoBracketsStack.length <
  1708. context.extendedPseudoNamesStack.length
  1709. ) {
  1710. context.extendedPseudoNamesStack.pop();
  1711. } else {
  1712. updateBufferNode(context, tokenValue);
  1713. }
  1714. }
  1715. }
  1716. }
  1717. if (isRegularSelectorNode(bufferNode)) {
  1718. if (context.isAttributeBracketsOpen) {
  1719. updateBufferNode(context, tokenValue);
  1720. } else if (
  1721. context.standardPseudoNamesStack.length > 0 &&
  1722. context.standardPseudoBracketsStack.length > 0
  1723. ) {
  1724. updateBufferNode(context, tokenValue);
  1725. context.standardPseudoBracketsStack.pop();
  1726. const lastStandardPseudo =
  1727. context.standardPseudoNamesStack.pop();
  1728. if (!lastStandardPseudo) {
  1729. throw new Error(
  1730. `Parsing error. Invalid selector: ${selector}`
  1731. );
  1732. }
  1733. if (
  1734. Object.values(REGULAR_PSEUDO_ELEMENTS).includes(
  1735. lastStandardPseudo
  1736. ) &&
  1737. nextTokenValue === COLON &&
  1738. nextToNextTokenValue &&
  1739. HAS_PSEUDO_CLASS_MARKERS.includes(nextToNextTokenValue)
  1740. ) {
  1741. throw new Error(
  1742. `Usage of :${nextToNextTokenValue}() pseudo-class is not allowed after any regular pseudo-element: '${lastStandardPseudo}'`
  1743. );
  1744. }
  1745. } else {
  1746. context.extendedPseudoBracketsStack.pop();
  1747. context.extendedPseudoNamesStack.pop();
  1748. upToClosest(context, NODE.EXTENDED_SELECTOR);
  1749. upToClosest(context, NODE.SELECTOR);
  1750. }
  1751. }
  1752. if (isSelectorNode(bufferNode)) {
  1753. context.extendedPseudoBracketsStack.pop();
  1754. context.extendedPseudoNamesStack.pop();
  1755. upToClosest(context, NODE.EXTENDED_SELECTOR);
  1756. upToClosest(context, NODE.SELECTOR);
  1757. }
  1758. if (isRelativePseudoClassNode(bufferNode)) {
  1759. if (
  1760. context.extendedPseudoNamesStack.length > 0 &&
  1761. context.extendedPseudoBracketsStack.length > 0
  1762. ) {
  1763. context.extendedPseudoBracketsStack.pop();
  1764. context.extendedPseudoNamesStack.pop();
  1765. }
  1766. }
  1767. break;
  1768. case LINE_FEED:
  1769. case FORM_FEED:
  1770. case CARRIAGE_RETURN:
  1771. throw new Error(`'${selector}' is not a valid selector`);
  1772. case TAB:
  1773. if (
  1774. isRegularSelectorNode(bufferNode) &&
  1775. context.isAttributeBracketsOpen
  1776. ) {
  1777. updateBufferNode(context, tokenValue);
  1778. } else {
  1779. throw new Error(`'${selector}' is not a valid selector`);
  1780. }
  1781. }
  1782. break;
  1783. default:
  1784. throw new Error(`Unknown type of token: '${tokenValue}'`);
  1785. }
  1786. i += 1;
  1787. }
  1788. if (context.ast === null) {
  1789. throw new Error(`'${selector}' is not a valid selector`);
  1790. }
  1791. if (
  1792. context.extendedPseudoNamesStack.length > 0 ||
  1793. context.extendedPseudoBracketsStack.length > 0
  1794. ) {
  1795. throw new Error(
  1796. `Unbalanced brackets for extended pseudo-class: '${getLast(
  1797. context.extendedPseudoNamesStack
  1798. )}'`
  1799. );
  1800. }
  1801. if (context.isAttributeBracketsOpen) {
  1802. throw new Error(
  1803. `Unbalanced attribute brackets in selector: '${selector}'`
  1804. );
  1805. }
  1806. return context.shouldOptimize ? optimizeAst(context.ast) : context.ast;
  1807. };
  1808. const natives = {
  1809. MutationObserver: window.MutationObserver || window.WebKitMutationObserver,
  1810. };
  1811. class NativeTextContent {
  1812. constructor() {
  1813. this.nativeNode = window.Node || Node;
  1814. }
  1815. setGetter() {
  1816. var _Object$getOwnPropert;
  1817. this.getter =
  1818. (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(
  1819. this.nativeNode.prototype,
  1820. "textContent"
  1821. )) === null || _Object$getOwnPropert === void 0
  1822. ? void 0
  1823. : _Object$getOwnPropert.get;
  1824. }
  1825. }
  1826. const nativeTextContent = new NativeTextContent();
  1827. const getNodeTextContent = (domElement) => {
  1828. if (nativeTextContent.getter) {
  1829. return nativeTextContent.getter.apply(domElement);
  1830. }
  1831. return domElement.textContent || "";
  1832. };
  1833. const getElementSelectorDesc = (element) => {
  1834. let selectorText = element.tagName.toLowerCase();
  1835. selectorText += Array.from(element.attributes)
  1836. .map((attr) => {
  1837. return `[${attr.name}="${element.getAttribute(attr.name)}"]`;
  1838. })
  1839. .join("");
  1840. return selectorText;
  1841. };
  1842. const getElementSelectorPath = (inputEl) => {
  1843. if (!(inputEl instanceof Element)) {
  1844. throw new Error("Function received argument with wrong type");
  1845. }
  1846. let el;
  1847. el = inputEl;
  1848. const path = [];
  1849. while (!!el && el.nodeType === Node.ELEMENT_NODE) {
  1850. let selector = el.nodeName.toLowerCase();
  1851. if (el.id && typeof el.id === "string") {
  1852. selector += `#${el.id}`;
  1853. path.unshift(selector);
  1854. break;
  1855. }
  1856. let sibling = el;
  1857. let nth = 1;
  1858. while (sibling.previousElementSibling) {
  1859. sibling = sibling.previousElementSibling;
  1860. if (
  1861. sibling.nodeType === Node.ELEMENT_NODE &&
  1862. sibling.nodeName.toLowerCase() === selector
  1863. ) {
  1864. nth += 1;
  1865. }
  1866. }
  1867. if (nth !== 1) {
  1868. selector += `:nth-of-type(${nth})`;
  1869. }
  1870. path.unshift(selector);
  1871. el = el.parentElement;
  1872. }
  1873. return path.join(" > ");
  1874. };
  1875. const isHtmlElement = (element) => {
  1876. return element instanceof HTMLElement;
  1877. };
  1878. const getParent = (element, errorMessage) => {
  1879. const { parentElement } = element;
  1880. if (!parentElement) {
  1881. throw new Error(errorMessage || "Element does no have parent element");
  1882. }
  1883. return parentElement;
  1884. };
  1885. const isErrorWithMessage = (error) => {
  1886. return (
  1887. typeof error === "object" &&
  1888. error !== null &&
  1889. "message" in error &&
  1890. typeof error.message === "string"
  1891. );
  1892. };
  1893. const toErrorWithMessage = (maybeError) => {
  1894. if (isErrorWithMessage(maybeError)) {
  1895. return maybeError;
  1896. }
  1897. try {
  1898. return new Error(JSON.stringify(maybeError));
  1899. } catch {
  1900. return new Error(String(maybeError));
  1901. }
  1902. };
  1903. const getErrorMessage = (error) => {
  1904. return toErrorWithMessage(error).message;
  1905. };
  1906. const logger = {
  1907. error:
  1908. typeof console !== "undefined" && console.error && console.error.bind
  1909. ? console.error.bind(window.console)
  1910. : console.error,
  1911. info:
  1912. typeof console !== "undefined" && console.info && console.info.bind
  1913. ? console.info.bind(window.console)
  1914. : console.info,
  1915. };
  1916. const removeSuffix = (str, suffix) => {
  1917. const index = str.indexOf(suffix, str.length - suffix.length);
  1918. if (index >= 0) {
  1919. return str.substring(0, index);
  1920. }
  1921. return str;
  1922. };
  1923. const replaceAll = (input, pattern, replacement) => {
  1924. if (!input) {
  1925. return input;
  1926. }
  1927. return input.split(pattern).join(replacement);
  1928. };
  1929. const toRegExp = (str) => {
  1930. if (str.startsWith(SLASH) && str.endsWith(SLASH)) {
  1931. return new RegExp(str.slice(1, -1));
  1932. }
  1933. const escaped = str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  1934. return new RegExp(escaped);
  1935. };
  1936. const convertTypeIntoString = (value) => {
  1937. let output;
  1938. switch (value) {
  1939. case undefined:
  1940. output = "undefined";
  1941. break;
  1942. case null:
  1943. output = "null";
  1944. break;
  1945. default:
  1946. output = value.toString();
  1947. }
  1948. return output;
  1949. };
  1950. const convertTypeFromString = (value) => {
  1951. const numValue = Number(value);
  1952. let output;
  1953. if (!Number.isNaN(numValue)) {
  1954. output = numValue;
  1955. } else {
  1956. switch (value) {
  1957. case "undefined":
  1958. output = undefined;
  1959. break;
  1960. case "null":
  1961. output = null;
  1962. break;
  1963. case "true":
  1964. output = true;
  1965. break;
  1966. case "false":
  1967. output = false;
  1968. break;
  1969. default:
  1970. output = value;
  1971. }
  1972. }
  1973. return output;
  1974. };
  1975. const SAFARI_USER_AGENT_REGEXP = /\sVersion\/(\d{2}\.\d)(.+\s|\s)(Safari)\//;
  1976. const isSafariBrowser = SAFARI_USER_AGENT_REGEXP.test(navigator.userAgent);
  1977. const isUserAgentSupported = (userAgent) => {
  1978. if (userAgent.includes("MSIE") || userAgent.includes("Trident/")) {
  1979. return false;
  1980. }
  1981. return true;
  1982. };
  1983. const isBrowserSupported = () => {
  1984. return isUserAgentSupported(navigator.userAgent);
  1985. };
  1986. const CSS_PROPERTY = {
  1987. BACKGROUND: "background",
  1988. BACKGROUND_IMAGE: "background-image",
  1989. CONTENT: "content",
  1990. OPACITY: "opacity",
  1991. };
  1992. const REGEXP_ANY_SYMBOL = ".*";
  1993. const REGEXP_WITH_FLAGS_REGEXP = /^\s*\/.*\/[gmisuy]*\s*$/;
  1994. const removeContentQuotes = (str) => {
  1995. return str.replace(/^(["'])([\s\S]*)\1$/, "$2");
  1996. };
  1997. const addUrlPropertyQuotes = (str) => {
  1998. if (!str.includes('url("')) {
  1999. const re = /url\((.*?)\)/g;
  2000. return str.replace(re, 'url("$1")');
  2001. }
  2002. return str;
  2003. };
  2004. const addUrlQuotesTo = {
  2005. regexpArg: (str) => {
  2006. const re = /(\^)?url(\\)?\\\((\w|\[\w)/g;
  2007. return str.replace(re, '$1url$2\\(\\"?$3');
  2008. },
  2009. noneRegexpArg: addUrlPropertyQuotes,
  2010. };
  2011. const escapeRegExp = (str) => {
  2012. const specials = [
  2013. ".",
  2014. "+",
  2015. "?",
  2016. "$",
  2017. "{",
  2018. "}",
  2019. "(",
  2020. ")",
  2021. "[",
  2022. "]",
  2023. "\\",
  2024. "/",
  2025. ];
  2026. const specialsRegex = new RegExp(`[${specials.join("\\")}]`, "g");
  2027. return str.replace(specialsRegex, "\\$&");
  2028. };
  2029. const convertStyleMatchValueToRegexp = (rawValue) => {
  2030. let value;
  2031. if (rawValue.startsWith(SLASH) && rawValue.endsWith(SLASH)) {
  2032. value = addUrlQuotesTo.regexpArg(rawValue);
  2033. value = value.slice(1, -1);
  2034. } else {
  2035. value = addUrlQuotesTo.noneRegexpArg(rawValue);
  2036. value = value.replace(/\\([\\()[\]"])/g, "$1");
  2037. value = escapeRegExp(value);
  2038. value = replaceAll(value, ASTERISK, REGEXP_ANY_SYMBOL);
  2039. }
  2040. return new RegExp(value, "i");
  2041. };
  2042. const normalizePropertyValue = (propertyName, propertyValue) => {
  2043. let normalized = "";
  2044. switch (propertyName) {
  2045. case CSS_PROPERTY.BACKGROUND:
  2046. case CSS_PROPERTY.BACKGROUND_IMAGE:
  2047. normalized = addUrlPropertyQuotes(propertyValue);
  2048. break;
  2049. case CSS_PROPERTY.CONTENT:
  2050. normalized = removeContentQuotes(propertyValue);
  2051. break;
  2052. case CSS_PROPERTY.OPACITY:
  2053. normalized = isSafariBrowser
  2054. ? (Math.round(parseFloat(propertyValue) * 100) / 100).toString()
  2055. : propertyValue;
  2056. break;
  2057. default:
  2058. normalized = propertyValue;
  2059. }
  2060. return normalized;
  2061. };
  2062. const getComputedStylePropertyValue = (
  2063. domElement,
  2064. propertyName,
  2065. regularPseudoElement
  2066. ) => {
  2067. const style = window.getComputedStyle(domElement, regularPseudoElement);
  2068. const propertyValue = style.getPropertyValue(propertyName);
  2069. return normalizePropertyValue(propertyName, propertyValue);
  2070. };
  2071. const getPseudoArgData = (pseudoArg, separator) => {
  2072. const index = pseudoArg.indexOf(separator);
  2073. let name;
  2074. let value;
  2075. if (index > -1) {
  2076. name = pseudoArg.substring(0, index).trim();
  2077. value = pseudoArg.substring(index + 1).trim();
  2078. } else {
  2079. name = pseudoArg;
  2080. }
  2081. return {
  2082. name,
  2083. value,
  2084. };
  2085. };
  2086. const parseStyleMatchArg = (pseudoName, rawArg) => {
  2087. const { name, value } = getPseudoArgData(rawArg, COMMA);
  2088. let regularPseudoElement = name;
  2089. let styleMatchArg = value;
  2090. if (!Object.values(REGULAR_PSEUDO_ELEMENTS).includes(name)) {
  2091. regularPseudoElement = null;
  2092. styleMatchArg = rawArg;
  2093. }
  2094. if (!styleMatchArg) {
  2095. throw new Error(
  2096. `Required style property argument part is missing in :${pseudoName}() arg: '${rawArg}'`
  2097. );
  2098. }
  2099. if (regularPseudoElement) {
  2100. regularPseudoElement = `${COLON}${COLON}${regularPseudoElement}`;
  2101. }
  2102. return {
  2103. regularPseudoElement,
  2104. styleMatchArg,
  2105. };
  2106. };
  2107. const isStyleMatched = (argsData) => {
  2108. const { pseudoName, pseudoArg, domElement } = argsData;
  2109. const { regularPseudoElement, styleMatchArg } = parseStyleMatchArg(
  2110. pseudoName,
  2111. pseudoArg
  2112. );
  2113. const { name: matchName, value: matchValue } = getPseudoArgData(
  2114. styleMatchArg,
  2115. COLON
  2116. );
  2117. if (!matchName || !matchValue) {
  2118. throw new Error(
  2119. `Required property name or value is missing in :${pseudoName}() arg: '${styleMatchArg}'`
  2120. );
  2121. }
  2122. let valueRegexp;
  2123. try {
  2124. valueRegexp = convertStyleMatchValueToRegexp(matchValue);
  2125. } catch (e) {
  2126. logger.error(getErrorMessage(e));
  2127. throw new Error(
  2128. `Invalid argument of :${pseudoName}() pseudo-class: '${styleMatchArg}'`
  2129. );
  2130. }
  2131. const value = getComputedStylePropertyValue(
  2132. domElement,
  2133. matchName,
  2134. regularPseudoElement
  2135. );
  2136. return valueRegexp && valueRegexp.test(value);
  2137. };
  2138. const validateStrMatcherArg = (arg) => {
  2139. if (arg.includes(SLASH)) {
  2140. return false;
  2141. }
  2142. if (!/^[\w-]+$/.test(arg)) {
  2143. return false;
  2144. }
  2145. return true;
  2146. };
  2147. const getValidMatcherArg = function (rawArg) {
  2148. let isWildcardAllowed =
  2149. arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  2150. let arg;
  2151. if (
  2152. rawArg.length > 1 &&
  2153. rawArg.startsWith(DOUBLE_QUOTE) &&
  2154. rawArg.endsWith(DOUBLE_QUOTE)
  2155. ) {
  2156. rawArg = rawArg.slice(1, -1);
  2157. }
  2158. if (rawArg === "") {
  2159. throw new Error("Argument should be specified. Empty arg is invalid.");
  2160. }
  2161. if (rawArg.startsWith(SLASH) && rawArg.endsWith(SLASH)) {
  2162. if (rawArg.length > 2) {
  2163. arg = toRegExp(rawArg);
  2164. } else {
  2165. throw new Error(`Invalid regexp: '${rawArg}'`);
  2166. }
  2167. } else if (rawArg.includes(ASTERISK)) {
  2168. if (rawArg === ASTERISK && !isWildcardAllowed) {
  2169. throw new Error(`Argument should be more specific than ${rawArg}`);
  2170. }
  2171. arg = replaceAll(rawArg, ASTERISK, REGEXP_ANY_SYMBOL);
  2172. arg = new RegExp(arg);
  2173. } else {
  2174. if (!validateStrMatcherArg(rawArg)) {
  2175. throw new Error(`Invalid argument: '${rawArg}'`);
  2176. }
  2177. arg = rawArg;
  2178. }
  2179. return arg;
  2180. };
  2181. const getRawMatchingData = (pseudoName, pseudoArg) => {
  2182. const { name: rawName, value: rawValue } = getPseudoArgData(
  2183. pseudoArg,
  2184. EQUAL_SIGN
  2185. );
  2186. if (!rawName) {
  2187. throw new Error(
  2188. `Required attribute name is missing in :${pseudoName} arg: ${pseudoArg}`
  2189. );
  2190. }
  2191. return {
  2192. rawName,
  2193. rawValue,
  2194. };
  2195. };
  2196. const isAttributeMatched = (argsData) => {
  2197. const { pseudoName, pseudoArg, domElement } = argsData;
  2198. const elementAttributes = domElement.attributes;
  2199. if (elementAttributes.length === 0) {
  2200. return false;
  2201. }
  2202. const { rawName: rawAttrName, rawValue: rawAttrValue } = getRawMatchingData(
  2203. pseudoName,
  2204. pseudoArg
  2205. );
  2206. let attrNameMatch;
  2207. try {
  2208. attrNameMatch = getValidMatcherArg(rawAttrName);
  2209. } catch (e) {
  2210. const errorMessage = getErrorMessage(e);
  2211. logger.error(errorMessage);
  2212. throw new SyntaxError(errorMessage);
  2213. }
  2214. let isMatched = false;
  2215. let i = 0;
  2216. while (i < elementAttributes.length && !isMatched) {
  2217. const attr = elementAttributes[i];
  2218. if (!attr) {
  2219. break;
  2220. }
  2221. const isNameMatched =
  2222. attrNameMatch instanceof RegExp
  2223. ? attrNameMatch.test(attr.name)
  2224. : attrNameMatch === attr.name;
  2225. if (!rawAttrValue) {
  2226. isMatched = isNameMatched;
  2227. } else {
  2228. let attrValueMatch;
  2229. try {
  2230. attrValueMatch = getValidMatcherArg(rawAttrValue);
  2231. } catch (e) {
  2232. const errorMessage = getErrorMessage(e);
  2233. logger.error(errorMessage);
  2234. throw new SyntaxError(errorMessage);
  2235. }
  2236. const isValueMatched =
  2237. attrValueMatch instanceof RegExp
  2238. ? attrValueMatch.test(attr.value)
  2239. : attrValueMatch === attr.value;
  2240. isMatched = isNameMatched && isValueMatched;
  2241. }
  2242. i += 1;
  2243. }
  2244. return isMatched;
  2245. };
  2246. const parseRawPropChain = (input) => {
  2247. if (
  2248. input.length > 1 &&
  2249. input.startsWith(DOUBLE_QUOTE) &&
  2250. input.endsWith(DOUBLE_QUOTE)
  2251. ) {
  2252. input = input.slice(1, -1);
  2253. }
  2254. const chainChunks = input.split(DOT);
  2255. const chainPatterns = [];
  2256. let patternBuffer = "";
  2257. let isRegexpPattern = false;
  2258. let i = 0;
  2259. while (i < chainChunks.length) {
  2260. const chunk = getItemByIndex(
  2261. chainChunks,
  2262. i,
  2263. `Invalid pseudo-class arg: '${input}'`
  2264. );
  2265. if (
  2266. chunk.startsWith(SLASH) &&
  2267. chunk.endsWith(SLASH) &&
  2268. chunk.length > 2
  2269. ) {
  2270. chainPatterns.push(chunk);
  2271. } else if (chunk.startsWith(SLASH)) {
  2272. isRegexpPattern = true;
  2273. patternBuffer += chunk;
  2274. } else if (chunk.endsWith(SLASH)) {
  2275. isRegexpPattern = false;
  2276. patternBuffer += `.${chunk}`;
  2277. chainPatterns.push(patternBuffer);
  2278. patternBuffer = "";
  2279. } else {
  2280. if (isRegexpPattern) {
  2281. patternBuffer += chunk;
  2282. } else {
  2283. chainPatterns.push(chunk);
  2284. }
  2285. }
  2286. i += 1;
  2287. }
  2288. if (patternBuffer.length > 0) {
  2289. throw new Error(`Invalid regexp property pattern '${input}'`);
  2290. }
  2291. const chainMatchPatterns = chainPatterns.map((pattern) => {
  2292. if (pattern.length === 0) {
  2293. throw new Error(
  2294. `Empty pattern '${pattern}' is invalid in chain '${input}'`
  2295. );
  2296. }
  2297. let validPattern;
  2298. try {
  2299. validPattern = getValidMatcherArg(pattern, true);
  2300. } catch (e) {
  2301. logger.error(getErrorMessage(e));
  2302. throw new Error(
  2303. `Invalid property pattern '${pattern}' in property chain '${input}'`
  2304. );
  2305. }
  2306. return validPattern;
  2307. });
  2308. return chainMatchPatterns;
  2309. };
  2310. const filterRootsByRegexpChain = function (base, chain) {
  2311. let output =
  2312. arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  2313. const tempProp = getFirst(chain);
  2314. if (chain.length === 1) {
  2315. let key;
  2316. for (key in base) {
  2317. if (tempProp instanceof RegExp) {
  2318. if (tempProp.test(key)) {
  2319. output.push({
  2320. base,
  2321. prop: key,
  2322. value: base[key],
  2323. });
  2324. }
  2325. } else if (tempProp === key) {
  2326. output.push({
  2327. base,
  2328. prop: tempProp,
  2329. value: base[key],
  2330. });
  2331. }
  2332. }
  2333. return output;
  2334. }
  2335. if (tempProp instanceof RegExp) {
  2336. const nextProp = chain.slice(1);
  2337. const baseKeys = [];
  2338. for (const key in base) {
  2339. if (tempProp.test(key)) {
  2340. baseKeys.push(key);
  2341. }
  2342. }
  2343. baseKeys.forEach((key) => {
  2344. var _Object$getOwnPropert;
  2345. const item =
  2346. (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(
  2347. base,
  2348. key
  2349. )) === null || _Object$getOwnPropert === void 0
  2350. ? void 0
  2351. : _Object$getOwnPropert.value;
  2352. filterRootsByRegexpChain(item, nextProp, output);
  2353. });
  2354. }
  2355. if (base && typeof tempProp === "string") {
  2356. var _Object$getOwnPropert2;
  2357. const nextBase =
  2358. (_Object$getOwnPropert2 = Object.getOwnPropertyDescriptor(
  2359. base,
  2360. tempProp
  2361. )) === null || _Object$getOwnPropert2 === void 0
  2362. ? void 0
  2363. : _Object$getOwnPropert2.value;
  2364. chain = chain.slice(1);
  2365. if (nextBase !== undefined) {
  2366. filterRootsByRegexpChain(nextBase, chain, output);
  2367. }
  2368. }
  2369. return output;
  2370. };
  2371. const isPropertyMatched = (argsData) => {
  2372. const { pseudoName, pseudoArg, domElement } = argsData;
  2373. const { rawName: rawPropertyName, rawValue: rawPropertyValue } =
  2374. getRawMatchingData(pseudoName, pseudoArg);
  2375. if (rawPropertyName.includes("\\/") || rawPropertyName.includes("\\.")) {
  2376. throw new Error(
  2377. `Invalid :${pseudoName} name pattern: ${rawPropertyName}`
  2378. );
  2379. }
  2380. let propChainMatches;
  2381. try {
  2382. propChainMatches = parseRawPropChain(rawPropertyName);
  2383. } catch (e) {
  2384. const errorMessage = getErrorMessage(e);
  2385. logger.error(errorMessage);
  2386. throw new SyntaxError(errorMessage);
  2387. }
  2388. const ownerObjArr = filterRootsByRegexpChain(domElement, propChainMatches);
  2389. if (ownerObjArr.length === 0) {
  2390. return false;
  2391. }
  2392. let isMatched = true;
  2393. if (rawPropertyValue) {
  2394. let propValueMatch;
  2395. try {
  2396. propValueMatch = getValidMatcherArg(rawPropertyValue);
  2397. } catch (e) {
  2398. const errorMessage = getErrorMessage(e);
  2399. logger.error(errorMessage);
  2400. throw new SyntaxError(errorMessage);
  2401. }
  2402. if (propValueMatch) {
  2403. for (let i = 0; i < ownerObjArr.length; i += 1) {
  2404. var _ownerObjArr$i;
  2405. const realValue =
  2406. (_ownerObjArr$i = ownerObjArr[i]) === null ||
  2407. _ownerObjArr$i === void 0
  2408. ? void 0
  2409. : _ownerObjArr$i.value;
  2410. if (propValueMatch instanceof RegExp) {
  2411. isMatched = propValueMatch.test(convertTypeIntoString(realValue));
  2412. } else {
  2413. if (realValue === "null" || realValue === "undefined") {
  2414. isMatched = propValueMatch === realValue;
  2415. break;
  2416. }
  2417. isMatched = convertTypeFromString(propValueMatch) === realValue;
  2418. }
  2419. if (isMatched) {
  2420. break;
  2421. }
  2422. }
  2423. }
  2424. }
  2425. return isMatched;
  2426. };
  2427. const isTextMatched = (argsData) => {
  2428. const { pseudoName, pseudoArg, domElement } = argsData;
  2429. const textContent = getNodeTextContent(domElement);
  2430. let isTextContentMatched;
  2431. let pseudoArgToMatch = pseudoArg;
  2432. if (
  2433. pseudoArgToMatch.startsWith(SLASH) &&
  2434. REGEXP_WITH_FLAGS_REGEXP.test(pseudoArgToMatch)
  2435. ) {
  2436. const flagsIndex = pseudoArgToMatch.lastIndexOf("/");
  2437. const flagsStr = pseudoArgToMatch.substring(flagsIndex + 1);
  2438. pseudoArgToMatch = pseudoArgToMatch
  2439. .substring(0, flagsIndex + 1)
  2440. .slice(1, -1)
  2441. .replace(/\\([\\"])/g, "$1");
  2442. let regex;
  2443. try {
  2444. regex = new RegExp(pseudoArgToMatch, flagsStr);
  2445. } catch (e) {
  2446. throw new Error(
  2447. `Invalid argument of :${pseudoName}() pseudo-class: ${pseudoArg}`
  2448. );
  2449. }
  2450. isTextContentMatched = regex.test(textContent);
  2451. } else {
  2452. pseudoArgToMatch = pseudoArgToMatch.replace(/\\([\\()[\]"])/g, "$1");
  2453. isTextContentMatched = textContent.includes(pseudoArgToMatch);
  2454. }
  2455. return isTextContentMatched;
  2456. };
  2457. const getValidNumberAncestorArg = (rawArg, pseudoName) => {
  2458. const deep = Number(rawArg);
  2459. if (Number.isNaN(deep) || deep < 1 || deep >= 256) {
  2460. throw new Error(
  2461. `Invalid argument of :${pseudoName} pseudo-class: '${rawArg}'`
  2462. );
  2463. }
  2464. return deep;
  2465. };
  2466. const getNthAncestor = (domElement, nth, pseudoName) => {
  2467. let ancestor = null;
  2468. let i = 0;
  2469. while (i < nth) {
  2470. ancestor = domElement.parentElement;
  2471. if (!ancestor) {
  2472. throw new Error(
  2473. `Out of DOM: Argument of :${pseudoName}() pseudo-class is too big '${nth}'.`
  2474. );
  2475. }
  2476. domElement = ancestor;
  2477. i += 1;
  2478. }
  2479. return ancestor;
  2480. };
  2481. const validateStandardSelector = (selector) => {
  2482. let isValid;
  2483. try {
  2484. document.querySelectorAll(selector);
  2485. isValid = true;
  2486. } catch (e) {
  2487. isValid = false;
  2488. }
  2489. return isValid;
  2490. };
  2491. const matcherWrapper = (callback, argsData, errorMessage) => {
  2492. let isMatched;
  2493. try {
  2494. isMatched = callback(argsData);
  2495. } catch (e) {
  2496. logger.error(getErrorMessage(e));
  2497. throw new Error(errorMessage);
  2498. }
  2499. return isMatched;
  2500. };
  2501. const getAbsolutePseudoError = (propDesc, pseudoName, pseudoArg) => {
  2502. return `${MATCHING_ELEMENT_ERROR_PREFIX} ${propDesc}, may be invalid :${pseudoName}() pseudo-class arg: '${pseudoArg}'`;
  2503. };
  2504. const isMatchedByAbsolutePseudo = (domElement, pseudoName, pseudoArg) => {
  2505. let argsData;
  2506. let errorMessage;
  2507. let callback;
  2508. switch (pseudoName) {
  2509. case CONTAINS_PSEUDO:
  2510. case HAS_TEXT_PSEUDO:
  2511. case ABP_CONTAINS_PSEUDO:
  2512. callback = isTextMatched;
  2513. argsData = {
  2514. pseudoName,
  2515. pseudoArg,
  2516. domElement,
  2517. };
  2518. errorMessage = getAbsolutePseudoError(
  2519. "text content",
  2520. pseudoName,
  2521. pseudoArg
  2522. );
  2523. break;
  2524. case MATCHES_CSS_PSEUDO:
  2525. case MATCHES_CSS_AFTER_PSEUDO:
  2526. case MATCHES_CSS_BEFORE_PSEUDO:
  2527. callback = isStyleMatched;
  2528. argsData = {
  2529. pseudoName,
  2530. pseudoArg,
  2531. domElement,
  2532. };
  2533. errorMessage = getAbsolutePseudoError("style", pseudoName, pseudoArg);
  2534. break;
  2535. case MATCHES_ATTR_PSEUDO_CLASS_MARKER:
  2536. callback = isAttributeMatched;
  2537. argsData = {
  2538. domElement,
  2539. pseudoName,
  2540. pseudoArg,
  2541. };
  2542. errorMessage = getAbsolutePseudoError(
  2543. "attributes",
  2544. pseudoName,
  2545. pseudoArg
  2546. );
  2547. break;
  2548. case MATCHES_PROPERTY_PSEUDO_CLASS_MARKER:
  2549. callback = isPropertyMatched;
  2550. argsData = {
  2551. domElement,
  2552. pseudoName,
  2553. pseudoArg,
  2554. };
  2555. errorMessage = getAbsolutePseudoError(
  2556. "properties",
  2557. pseudoName,
  2558. pseudoArg
  2559. );
  2560. break;
  2561. default:
  2562. throw new Error(`Unknown absolute pseudo-class :${pseudoName}()`);
  2563. }
  2564. return matcherWrapper(callback, argsData, errorMessage);
  2565. };
  2566. const findByAbsolutePseudoPseudo = {
  2567. nthAncestor: (domElements, rawPseudoArg, pseudoName) => {
  2568. const deep = getValidNumberAncestorArg(rawPseudoArg, pseudoName);
  2569. const ancestors = domElements
  2570. .map((domElement) => {
  2571. let ancestor = null;
  2572. try {
  2573. ancestor = getNthAncestor(domElement, deep, pseudoName);
  2574. } catch (e) {
  2575. logger.error(getErrorMessage(e));
  2576. }
  2577. return ancestor;
  2578. })
  2579. .filter(isHtmlElement);
  2580. return ancestors;
  2581. },
  2582. xpath: (domElements, rawPseudoArg) => {
  2583. const foundElements = domElements.map((domElement) => {
  2584. const result = [];
  2585. let xpathResult;
  2586. try {
  2587. xpathResult = document.evaluate(
  2588. rawPseudoArg,
  2589. domElement,
  2590. null,
  2591. window.XPathResult.UNORDERED_NODE_ITERATOR_TYPE,
  2592. null
  2593. );
  2594. } catch (e) {
  2595. logger.error(getErrorMessage(e));
  2596. throw new Error(
  2597. `Invalid argument of :xpath() pseudo-class: '${rawPseudoArg}'`
  2598. );
  2599. }
  2600. let node = xpathResult.iterateNext();
  2601. while (node) {
  2602. if (isHtmlElement(node)) {
  2603. result.push(node);
  2604. }
  2605. node = xpathResult.iterateNext();
  2606. }
  2607. return result;
  2608. });
  2609. return flatten(foundElements);
  2610. },
  2611. upward: (domElements, rawPseudoArg) => {
  2612. if (!validateStandardSelector(rawPseudoArg)) {
  2613. throw new Error(
  2614. `Invalid argument of :upward pseudo-class: '${rawPseudoArg}'`
  2615. );
  2616. }
  2617. const closestAncestors = domElements
  2618. .map((domElement) => {
  2619. const parent = domElement.parentElement;
  2620. if (!parent) {
  2621. return null;
  2622. }
  2623. return parent.closest(rawPseudoArg);
  2624. })
  2625. .filter(isHtmlElement);
  2626. return closestAncestors;
  2627. },
  2628. };
  2629. const scopeDirectChildren = `${SCOPE_CSS_PSEUDO_CLASS}${CHILD_COMBINATOR}`;
  2630. const scopeAnyChildren = `${SCOPE_CSS_PSEUDO_CLASS}${DESCENDANT_COMBINATOR}`;
  2631. const getFirstInnerRegularChild = (selectorNode, pseudoName) => {
  2632. return getFirstRegularChild(
  2633. selectorNode.children,
  2634. `RegularSelector is missing for :${pseudoName}() pseudo-class`
  2635. );
  2636. };
  2637. const hasRelativesBySelectorList = (argsData) => {
  2638. const { element, relativeSelectorList, pseudoName } = argsData;
  2639. return relativeSelectorList.children.every((selectorNode) => {
  2640. const relativeRegularSelector = getFirstInnerRegularChild(
  2641. selectorNode,
  2642. pseudoName
  2643. );
  2644. let specifiedSelector = "";
  2645. let rootElement = null;
  2646. const regularSelector = getNodeValue(relativeRegularSelector);
  2647. if (
  2648. regularSelector.startsWith(NEXT_SIBLING_COMBINATOR) ||
  2649. regularSelector.startsWith(SUBSEQUENT_SIBLING_COMBINATOR)
  2650. ) {
  2651. rootElement = element.parentElement;
  2652. const elementSelectorText = getElementSelectorDesc(element);
  2653. specifiedSelector = `${scopeDirectChildren}${elementSelectorText}${regularSelector}`;
  2654. } else if (regularSelector === ASTERISK) {
  2655. rootElement = element;
  2656. specifiedSelector = `${scopeAnyChildren}${ASTERISK}`;
  2657. } else {
  2658. specifiedSelector = `${scopeAnyChildren}${regularSelector}`;
  2659. rootElement = element;
  2660. }
  2661. if (!rootElement) {
  2662. throw new Error(
  2663. `Selection by :${pseudoName}() pseudo-class is not possible`
  2664. );
  2665. }
  2666. let relativeElements;
  2667. try {
  2668. relativeElements = getElementsForSelectorNode(
  2669. selectorNode,
  2670. rootElement,
  2671. specifiedSelector
  2672. );
  2673. } catch (e) {
  2674. logger.error(getErrorMessage(e));
  2675. throw new Error(
  2676. `Invalid selector for :${pseudoName}() pseudo-class: '${regularSelector}'`
  2677. );
  2678. }
  2679. return relativeElements.length > 0;
  2680. });
  2681. };
  2682. const isAnyElementBySelectorList = (argsData) => {
  2683. const { element, relativeSelectorList, pseudoName } = argsData;
  2684. return relativeSelectorList.children.some((selectorNode) => {
  2685. const relativeRegularSelector = getFirstInnerRegularChild(
  2686. selectorNode,
  2687. pseudoName
  2688. );
  2689. const rootElement = getParent(
  2690. element,
  2691. `Selection by :${pseudoName}() pseudo-class is not possible`
  2692. );
  2693. const specifiedSelector = `${scopeDirectChildren}${getNodeValue(
  2694. relativeRegularSelector
  2695. )}`;
  2696. let anyElements;
  2697. try {
  2698. anyElements = getElementsForSelectorNode(
  2699. selectorNode,
  2700. rootElement,
  2701. specifiedSelector
  2702. );
  2703. } catch (e) {
  2704. return false;
  2705. }
  2706. return anyElements.includes(element);
  2707. });
  2708. };
  2709. const notElementBySelectorList = (argsData) => {
  2710. const { element, relativeSelectorList, pseudoName } = argsData;
  2711. return relativeSelectorList.children.every((selectorNode) => {
  2712. const relativeRegularSelector = getFirstInnerRegularChild(
  2713. selectorNode,
  2714. pseudoName
  2715. );
  2716. const rootElement = getParent(
  2717. element,
  2718. `Selection by :${pseudoName}() pseudo-class is not possible`
  2719. );
  2720. const specifiedSelector = `${scopeDirectChildren}${getNodeValue(
  2721. relativeRegularSelector
  2722. )}`;
  2723. let anyElements;
  2724. try {
  2725. anyElements = getElementsForSelectorNode(
  2726. selectorNode,
  2727. rootElement,
  2728. specifiedSelector
  2729. );
  2730. } catch (e) {
  2731. logger.error(getErrorMessage(e));
  2732. throw new Error(
  2733. `Invalid selector for :${pseudoName}() pseudo-class: '${getNodeValue(
  2734. relativeRegularSelector
  2735. )}'`
  2736. );
  2737. }
  2738. return !anyElements.includes(element);
  2739. });
  2740. };
  2741. const getByRegularSelector = (
  2742. regularSelectorNode,
  2743. root,
  2744. specifiedSelector
  2745. ) => {
  2746. const selectorText = specifiedSelector
  2747. ? specifiedSelector
  2748. : getNodeValue(regularSelectorNode);
  2749. let selectedElements = [];
  2750. try {
  2751. selectedElements = Array.from(root.querySelectorAll(selectorText));
  2752. } catch (e) {
  2753. throw new Error(
  2754. `Error: unable to select by '${selectorText}' ${getErrorMessage(e)}`
  2755. );
  2756. }
  2757. return selectedElements;
  2758. };
  2759. const getByExtendedSelector = (domElements, extendedSelectorNode) => {
  2760. let foundElements = [];
  2761. const extendedPseudoClassNode = getPseudoClassNode(extendedSelectorNode);
  2762. const pseudoName = getNodeName(extendedPseudoClassNode);
  2763. if (isAbsolutePseudoClass(pseudoName)) {
  2764. const absolutePseudoArg = getNodeValue(
  2765. extendedPseudoClassNode,
  2766. `Missing arg for :${pseudoName}() pseudo-class`
  2767. );
  2768. if (pseudoName === NTH_ANCESTOR_PSEUDO_CLASS_MARKER) {
  2769. foundElements = findByAbsolutePseudoPseudo.nthAncestor(
  2770. domElements,
  2771. absolutePseudoArg,
  2772. pseudoName
  2773. );
  2774. } else if (pseudoName === XPATH_PSEUDO_CLASS_MARKER) {
  2775. try {
  2776. document.createExpression(absolutePseudoArg, null);
  2777. } catch (e) {
  2778. throw new Error(
  2779. `Invalid argument of :${pseudoName}() pseudo-class: '${absolutePseudoArg}'`
  2780. );
  2781. }
  2782. foundElements = findByAbsolutePseudoPseudo.xpath(
  2783. domElements,
  2784. absolutePseudoArg
  2785. );
  2786. } else if (pseudoName === UPWARD_PSEUDO_CLASS_MARKER) {
  2787. if (Number.isNaN(Number(absolutePseudoArg))) {
  2788. foundElements = findByAbsolutePseudoPseudo.upward(
  2789. domElements,
  2790. absolutePseudoArg
  2791. );
  2792. } else {
  2793. foundElements = findByAbsolutePseudoPseudo.nthAncestor(
  2794. domElements,
  2795. absolutePseudoArg,
  2796. pseudoName
  2797. );
  2798. }
  2799. } else {
  2800. foundElements = domElements.filter((element) => {
  2801. return isMatchedByAbsolutePseudo(
  2802. element,
  2803. pseudoName,
  2804. absolutePseudoArg
  2805. );
  2806. });
  2807. }
  2808. } else if (isRelativePseudoClass(pseudoName)) {
  2809. const relativeSelectorList = getRelativeSelectorListNode(
  2810. extendedPseudoClassNode
  2811. );
  2812. let relativePredicate;
  2813. switch (pseudoName) {
  2814. case HAS_PSEUDO_CLASS_MARKER:
  2815. case ABP_HAS_PSEUDO_CLASS_MARKER:
  2816. relativePredicate = (element) =>
  2817. hasRelativesBySelectorList({
  2818. element,
  2819. relativeSelectorList,
  2820. pseudoName,
  2821. });
  2822. break;
  2823. case IS_PSEUDO_CLASS_MARKER:
  2824. relativePredicate = (element) =>
  2825. isAnyElementBySelectorList({
  2826. element,
  2827. relativeSelectorList,
  2828. pseudoName,
  2829. });
  2830. break;
  2831. case NOT_PSEUDO_CLASS_MARKER:
  2832. relativePredicate = (element) =>
  2833. notElementBySelectorList({
  2834. element,
  2835. relativeSelectorList,
  2836. pseudoName,
  2837. });
  2838. break;
  2839. default:
  2840. throw new Error(`Unknown relative pseudo-class: '${pseudoName}'`);
  2841. }
  2842. foundElements = domElements.filter(relativePredicate);
  2843. } else {
  2844. throw new Error(`Unknown extended pseudo-class: '${pseudoName}'`);
  2845. }
  2846. return foundElements;
  2847. };
  2848. const getByFollowingRegularSelector = (domElements, regularSelectorNode) => {
  2849. let foundElements = [];
  2850. const value = getNodeValue(regularSelectorNode);
  2851. if (value.startsWith(CHILD_COMBINATOR)) {
  2852. foundElements = domElements.map((root) => {
  2853. const specifiedSelector = `${SCOPE_CSS_PSEUDO_CLASS}${value}`;
  2854. return getByRegularSelector(
  2855. regularSelectorNode,
  2856. root,
  2857. specifiedSelector
  2858. );
  2859. });
  2860. } else if (
  2861. value.startsWith(NEXT_SIBLING_COMBINATOR) ||
  2862. value.startsWith(SUBSEQUENT_SIBLING_COMBINATOR)
  2863. ) {
  2864. foundElements = domElements.map((element) => {
  2865. const rootElement = element.parentElement;
  2866. if (!rootElement) {
  2867. return [];
  2868. }
  2869. const elementSelectorText = getElementSelectorDesc(element);
  2870. const specifiedSelector = `${scopeDirectChildren}${elementSelectorText}${value}`;
  2871. const selected = getByRegularSelector(
  2872. regularSelectorNode,
  2873. rootElement,
  2874. specifiedSelector
  2875. );
  2876. return selected;
  2877. });
  2878. } else {
  2879. foundElements = domElements.map((root) => {
  2880. const specifiedSelector = `${scopeAnyChildren}${getNodeValue(
  2881. regularSelectorNode
  2882. )}`;
  2883. return getByRegularSelector(
  2884. regularSelectorNode,
  2885. root,
  2886. specifiedSelector
  2887. );
  2888. });
  2889. }
  2890. return flatten(foundElements);
  2891. };
  2892. const getElementsForSelectorNode = (
  2893. selectorNode,
  2894. root,
  2895. specifiedSelector
  2896. ) => {
  2897. let selectedElements = [];
  2898. let i = 0;
  2899. while (i < selectorNode.children.length) {
  2900. const selectorNodeChild = getItemByIndex(
  2901. selectorNode.children,
  2902. i,
  2903. "selectorNodeChild should be specified"
  2904. );
  2905. if (i === 0) {
  2906. selectedElements = getByRegularSelector(
  2907. selectorNodeChild,
  2908. root,
  2909. specifiedSelector
  2910. );
  2911. } else if (isExtendedSelectorNode(selectorNodeChild)) {
  2912. selectedElements = getByExtendedSelector(
  2913. selectedElements,
  2914. selectorNodeChild
  2915. );
  2916. } else if (isRegularSelectorNode(selectorNodeChild)) {
  2917. selectedElements = getByFollowingRegularSelector(
  2918. selectedElements,
  2919. selectorNodeChild
  2920. );
  2921. }
  2922. i += 1;
  2923. }
  2924. return selectedElements;
  2925. };
  2926. const selectElementsByAst = function (ast) {
  2927. let doc =
  2928. arguments.length > 1 && arguments[1] !== undefined
  2929. ? arguments[1]
  2930. : document;
  2931. const selectedElements = [];
  2932. ast.children.forEach((selectorNode) => {
  2933. selectedElements.push(...getElementsForSelectorNode(selectorNode, doc));
  2934. });
  2935. const uniqueElements = [...new Set(flatten(selectedElements))];
  2936. return uniqueElements;
  2937. };
  2938. class ExtCssDocument {
  2939. constructor() {
  2940. this.astCache = new Map();
  2941. }
  2942. saveAstToCache(selector, ast) {
  2943. this.astCache.set(selector, ast);
  2944. }
  2945. getAstFromCache(selector) {
  2946. const cachedAst = this.astCache.get(selector) || null;
  2947. return cachedAst;
  2948. }
  2949. getSelectorAst(selector) {
  2950. let ast = this.getAstFromCache(selector);
  2951. if (!ast) {
  2952. ast = parse(selector);
  2953. }
  2954. this.saveAstToCache(selector, ast);
  2955. return ast;
  2956. }
  2957. querySelectorAll(selector) {
  2958. const ast = this.getSelectorAst(selector);
  2959. return selectElementsByAst(ast);
  2960. }
  2961. }
  2962. const extCssDocument = new ExtCssDocument();
  2963. const getObjectFromEntries = (entries) => {
  2964. const object = {};
  2965. entries.forEach((el) => {
  2966. const [key, value] = el;
  2967. object[key] = value;
  2968. });
  2969. return object;
  2970. };
  2971. const DEBUG_PSEUDO_PROPERTY_KEY = "debug";
  2972. const parseRemoveSelector = (rawSelector) => {
  2973. const VALID_REMOVE_MARKER = `${COLON}${REMOVE_PSEUDO_MARKER}${BRACKET.PARENTHESES.LEFT}${BRACKET.PARENTHESES.RIGHT}`;
  2974. const INVALID_REMOVE_MARKER = `${COLON}${REMOVE_PSEUDO_MARKER}${BRACKET.PARENTHESES.LEFT}`;
  2975. let selector;
  2976. let shouldRemove = false;
  2977. const firstIndex = rawSelector.indexOf(VALID_REMOVE_MARKER);
  2978. if (firstIndex === 0) {
  2979. throw new Error(
  2980. `${REMOVE_ERROR_PREFIX.NO_TARGET_SELECTOR}: '${rawSelector}'`
  2981. );
  2982. } else if (firstIndex > 0) {
  2983. if (firstIndex !== rawSelector.lastIndexOf(VALID_REMOVE_MARKER)) {
  2984. throw new Error(
  2985. `${REMOVE_ERROR_PREFIX.MULTIPLE_USAGE}: '${rawSelector}'`
  2986. );
  2987. } else if (firstIndex + VALID_REMOVE_MARKER.length < rawSelector.length) {
  2988. throw new Error(
  2989. `${REMOVE_ERROR_PREFIX.INVALID_POSITION}: '${rawSelector}'`
  2990. );
  2991. } else {
  2992. selector = rawSelector.substring(0, firstIndex);
  2993. shouldRemove = true;
  2994. }
  2995. } else if (rawSelector.includes(INVALID_REMOVE_MARKER)) {
  2996. throw new Error(
  2997. `${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${rawSelector}'`
  2998. );
  2999. } else {
  3000. selector = rawSelector;
  3001. }
  3002. const stylesOfSelector = shouldRemove
  3003. ? [
  3004. {
  3005. property: REMOVE_PSEUDO_MARKER,
  3006. value: PSEUDO_PROPERTY_POSITIVE_VALUE,
  3007. },
  3008. ]
  3009. : [];
  3010. return {
  3011. selector,
  3012. stylesOfSelector,
  3013. };
  3014. };
  3015. const parseSelectorRulePart = (selectorBuffer, extCssDoc) => {
  3016. let selector = selectorBuffer.trim();
  3017. if (selector.startsWith(AT_RULE_MARKER)) {
  3018. throw new Error(`${NO_AT_RULE_ERROR_PREFIX}: '${selector}'.`);
  3019. }
  3020. let removeSelectorData;
  3021. try {
  3022. removeSelectorData = parseRemoveSelector(selector);
  3023. } catch (e) {
  3024. logger.error(getErrorMessage(e));
  3025. throw new Error(`${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`);
  3026. }
  3027. let stylesOfSelector = [];
  3028. let success = false;
  3029. let ast;
  3030. try {
  3031. selector = removeSelectorData.selector;
  3032. stylesOfSelector = removeSelectorData.stylesOfSelector;
  3033. ast = extCssDoc.getSelectorAst(selector);
  3034. success = true;
  3035. } catch (e) {
  3036. success = false;
  3037. }
  3038. return {
  3039. success,
  3040. selector,
  3041. ast,
  3042. stylesOfSelector,
  3043. };
  3044. };
  3045. const createRawResultsMap = () => {
  3046. return new Map();
  3047. };
  3048. const saveToRawResults = (rawResults, rawRuleData) => {
  3049. const { selector, ast, rawStyles } = rawRuleData;
  3050. if (!rawStyles) {
  3051. throw new Error(`No style declaration for selector: '${selector}'`);
  3052. }
  3053. if (!ast) {
  3054. throw new Error(`No ast parsed for selector: '${selector}'`);
  3055. }
  3056. const storedRuleData = rawResults.get(selector);
  3057. if (!storedRuleData) {
  3058. rawResults.set(selector, {
  3059. ast,
  3060. styles: rawStyles,
  3061. });
  3062. } else {
  3063. storedRuleData.styles.push(...rawStyles);
  3064. }
  3065. };
  3066. const isRemoveSetInStyles = (styles) => {
  3067. return styles.some((s) => {
  3068. return (
  3069. s.property === REMOVE_PSEUDO_MARKER &&
  3070. s.value === PSEUDO_PROPERTY_POSITIVE_VALUE
  3071. );
  3072. });
  3073. };
  3074. const getDebugStyleValue = (styles) => {
  3075. const debugStyle = styles.find((s) => {
  3076. return s.property === DEBUG_PSEUDO_PROPERTY_KEY;
  3077. });
  3078. return debugStyle === null || debugStyle === void 0
  3079. ? void 0
  3080. : debugStyle.value;
  3081. };
  3082. const prepareRuleData = (rawRuleData) => {
  3083. const { selector, ast, rawStyles } = rawRuleData;
  3084. if (!ast) {
  3085. throw new Error(`AST should be parsed for selector: '${selector}'`);
  3086. }
  3087. if (!rawStyles) {
  3088. throw new Error(`Styles should be parsed for selector: '${selector}'`);
  3089. }
  3090. const ruleData = {
  3091. selector,
  3092. ast,
  3093. };
  3094. const debugValue = getDebugStyleValue(rawStyles);
  3095. const shouldRemove = isRemoveSetInStyles(rawStyles);
  3096. let styles = rawStyles;
  3097. if (debugValue) {
  3098. styles = rawStyles.filter(
  3099. (s) => s.property !== DEBUG_PSEUDO_PROPERTY_KEY
  3100. );
  3101. if (
  3102. debugValue === PSEUDO_PROPERTY_POSITIVE_VALUE ||
  3103. debugValue === DEBUG_PSEUDO_PROPERTY_GLOBAL_VALUE
  3104. ) {
  3105. ruleData.debug = debugValue;
  3106. }
  3107. }
  3108. if (shouldRemove) {
  3109. ruleData.style = {
  3110. [REMOVE_PSEUDO_MARKER]: PSEUDO_PROPERTY_POSITIVE_VALUE,
  3111. };
  3112. const contentStyle = styles.find(
  3113. (s) => s.property === CONTENT_CSS_PROPERTY
  3114. );
  3115. if (contentStyle) {
  3116. ruleData.style[CONTENT_CSS_PROPERTY] = contentStyle.value;
  3117. }
  3118. } else {
  3119. if (styles.length > 0) {
  3120. const stylesAsEntries = styles.map((style) => {
  3121. const { property, value } = style;
  3122. return [property, value];
  3123. });
  3124. const preparedStyleData = getObjectFromEntries(stylesAsEntries);
  3125. ruleData.style = preparedStyleData;
  3126. }
  3127. }
  3128. return ruleData;
  3129. };
  3130. const combineRulesData = (rawResults) => {
  3131. const results = [];
  3132. rawResults.forEach((value, key) => {
  3133. const selector = key;
  3134. const { ast, styles: rawStyles } = value;
  3135. results.push(
  3136. prepareRuleData({
  3137. selector,
  3138. ast,
  3139. rawStyles,
  3140. })
  3141. );
  3142. });
  3143. return results;
  3144. };
  3145. const tokenizeStyleBlock = (rawStyle) => {
  3146. const styleDeclaration = rawStyle.trim();
  3147. return tokenize(styleDeclaration, SUPPORTED_STYLE_DECLARATION_MARKS);
  3148. };
  3149. const DECLARATION_PART = {
  3150. PROPERTY: "property",
  3151. VALUE: "value",
  3152. };
  3153. const isValueQuotesOpen = (context) => {
  3154. return context.bufferValue !== "" && context.valueQuoteMark !== null;
  3155. };
  3156. const collectStyle = (context) => {
  3157. context.styles.push({
  3158. property: context.bufferProperty.trim(),
  3159. value: context.bufferValue.trim(),
  3160. });
  3161. context.bufferProperty = "";
  3162. context.bufferValue = "";
  3163. };
  3164. const processPropertyToken = (context, styleBlock, token) => {
  3165. const { value: tokenValue } = token;
  3166. switch (token.type) {
  3167. case TOKEN_TYPE.WORD:
  3168. if (context.bufferProperty.length > 0) {
  3169. throw new Error(
  3170. `Invalid style property in style block: '${styleBlock}'`
  3171. );
  3172. }
  3173. context.bufferProperty += tokenValue;
  3174. break;
  3175. case TOKEN_TYPE.MARK:
  3176. if (tokenValue === COLON) {
  3177. if (context.bufferProperty.trim().length === 0) {
  3178. throw new Error(
  3179. `Missing style property before ':' in style block: '${styleBlock}'`
  3180. );
  3181. }
  3182. context.bufferProperty = context.bufferProperty.trim();
  3183. context.processing = DECLARATION_PART.VALUE;
  3184. } else if (WHITE_SPACE_CHARACTERS.includes(tokenValue));
  3185. else {
  3186. throw new Error(
  3187. `Invalid style declaration in style block: '${styleBlock}'`
  3188. );
  3189. }
  3190. break;
  3191. default:
  3192. throw new Error(
  3193. `Unsupported style property character: '${tokenValue}' in style block: '${styleBlock}'`
  3194. );
  3195. }
  3196. };
  3197. const processValueToken = (context, styleBlock, token) => {
  3198. const { value: tokenValue } = token;
  3199. if (token.type === TOKEN_TYPE.WORD) {
  3200. context.bufferValue += tokenValue;
  3201. } else {
  3202. switch (tokenValue) {
  3203. case COLON:
  3204. if (!isValueQuotesOpen(context)) {
  3205. throw new Error(
  3206. `Invalid style value for property '${context.bufferProperty}' in style block: '${styleBlock}'`
  3207. );
  3208. }
  3209. context.bufferValue += tokenValue;
  3210. break;
  3211. case SEMICOLON:
  3212. if (isValueQuotesOpen(context)) {
  3213. context.bufferValue += tokenValue;
  3214. } else {
  3215. collectStyle(context);
  3216. context.processing = DECLARATION_PART.PROPERTY;
  3217. }
  3218. break;
  3219. case SINGLE_QUOTE:
  3220. case DOUBLE_QUOTE:
  3221. if (context.valueQuoteMark === null) {
  3222. context.valueQuoteMark = tokenValue;
  3223. } else if (
  3224. !context.bufferValue.endsWith(BACKSLASH) &&
  3225. context.valueQuoteMark === tokenValue
  3226. ) {
  3227. context.valueQuoteMark = null;
  3228. }
  3229. context.bufferValue += tokenValue;
  3230. break;
  3231. case BACKSLASH:
  3232. if (!isValueQuotesOpen(context)) {
  3233. throw new Error(
  3234. `Invalid style value for property '${context.bufferProperty}' in style block: '${styleBlock}'`
  3235. );
  3236. }
  3237. context.bufferValue += tokenValue;
  3238. break;
  3239. case SPACE:
  3240. case TAB:
  3241. case CARRIAGE_RETURN:
  3242. case LINE_FEED:
  3243. case FORM_FEED:
  3244. if (context.bufferValue.length > 0) {
  3245. context.bufferValue += tokenValue;
  3246. }
  3247. break;
  3248. default:
  3249. throw new Error(`Unknown style declaration token: '${tokenValue}'`);
  3250. }
  3251. }
  3252. };
  3253. const parseStyleBlock = (rawStyleBlock) => {
  3254. const styleBlock = rawStyleBlock.trim();
  3255. const tokens = tokenizeStyleBlock(styleBlock);
  3256. const context = {
  3257. processing: DECLARATION_PART.PROPERTY,
  3258. styles: [],
  3259. bufferProperty: "",
  3260. bufferValue: "",
  3261. valueQuoteMark: null,
  3262. };
  3263. let i = 0;
  3264. while (i < tokens.length) {
  3265. const token = tokens[i];
  3266. if (!token) {
  3267. break;
  3268. }
  3269. if (context.processing === DECLARATION_PART.PROPERTY) {
  3270. processPropertyToken(context, styleBlock, token);
  3271. } else if (context.processing === DECLARATION_PART.VALUE) {
  3272. processValueToken(context, styleBlock, token);
  3273. } else {
  3274. throw new Error("Style declaration parsing failed");
  3275. }
  3276. i += 1;
  3277. }
  3278. if (isValueQuotesOpen(context)) {
  3279. throw new Error(
  3280. `Unbalanced style declaration quotes in style block: '${styleBlock}'`
  3281. );
  3282. }
  3283. if (context.bufferProperty.length > 0) {
  3284. if (context.bufferValue.length === 0) {
  3285. throw new Error(
  3286. `Missing style value for property '${context.bufferProperty}' in style block '${styleBlock}'`
  3287. );
  3288. }
  3289. collectStyle(context);
  3290. }
  3291. if (context.styles.length === 0) {
  3292. throw new Error(STYLE_ERROR_PREFIX.NO_STYLE);
  3293. }
  3294. return context.styles;
  3295. };
  3296. const getLeftCurlyBracketIndexes = (cssRule) => {
  3297. const indexes = [];
  3298. for (let i = 0; i < cssRule.length; i += 1) {
  3299. if (cssRule[i] === BRACKET.CURLY.LEFT) {
  3300. indexes.push(i);
  3301. }
  3302. }
  3303. return indexes;
  3304. };
  3305. const parseRule = (rawCssRule, extCssDoc) => {
  3306. var _rawRuleData$selector;
  3307. const cssRule = rawCssRule.trim();
  3308. if (
  3309. cssRule.includes(`${SLASH}${ASTERISK}`) &&
  3310. cssRule.includes(`${ASTERISK}${SLASH}`)
  3311. ) {
  3312. throw new Error(STYLE_ERROR_PREFIX.NO_COMMENT);
  3313. }
  3314. const leftCurlyBracketIndexes = getLeftCurlyBracketIndexes(cssRule);
  3315. if (getFirst(leftCurlyBracketIndexes) === 0) {
  3316. throw new Error(NO_SELECTOR_ERROR_PREFIX);
  3317. }
  3318. let selectorData;
  3319. if (
  3320. leftCurlyBracketIndexes.length > 0 &&
  3321. !cssRule.includes(BRACKET.CURLY.RIGHT)
  3322. ) {
  3323. throw new Error(
  3324. `${STYLE_ERROR_PREFIX.NO_STYLE} OR ${STYLE_ERROR_PREFIX.UNCLOSED_STYLE}`
  3325. );
  3326. }
  3327. if (
  3328. leftCurlyBracketIndexes.length === 0 ||
  3329. !cssRule.includes(BRACKET.CURLY.RIGHT)
  3330. ) {
  3331. try {
  3332. selectorData = parseSelectorRulePart(cssRule, extCssDoc);
  3333. if (selectorData.success) {
  3334. var _selectorData$stylesO;
  3335. if (
  3336. ((_selectorData$stylesO = selectorData.stylesOfSelector) === null ||
  3337. _selectorData$stylesO === void 0
  3338. ? void 0
  3339. : _selectorData$stylesO.length) === 0
  3340. ) {
  3341. throw new Error(STYLE_ERROR_PREFIX.NO_STYLE_OR_REMOVE);
  3342. }
  3343. return {
  3344. selector: selectorData.selector.trim(),
  3345. ast: selectorData.ast,
  3346. rawStyles: selectorData.stylesOfSelector,
  3347. };
  3348. } else {
  3349. throw new Error("Invalid selector");
  3350. }
  3351. } catch (e) {
  3352. throw new Error(getErrorMessage(e));
  3353. }
  3354. }
  3355. let selectorBuffer;
  3356. let styleBlockBuffer;
  3357. const rawRuleData = {
  3358. selector: "",
  3359. };
  3360. for (let i = leftCurlyBracketIndexes.length - 1; i > -1; i -= 1) {
  3361. const index = leftCurlyBracketIndexes[i];
  3362. if (!index) {
  3363. throw new Error(
  3364. `Impossible to continue, no '{' to process for rule: '${cssRule}'`
  3365. );
  3366. }
  3367. selectorBuffer = cssRule.slice(0, index);
  3368. styleBlockBuffer = cssRule.slice(index + 1, cssRule.length - 1);
  3369. selectorData = parseSelectorRulePart(selectorBuffer, extCssDoc);
  3370. if (selectorData.success) {
  3371. var _rawRuleData$rawStyle;
  3372. rawRuleData.selector = selectorData.selector.trim();
  3373. rawRuleData.ast = selectorData.ast;
  3374. rawRuleData.rawStyles = selectorData.stylesOfSelector;
  3375. const parsedStyles = parseStyleBlock(styleBlockBuffer);
  3376. (_rawRuleData$rawStyle = rawRuleData.rawStyles) === null ||
  3377. _rawRuleData$rawStyle === void 0
  3378. ? void 0
  3379. : _rawRuleData$rawStyle.push(...parsedStyles);
  3380. break;
  3381. } else {
  3382. continue;
  3383. }
  3384. }
  3385. if (
  3386. ((_rawRuleData$selector = rawRuleData.selector) === null ||
  3387. _rawRuleData$selector === void 0
  3388. ? void 0
  3389. : _rawRuleData$selector.length) === 0
  3390. ) {
  3391. throw new Error("Selector in not valid");
  3392. }
  3393. return rawRuleData;
  3394. };
  3395. const parseRules$1 = (rawCssRules, extCssDoc) => {
  3396. const rawResults = createRawResultsMap();
  3397. const warnings = [];
  3398. const uniqueRules = [...new Set(rawCssRules.map((r) => r.trim()))];
  3399. uniqueRules.forEach((rule) => {
  3400. try {
  3401. saveToRawResults(rawResults, parseRule(rule, extCssDoc));
  3402. } catch (e) {
  3403. const errorMessage = getErrorMessage(e);
  3404. warnings.push(`'${rule}' - error: '${errorMessage}'`);
  3405. }
  3406. });
  3407. if (warnings.length > 0) {
  3408. logger.info(`Invalid rules:\n ${warnings.join("\n ")}`);
  3409. }
  3410. return combineRulesData(rawResults);
  3411. };
  3412. const REGEXP_DECLARATION_END = /[;}]/g;
  3413. const REGEXP_DECLARATION_DIVIDER = /[;:}]/g;
  3414. const REGEXP_NON_WHITESPACE = /\S/g;
  3415. const restoreRuleAcc = (context) => {
  3416. context.rawRuleData = {
  3417. selector: "",
  3418. };
  3419. };
  3420. const parseSelectorPart = (context, extCssDoc) => {
  3421. let selector = context.selectorBuffer.trim();
  3422. if (selector.startsWith(AT_RULE_MARKER)) {
  3423. throw new Error(`${NO_AT_RULE_ERROR_PREFIX}: '${selector}'.`);
  3424. }
  3425. let removeSelectorData;
  3426. try {
  3427. removeSelectorData = parseRemoveSelector(selector);
  3428. } catch (e) {
  3429. logger.error(getErrorMessage(e));
  3430. throw new Error(`${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`);
  3431. }
  3432. if (context.nextIndex === -1) {
  3433. if (selector === removeSelectorData.selector) {
  3434. throw new Error(
  3435. `${STYLE_ERROR_PREFIX.NO_STYLE_OR_REMOVE}: '${context.cssToParse}'`
  3436. );
  3437. }
  3438. context.cssToParse = "";
  3439. }
  3440. let stylesOfSelector = [];
  3441. let success = false;
  3442. let ast;
  3443. try {
  3444. selector = removeSelectorData.selector;
  3445. stylesOfSelector = removeSelectorData.stylesOfSelector;
  3446. ast = extCssDoc.getSelectorAst(selector);
  3447. success = true;
  3448. } catch (e) {
  3449. success = false;
  3450. }
  3451. if (context.nextIndex > 0) {
  3452. context.cssToParse = context.cssToParse.slice(context.nextIndex);
  3453. }
  3454. return {
  3455. success,
  3456. selector,
  3457. ast,
  3458. stylesOfSelector,
  3459. };
  3460. };
  3461. const parseUntilClosingBracket = (context, styles) => {
  3462. REGEXP_DECLARATION_DIVIDER.lastIndex = context.nextIndex;
  3463. let match = REGEXP_DECLARATION_DIVIDER.exec(context.cssToParse);
  3464. if (match === null) {
  3465. throw new Error(
  3466. `${STYLE_ERROR_PREFIX.INVALID_STYLE}: '${context.cssToParse}'`
  3467. );
  3468. }
  3469. let matchPos = match.index;
  3470. let matched = match[0];
  3471. if (matched === BRACKET.CURLY.RIGHT) {
  3472. const declarationChunk = context.cssToParse.slice(
  3473. context.nextIndex,
  3474. matchPos
  3475. );
  3476. if (declarationChunk.trim().length === 0) {
  3477. if (styles.length === 0) {
  3478. throw new Error(
  3479. `${STYLE_ERROR_PREFIX.NO_STYLE}: '${context.cssToParse}'`
  3480. );
  3481. }
  3482. } else {
  3483. throw new Error(
  3484. `${STYLE_ERROR_PREFIX.INVALID_STYLE}: '${context.cssToParse}'`
  3485. );
  3486. }
  3487. return matchPos;
  3488. }
  3489. if (matched === COLON) {
  3490. const colonIndex = matchPos;
  3491. REGEXP_DECLARATION_END.lastIndex = colonIndex;
  3492. match = REGEXP_DECLARATION_END.exec(context.cssToParse);
  3493. if (match === null) {
  3494. throw new Error(
  3495. `${STYLE_ERROR_PREFIX.UNCLOSED_STYLE}: '${context.cssToParse}'`
  3496. );
  3497. }
  3498. matchPos = match.index;
  3499. matched = match[0];
  3500. const property = context.cssToParse
  3501. .slice(context.nextIndex, colonIndex)
  3502. .trim();
  3503. if (property.length === 0) {
  3504. throw new Error(
  3505. `${STYLE_ERROR_PREFIX.NO_PROPERTY}: '${context.cssToParse}'`
  3506. );
  3507. }
  3508. const value = context.cssToParse.slice(colonIndex + 1, matchPos).trim();
  3509. if (value.length === 0) {
  3510. throw new Error(
  3511. `${STYLE_ERROR_PREFIX.NO_VALUE}: '${context.cssToParse}'`
  3512. );
  3513. }
  3514. styles.push({
  3515. property,
  3516. value,
  3517. });
  3518. if (matched === BRACKET.CURLY.RIGHT) {
  3519. return matchPos;
  3520. }
  3521. }
  3522. context.cssToParse = context.cssToParse.slice(matchPos + 1);
  3523. context.nextIndex = 0;
  3524. return parseUntilClosingBracket(context, styles);
  3525. };
  3526. const parseNextStyle = (context) => {
  3527. const styles = [];
  3528. const styleEndPos = parseUntilClosingBracket(context, styles);
  3529. REGEXP_NON_WHITESPACE.lastIndex = styleEndPos + 1;
  3530. const match = REGEXP_NON_WHITESPACE.exec(context.cssToParse);
  3531. if (match === null) {
  3532. context.cssToParse = "";
  3533. return styles;
  3534. }
  3535. const matchPos = match.index;
  3536. context.cssToParse = context.cssToParse.slice(matchPos);
  3537. return styles;
  3538. };
  3539. const parseStylesheet = (rawStylesheet, extCssDoc) => {
  3540. const stylesheet = rawStylesheet.trim();
  3541. if (
  3542. stylesheet.includes(`${SLASH}${ASTERISK}`) &&
  3543. stylesheet.includes(`${ASTERISK}${SLASH}`)
  3544. ) {
  3545. throw new Error(
  3546. `${STYLE_ERROR_PREFIX.NO_COMMENT} in stylesheet: '${stylesheet}'`
  3547. );
  3548. }
  3549. const context = {
  3550. isSelector: true,
  3551. nextIndex: 0,
  3552. cssToParse: stylesheet,
  3553. selectorBuffer: "",
  3554. rawRuleData: {
  3555. selector: "",
  3556. },
  3557. };
  3558. const rawResults = createRawResultsMap();
  3559. let selectorData;
  3560. while (context.cssToParse) {
  3561. if (context.isSelector) {
  3562. context.nextIndex = context.cssToParse.indexOf(BRACKET.CURLY.LEFT);
  3563. if (context.selectorBuffer.length === 0 && context.nextIndex === 0) {
  3564. throw new Error(
  3565. `${STYLE_ERROR_PREFIX.NO_SELECTOR}: '${context.cssToParse}'`
  3566. );
  3567. }
  3568. if (context.nextIndex === -1) {
  3569. context.selectorBuffer = context.cssToParse;
  3570. } else {
  3571. context.selectorBuffer += context.cssToParse.slice(
  3572. 0,
  3573. context.nextIndex
  3574. );
  3575. }
  3576. selectorData = parseSelectorPart(context, extCssDoc);
  3577. if (selectorData.success) {
  3578. context.rawRuleData.selector = selectorData.selector.trim();
  3579. context.rawRuleData.ast = selectorData.ast;
  3580. context.rawRuleData.rawStyles = selectorData.stylesOfSelector;
  3581. context.isSelector = false;
  3582. if (context.nextIndex === -1) {
  3583. saveToRawResults(rawResults, context.rawRuleData);
  3584. restoreRuleAcc(context);
  3585. } else {
  3586. context.nextIndex = 1;
  3587. context.selectorBuffer = "";
  3588. }
  3589. } else {
  3590. context.selectorBuffer += BRACKET.CURLY.LEFT;
  3591. context.cssToParse = context.cssToParse.slice(1);
  3592. }
  3593. } else {
  3594. var _context$rawRuleData$;
  3595. const parsedStyles = parseNextStyle(context);
  3596. (_context$rawRuleData$ = context.rawRuleData.rawStyles) === null ||
  3597. _context$rawRuleData$ === void 0
  3598. ? void 0
  3599. : _context$rawRuleData$.push(...parsedStyles);
  3600. saveToRawResults(rawResults, context.rawRuleData);
  3601. context.nextIndex = 0;
  3602. restoreRuleAcc(context);
  3603. context.isSelector = true;
  3604. }
  3605. }
  3606. return combineRulesData(rawResults);
  3607. };
  3608. const isNumber = (arg) => {
  3609. return typeof arg === "number" && !Number.isNaN(arg);
  3610. };
  3611. class ThrottleWrapper {
  3612. constructor(callback) {
  3613. this.callback = callback;
  3614. this.executeCallback = this.executeCallback.bind(this);
  3615. }
  3616. executeCallback() {
  3617. this.lastRunTime = performance.now();
  3618. if (isNumber(this.timerId)) {
  3619. clearTimeout(this.timerId);
  3620. delete this.timerId;
  3621. }
  3622. this.callback();
  3623. }
  3624. run() {
  3625. if (isNumber(this.timerId)) {
  3626. return;
  3627. }
  3628. if (isNumber(this.lastRunTime)) {
  3629. const elapsedTime = performance.now() - this.lastRunTime;
  3630. if (elapsedTime < ThrottleWrapper.THROTTLE_DELAY_MS) {
  3631. this.timerId = window.setTimeout(
  3632. this.executeCallback,
  3633. ThrottleWrapper.THROTTLE_DELAY_MS - elapsedTime
  3634. );
  3635. return;
  3636. }
  3637. }
  3638. this.timerId = window.setTimeout(this.executeCallback);
  3639. }
  3640. }
  3641. _defineProperty(ThrottleWrapper, "THROTTLE_DELAY_MS", 150);
  3642. const LAST_EVENT_TIMEOUT_MS = 10;
  3643. const IGNORED_EVENTS = ["mouseover", "mouseleave", "mouseenter", "mouseout"];
  3644. const SUPPORTED_EVENTS = [
  3645. "keydown",
  3646. "keypress",
  3647. "keyup",
  3648. "auxclick",
  3649. "click",
  3650. "contextmenu",
  3651. "dblclick",
  3652. "mousedown",
  3653. "mouseenter",
  3654. "mouseleave",
  3655. "mousemove",
  3656. "mouseover",
  3657. "mouseout",
  3658. "mouseup",
  3659. "pointerlockchange",
  3660. "pointerlockerror",
  3661. "select",
  3662. "wheel",
  3663. ];
  3664. const SAFARI_PROBLEMATIC_EVENTS = ["wheel"];
  3665. class EventTracker {
  3666. constructor() {
  3667. _defineProperty(this, "getLastEventType", () => this.lastEventType);
  3668. _defineProperty(this, "getTimeSinceLastEvent", () => {
  3669. if (!this.lastEventTime) {
  3670. return null;
  3671. }
  3672. return Date.now() - this.lastEventTime;
  3673. });
  3674. this.trackedEvents = isSafariBrowser
  3675. ? SUPPORTED_EVENTS.filter(
  3676. (event) => !SAFARI_PROBLEMATIC_EVENTS.includes(event)
  3677. )
  3678. : SUPPORTED_EVENTS;
  3679. this.trackedEvents.forEach((eventName) => {
  3680. document.documentElement.addEventListener(
  3681. eventName,
  3682. this.trackEvent,
  3683. true
  3684. );
  3685. });
  3686. }
  3687. trackEvent(event) {
  3688. this.lastEventType = event.type;
  3689. this.lastEventTime = Date.now();
  3690. }
  3691. isIgnoredEventType() {
  3692. const lastEventType = this.getLastEventType();
  3693. const sinceLastEventTime = this.getTimeSinceLastEvent();
  3694. return (
  3695. !!lastEventType &&
  3696. IGNORED_EVENTS.includes(lastEventType) &&
  3697. !!sinceLastEventTime &&
  3698. sinceLastEventTime < LAST_EVENT_TIMEOUT_MS
  3699. );
  3700. }
  3701. stopTracking() {
  3702. this.trackedEvents.forEach((eventName) => {
  3703. document.documentElement.removeEventListener(
  3704. eventName,
  3705. this.trackEvent,
  3706. true
  3707. );
  3708. });
  3709. }
  3710. }
  3711. function shouldIgnoreMutations(mutations) {
  3712. return !mutations.some((m) => m.type !== "attributes");
  3713. }
  3714. function observeDocument(context) {
  3715. if (context.isDomObserved) {
  3716. return;
  3717. }
  3718. context.isDomObserved = true;
  3719. context.domMutationObserver = new natives.MutationObserver((mutations) => {
  3720. if (!mutations || mutations.length === 0) {
  3721. return;
  3722. }
  3723. const eventTracker = new EventTracker();
  3724. if (
  3725. eventTracker.isIgnoredEventType() &&
  3726. shouldIgnoreMutations(mutations)
  3727. ) {
  3728. return;
  3729. }
  3730. context.eventTracker = eventTracker;
  3731. context.scheduler.run();
  3732. });
  3733. context.domMutationObserver.observe(document, {
  3734. childList: true,
  3735. subtree: true,
  3736. attributes: true,
  3737. attributeFilter: ["id", "class"],
  3738. });
  3739. }
  3740. function disconnectDocument(context) {
  3741. if (!context.isDomObserved) {
  3742. return;
  3743. }
  3744. context.isDomObserved = false;
  3745. if (context.domMutationObserver) {
  3746. context.domMutationObserver.disconnect();
  3747. }
  3748. if (context.eventTracker) {
  3749. context.eventTracker.stopTracking();
  3750. }
  3751. }
  3752. const CONTENT_ATTR_PREFIX_REGEXP = /^("|')adguard.+?/;
  3753. const removeElement = (context, affectedElement) => {
  3754. const { node } = affectedElement;
  3755. affectedElement.removed = true;
  3756. const elementSelector = getElementSelectorPath(node);
  3757. const elementRemovalsCounter =
  3758. context.removalsStatistic[elementSelector] || 0;
  3759. if (elementRemovalsCounter > MAX_STYLE_PROTECTION_COUNT) {
  3760. logger.error(
  3761. `ExtendedCss: infinite loop protection for selector: '${elementSelector}'`
  3762. );
  3763. return;
  3764. }
  3765. if (node.parentElement) {
  3766. node.parentElement.removeChild(node);
  3767. context.removalsStatistic[elementSelector] = elementRemovalsCounter + 1;
  3768. }
  3769. };
  3770. const setStyleToElement = (node, style) => {
  3771. if (!(node instanceof HTMLElement)) {
  3772. return;
  3773. }
  3774. Object.keys(style).forEach((prop) => {
  3775. if (typeof node.style.getPropertyValue(prop.toString()) !== "undefined") {
  3776. let value = style[prop];
  3777. if (!value) {
  3778. return;
  3779. }
  3780. if (
  3781. prop === CONTENT_CSS_PROPERTY &&
  3782. value.match(CONTENT_ATTR_PREFIX_REGEXP)
  3783. ) {
  3784. return;
  3785. }
  3786. value = removeSuffix(value.trim(), "!important").trim();
  3787. node.style.setProperty(prop, value, "important");
  3788. }
  3789. });
  3790. };
  3791. const isIAffectedElement = (affectedElement) => {
  3792. return (
  3793. "node" in affectedElement &&
  3794. "rules" in affectedElement &&
  3795. affectedElement.rules instanceof Array
  3796. );
  3797. };
  3798. const isAffectedElement = (affectedElement) => {
  3799. return (
  3800. "node" in affectedElement &&
  3801. "originalStyle" in affectedElement &&
  3802. "rules" in affectedElement &&
  3803. affectedElement.rules instanceof Array
  3804. );
  3805. };
  3806. const applyStyle = (context, rawAffectedElement) => {
  3807. if (rawAffectedElement.protectionObserver) {
  3808. return;
  3809. }
  3810. let affectedElement;
  3811. if (context.beforeStyleApplied) {
  3812. if (!isIAffectedElement(rawAffectedElement)) {
  3813. throw new Error(
  3814. "Returned IAffectedElement should have 'node' and 'rules' properties"
  3815. );
  3816. }
  3817. affectedElement = context.beforeStyleApplied(rawAffectedElement);
  3818. if (!affectedElement) {
  3819. throw new Error(
  3820. "Callback 'beforeStyleApplied' should return IAffectedElement"
  3821. );
  3822. }
  3823. } else {
  3824. affectedElement = rawAffectedElement;
  3825. }
  3826. if (!isAffectedElement(affectedElement)) {
  3827. throw new Error(
  3828. "Returned IAffectedElement should have 'node' and 'rules' properties"
  3829. );
  3830. }
  3831. const { node, rules } = affectedElement;
  3832. for (let i = 0; i < rules.length; i += 1) {
  3833. const rule = rules[i];
  3834. const selector =
  3835. rule === null || rule === void 0 ? void 0 : rule.selector;
  3836. const style = rule === null || rule === void 0 ? void 0 : rule.style;
  3837. const debug = rule === null || rule === void 0 ? void 0 : rule.debug;
  3838. if (style) {
  3839. if (style[REMOVE_PSEUDO_MARKER] === PSEUDO_PROPERTY_POSITIVE_VALUE) {
  3840. removeElement(context, affectedElement);
  3841. return;
  3842. }
  3843. setStyleToElement(node, style);
  3844. } else if (!debug) {
  3845. throw new Error(
  3846. `No style declaration in rule for selector: '${selector}'`
  3847. );
  3848. }
  3849. }
  3850. };
  3851. const revertStyle = (affectedElement) => {
  3852. if (affectedElement.protectionObserver) {
  3853. affectedElement.protectionObserver.disconnect();
  3854. }
  3855. affectedElement.node.style.cssText = affectedElement.originalStyle;
  3856. };
  3857. class ExtMutationObserver {
  3858. constructor(protectionCallback) {
  3859. this.styleProtectionCount = 0;
  3860. this.observer = new natives.MutationObserver((mutations) => {
  3861. if (!mutations.length) {
  3862. return;
  3863. }
  3864. this.styleProtectionCount += 1;
  3865. protectionCallback(mutations, this);
  3866. });
  3867. }
  3868. observe(target, options) {
  3869. if (this.styleProtectionCount < MAX_STYLE_PROTECTION_COUNT) {
  3870. this.observer.observe(target, options);
  3871. } else {
  3872. logger.error("ExtendedCss: infinite loop protection for style");
  3873. }
  3874. }
  3875. disconnect() {
  3876. this.observer.disconnect();
  3877. }
  3878. }
  3879. const PROTECTION_OBSERVER_OPTIONS = {
  3880. attributes: true,
  3881. attributeOldValue: true,
  3882. attributeFilter: ["style"],
  3883. };
  3884. const createProtectionCallback = (styles) => {
  3885. const protectionCallback = (mutations, extObserver) => {
  3886. if (!mutations[0]) {
  3887. return;
  3888. }
  3889. const { target } = mutations[0];
  3890. extObserver.disconnect();
  3891. styles.forEach((style) => {
  3892. setStyleToElement(target, style);
  3893. });
  3894. extObserver.observe(target, PROTECTION_OBSERVER_OPTIONS);
  3895. };
  3896. return protectionCallback;
  3897. };
  3898. const protectStyleAttribute = (node, rules) => {
  3899. if (!natives.MutationObserver) {
  3900. return null;
  3901. }
  3902. const styles = [];
  3903. rules.forEach((ruleData) => {
  3904. const { style } = ruleData;
  3905. if (style) {
  3906. styles.push(style);
  3907. }
  3908. });
  3909. const protectionObserver = new ExtMutationObserver(
  3910. createProtectionCallback(styles)
  3911. );
  3912. protectionObserver.observe(node, PROTECTION_OBSERVER_OPTIONS);
  3913. return protectionObserver;
  3914. };
  3915. const STATS_DECIMAL_DIGITS_COUNT = 4;
  3916. class TimingStats {
  3917. constructor() {
  3918. this.appliesTimings = [];
  3919. this.appliesCount = 0;
  3920. this.timingsSum = 0;
  3921. this.meanTiming = 0;
  3922. this.squaredSum = 0;
  3923. this.standardDeviation = 0;
  3924. }
  3925. push(elapsedTimeMs) {
  3926. this.appliesTimings.push(elapsedTimeMs);
  3927. this.appliesCount += 1;
  3928. this.timingsSum += elapsedTimeMs;
  3929. this.meanTiming = this.timingsSum / this.appliesCount;
  3930. this.squaredSum += elapsedTimeMs * elapsedTimeMs;
  3931. this.standardDeviation = Math.sqrt(
  3932. this.squaredSum / this.appliesCount - Math.pow(this.meanTiming, 2)
  3933. );
  3934. }
  3935. }
  3936. const beautifyTimingNumber = (timestamp) => {
  3937. return Number(timestamp.toFixed(STATS_DECIMAL_DIGITS_COUNT));
  3938. };
  3939. const beautifyTimings = (rawTimings) => {
  3940. return {
  3941. appliesTimings: rawTimings.appliesTimings.map((t) =>
  3942. beautifyTimingNumber(t)
  3943. ),
  3944. appliesCount: beautifyTimingNumber(rawTimings.appliesCount),
  3945. timingsSum: beautifyTimingNumber(rawTimings.timingsSum),
  3946. meanTiming: beautifyTimingNumber(rawTimings.meanTiming),
  3947. standardDeviation: beautifyTimingNumber(rawTimings.standardDeviation),
  3948. };
  3949. };
  3950. const printTimingInfo = (context) => {
  3951. if (context.areTimingsPrinted) {
  3952. return;
  3953. }
  3954. context.areTimingsPrinted = true;
  3955. const timingsLogData = {};
  3956. context.parsedRules.forEach((ruleData) => {
  3957. if (ruleData.timingStats) {
  3958. const { selector, style, debug, matchedElements } = ruleData;
  3959. if (!style && !debug) {
  3960. throw new Error(
  3961. `Rule should have style declaration for selector: '${selector}'`
  3962. );
  3963. }
  3964. const selectorData = {
  3965. selectorParsed: selector,
  3966. timings: beautifyTimings(ruleData.timingStats),
  3967. };
  3968. if (
  3969. style &&
  3970. style[REMOVE_PSEUDO_MARKER] === PSEUDO_PROPERTY_POSITIVE_VALUE
  3971. ) {
  3972. selectorData.removed = true;
  3973. } else {
  3974. selectorData.styleApplied = style || null;
  3975. selectorData.matchedElements = matchedElements;
  3976. }
  3977. timingsLogData[selector] = selectorData;
  3978. }
  3979. });
  3980. if (Object.keys(timingsLogData).length === 0) {
  3981. return;
  3982. }
  3983. logger.info(
  3984. "[ExtendedCss] Timings in milliseconds for %o:\n%o",
  3985. window.location.href,
  3986. timingsLogData
  3987. );
  3988. };
  3989. const findAffectedElement = (affElements, domNode) => {
  3990. return affElements.find((affEl) => affEl.node === domNode);
  3991. };
  3992. const applyRule = (context, ruleData) => {
  3993. const isDebuggingMode = !!ruleData.debug || context.debug;
  3994. let startTime;
  3995. if (isDebuggingMode) {
  3996. startTime = performance.now();
  3997. }
  3998. const { ast } = ruleData;
  3999. const nodes = [];
  4000. try {
  4001. nodes.push(...selectElementsByAst(ast));
  4002. } catch (e) {
  4003. if (context.debug) {
  4004. logger.error(getErrorMessage(e));
  4005. }
  4006. }
  4007. nodes.forEach((node) => {
  4008. let affectedElement = findAffectedElement(context.affectedElements, node);
  4009. if (affectedElement) {
  4010. affectedElement.rules.push(ruleData);
  4011. applyStyle(context, affectedElement);
  4012. } else {
  4013. const originalStyle = node.style.cssText;
  4014. affectedElement = {
  4015. node,
  4016. rules: [ruleData],
  4017. originalStyle,
  4018. protectionObserver: null,
  4019. };
  4020. applyStyle(context, affectedElement);
  4021. context.affectedElements.push(affectedElement);
  4022. }
  4023. });
  4024. if (isDebuggingMode && startTime) {
  4025. const elapsedTimeMs = performance.now() - startTime;
  4026. if (!ruleData.timingStats) {
  4027. ruleData.timingStats = new TimingStats();
  4028. }
  4029. ruleData.timingStats.push(elapsedTimeMs);
  4030. }
  4031. return nodes;
  4032. };
  4033. const applyRules = (context) => {
  4034. const newSelectedElements = [];
  4035. disconnectDocument(context);
  4036. context.parsedRules.forEach((ruleData) => {
  4037. const nodes = applyRule(context, ruleData);
  4038. Array.prototype.push.apply(newSelectedElements, nodes);
  4039. if (ruleData.debug) {
  4040. ruleData.matchedElements = nodes;
  4041. }
  4042. });
  4043. let affLength = context.affectedElements.length;
  4044. while (affLength) {
  4045. const affectedElement = context.affectedElements[affLength - 1];
  4046. if (!affectedElement) {
  4047. break;
  4048. }
  4049. if (!newSelectedElements.includes(affectedElement.node)) {
  4050. revertStyle(affectedElement);
  4051. context.affectedElements.splice(affLength - 1, 1);
  4052. } else if (!affectedElement.removed) {
  4053. if (!affectedElement.protectionObserver) {
  4054. affectedElement.protectionObserver = protectStyleAttribute(
  4055. affectedElement.node,
  4056. affectedElement.rules
  4057. );
  4058. }
  4059. }
  4060. affLength -= 1;
  4061. }
  4062. observeDocument(context);
  4063. printTimingInfo(context);
  4064. };
  4065. class ExtendedCss {
  4066. constructor(configuration) {
  4067. if (!configuration) {
  4068. throw new Error("ExtendedCss configuration should be provided.");
  4069. }
  4070. this.applyRulesCallbackListener =
  4071. this.applyRulesCallbackListener.bind(this);
  4072. this.context = {
  4073. beforeStyleApplied: configuration.beforeStyleApplied,
  4074. debug: false,
  4075. affectedElements: [],
  4076. isDomObserved: false,
  4077. removalsStatistic: {},
  4078. parsedRules: [],
  4079. scheduler: new ThrottleWrapper(this.applyRulesCallbackListener),
  4080. };
  4081. if (!isBrowserSupported()) {
  4082. logger.error("Browser is not supported by ExtendedCss");
  4083. return;
  4084. }
  4085. if (!configuration.styleSheet && !configuration.cssRules) {
  4086. throw new Error(
  4087. "ExtendedCss configuration should have 'styleSheet' or 'cssRules' defined."
  4088. );
  4089. }
  4090. if (configuration.styleSheet) {
  4091. try {
  4092. this.context.parsedRules.push(
  4093. ...parseStylesheet(configuration.styleSheet, extCssDocument)
  4094. );
  4095. } catch (e) {
  4096. throw new Error(
  4097. `Pass the rules as configuration.cssRules since configuration.styleSheet cannot be parsed because of: '${getErrorMessage(
  4098. e
  4099. )}'`
  4100. );
  4101. }
  4102. }
  4103. if (configuration.cssRules) {
  4104. this.context.parsedRules.push(
  4105. ...parseRules$1(configuration.cssRules, extCssDocument)
  4106. );
  4107. }
  4108. this.context.debug =
  4109. configuration.debug ||
  4110. this.context.parsedRules.some((ruleData) => {
  4111. return ruleData.debug === DEBUG_PSEUDO_PROPERTY_GLOBAL_VALUE;
  4112. });
  4113. if (
  4114. this.context.beforeStyleApplied &&
  4115. typeof this.context.beforeStyleApplied !== "function"
  4116. ) {
  4117. throw new Error(
  4118. `Invalid configuration. Type of 'beforeStyleApplied' should be a function, received: '${typeof this
  4119. .context.beforeStyleApplied}'`
  4120. );
  4121. }
  4122. }
  4123. applyRulesCallbackListener() {
  4124. applyRules(this.context);
  4125. }
  4126. init() {
  4127. nativeTextContent.setGetter();
  4128. }
  4129. apply() {
  4130. applyRules(this.context);
  4131. if (document.readyState !== "complete") {
  4132. document.addEventListener(
  4133. "DOMContentLoaded",
  4134. this.applyRulesCallbackListener,
  4135. false
  4136. );
  4137. }
  4138. }
  4139. dispose() {
  4140. disconnectDocument(this.context);
  4141. this.context.affectedElements.forEach((el) => {
  4142. revertStyle(el);
  4143. });
  4144. document.removeEventListener(
  4145. "DOMContentLoaded",
  4146. this.applyRulesCallbackListener,
  4147. false
  4148. );
  4149. }
  4150. getAffectedElements() {
  4151. return this.context.affectedElements;
  4152. }
  4153. static query(selector) {
  4154. let noTiming =
  4155. arguments.length > 1 && arguments[1] !== undefined
  4156. ? arguments[1]
  4157. : true;
  4158. if (typeof selector !== "string") {
  4159. throw new Error("Selector should be defined as a string.");
  4160. }
  4161. const start = performance.now();
  4162. try {
  4163. return extCssDocument.querySelectorAll(selector);
  4164. } finally {
  4165. const end = performance.now();
  4166. if (!noTiming) {
  4167. logger.info(
  4168. `[ExtendedCss] Elapsed: ${Math.round((end - start) * 1000)} μs.`
  4169. );
  4170. }
  4171. }
  4172. }
  4173. static validate(inputSelector) {
  4174. try {
  4175. const { selector } = parseRemoveSelector(inputSelector);
  4176. ExtendedCss.query(selector);
  4177. return {
  4178. ok: true,
  4179. error: null,
  4180. };
  4181. } catch (e) {
  4182. const error = `Error: Invalid selector: '${inputSelector}' -- ${getErrorMessage(
  4183. e
  4184. )}`;
  4185. return {
  4186. ok: false,
  4187. error,
  4188. };
  4189. }
  4190. }
  4191. }
  4192.  
  4193. function canApplyCss(type) {
  4194. return (
  4195. (data.appliedLevel & (type >= 2 ? 2 : 1)) == 0 &&
  4196. data[styleBoxes[type]].length > 0
  4197. );
  4198. }
  4199.  
  4200. function getCustomRules(saveHash) {
  4201. return __awaiter(this, void 0, void 0, function* () {
  4202. return yield Promise.resolve(String(saveHash));
  4203. });
  4204. }
  4205. function initRules(apply) {
  4206. let abpRules = {};
  4207. data.receivedRules = "";
  4208. getCustomRules(true);
  4209. Object.keys(abpRules).forEach((name) => {
  4210. data.receivedRules += "\n" + abpRules[name];
  4211. });
  4212. data.allRules = data.customRules + data.receivedRules;
  4213. if (apply) splitRules();
  4214. return data.receivedRules.length;
  4215. }
  4216. function styleApplyExec(type) {
  4217. if (canApplyCss(type)) {
  4218. const csss = data[styleBoxes[type]];
  4219. new ExtendedCss({
  4220. styleSheet: csss.replaceAll(/\/\*\s*\d.+?\s*\*\//g, ""),
  4221. }).apply();
  4222. if (!(type % 2 == 1)) addStyle(csss);
  4223. }
  4224. }
  4225. function styleApply() {
  4226. for (let type = 0; type < 4; type++) styleApplyExec(type);
  4227. }
  4228. function parseRules() {
  4229. function addRule(rule, exten) {
  4230. const [full, selector] = ruleToCss(rule, data.preset);
  4231. const index = exten + (rule.generic ? 0 : 2);
  4232. const checkResult = ExtendedCss.validate(selector);
  4233. if (checkResult.ok) {
  4234. data[styleBoxes[index]] += full;
  4235. data.appliedCount++;
  4236. } else {
  4237. console.error("选择器检查错误:", rule, checkResult.error);
  4238. }
  4239. }
  4240. styleBoxes.forEach((box) => {
  4241. data[box] = "";
  4242. });
  4243. [data.styles, data.extStyles, data.selectors, data.extSelectors].forEach(
  4244. (r, t) => {
  4245. const sels = new Set();
  4246. r.white.forEach((obj) => !sels.has(obj.sel) && sels.add(obj.sel));
  4247. r.black
  4248. .filter((obj) => !sels.has(obj.sel) && sels.add(obj.sel))
  4249. .forEach((s) => addRule(s, t % 2));
  4250. }
  4251. );
  4252. if (!data.saved) styleApply();
  4253. }
  4254. function splitRules() {
  4255. dataBoxes.forEach((box) => {
  4256. data[box] = makeRuleBox();
  4257. });
  4258. data.allRules.split("\n").forEach((rule) => {
  4259. {
  4260. const ruleObj = ruleLoader(rule);
  4261. if (typeof ruleObj !== "undefined") {
  4262. if (
  4263. ruleObj.black === "black" &&
  4264. data[dataBoxes[ruleObj.type]].white.includes(ruleObj)
  4265. )
  4266. return;
  4267. data[dataBoxes[ruleObj.type]][ruleObj.black].push(ruleObj);
  4268. }
  4269. }
  4270. });
  4271. parseRules();
  4272. }
  4273.  
  4274. function main() {
  4275. return __awaiter(this, void 0, void 0, function* () {
  4276. yield getCustomRules(false);
  4277. {
  4278. if (initRules(false) === 0) {
  4279. initRules(true);
  4280. }
  4281. splitRules();
  4282. }
  4283. });
  4284. }
  4285. function runOnce(key, func) {
  4286. if (key in cat.unsafeWindow) return Promise.reject();
  4287. cat.unsafeWindow[key] = true;
  4288. return func();
  4289. }
  4290. {
  4291. runOnce(data.mutex, main);
  4292. }
  4293. })({
  4294. GM_info: typeof GM_info == "object" ? GM_info : {},
  4295. unsafeWindow: typeof unsafeWindow == "object" ? unsafeWindow : window,
  4296. GM_addStyle: typeof GM_addStyle == "function" ? GM_addStyle : undefined,
  4297. });

QingJ © 2025

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