搜索引擎去广告

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

目前为 2024-04-25 提交的版本。查看 最新版本

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

QingJ © 2025

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