套壳油猴的广告拦截脚本

将 ABP 中的元素隐藏规则转换为 CSS 使用

当前为 2023-07-10 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name AdBlock Script for WebView
  3. // @name:zh-CN 套壳油猴的广告拦截脚本
  4. // @author Lemon399
  5. // @version 2.6.3
  6. // @description Parse ABP Cosmetic rules to CSS and apply it.
  7. // @description:zh-CN 将 ABP 中的元素隐藏规则转换为 CSS 使用
  8. // @resource jiekouAD https://raw.fastgit.ixmu.net/damengzhu/banad/main/jiekouAD.txt
  9. // @resource CSSRule https://raw.fastgit.ixmu.net/damengzhu/abpmerge/main/CSSRule.txt
  10. // @match *://*/*
  11. // @run-at document-start
  12. // @grant unsafeWindow
  13. // @grant GM_registerMenuCommand
  14. // @grant GM.registerMenuCommand
  15. // @grant GM_unregisterMenuCommand
  16. // @grant GM.unregisterMenuCommand
  17. // @grant GM_getValue
  18. // @grant GM.getValue
  19. // @grant GM_deleteValue
  20. // @grant GM.deleteValue
  21. // @grant GM_setValue
  22. // @grant GM.setValue
  23. // @grant GM_addStyle
  24. // @grant GM.addStyle
  25. // @grant GM_xmlhttpRequest
  26. // @grant GM.xmlHttpRequest
  27. // @grant GM_getResourceText
  28. // @grant GM.getResourceText
  29. // @grant GM_download
  30. // @grant GM.download
  31. // @grant GM_listValues
  32. // @grant GM.listValues
  33. // @namespace https://lemon399-bitbucket-io.vercel.app/
  34. // @source https://gitee.com/lemon399/tampermonkey-cli/tree/master/projects/abp_parse
  35. // @source https://bitbucket.org/lemon399/tampermonkey-cli/src/master/projects/abp_parse/
  36. // @connect raw.fastgit.ixmu.net
  37. // @copyright GPL-3.0
  38. // @license GPL-3.0
  39. // ==/UserScript==
  40.  
  41. (function () {
  42. "use strict";
  43.  
  44. const $presets = {
  45. defaultRules: `
  46. ! 不支持的规则和开头为 ! 的行会忽略
  47. !
  48. ! 由于语法限制,此处规则中
  49. ! 一个反斜杠需要改成两个,像这样 \\
  50. `,
  51. userConfig: {
  52. css: `{
  53. display: none !important;
  54. width: 0 !important;
  55. height: 0 !important;
  56. }`,
  57. timeout: 10000,
  58. headTimeout: 2000,
  59. tryCount: 5,
  60. tryTimeout: 500,
  61. },
  62. onlineRules: [
  63. {
  64. 标识: `jiekouAD`,
  65. 地址: `https://raw.fastgit.ixmu.net/damengzhu/banad/main/jiekouAD.txt`,
  66. 在线更新: true,
  67. 筛选后存储: true,
  68. },
  69. {
  70. 标识: `CSSRule`,
  71. 地址: `https://raw.fastgit.ixmu.net/damengzhu/abpmerge/main/CSSRule.txt`,
  72. 在线更新: true,
  73. 筛选后存储: false,
  74. },
  75. ],
  76. };
  77.  
  78. /* ==UserConfig==
  79. 配置:
  80. css:
  81. title: 隐藏 CSS 规则
  82. description: 隐藏广告使用的 CSS 规则
  83. type: textarea
  84. rows: 7
  85. default: |-
  86. {
  87. display: none !important;
  88. width: 0 !important;
  89. height: 0 !important;
  90. }
  91. timeout:
  92. title: 规则下载超时
  93. description: 更新规则时,规则下载超时时间
  94. type: number
  95. default: 10000
  96. min: 0
  97. unit: 毫秒
  98. headTimeout:
  99. title: 获取规则信息超时
  100. description: 更新规则时,获取规则信息 (HEAD 请求) 超时时间
  101. type: number
  102. default: 2000
  103. min: 0
  104. unit: 毫秒
  105. tryCount:
  106. title: CSS 注入尝试次数
  107. description: 某些框架会重建页面,需要多次注入,只有检测到 CSS 不存在时才会尝试再次注入
  108. type: number
  109. default: 5
  110. min: 0
  111. unit: 次
  112. tryTimeout:
  113. title: CSS 注入尝试间隔
  114. description: 两次注入尝试的间隔时间
  115. type: number
  116. default: 500
  117. min: 100
  118. unit: 毫秒
  119. ==/UserConfig== */
  120.  
  121. /* eslint-disable no-redeclare, no-unused-vars, require-yield */
  122. /* global GM_info, GM, unsafeWindow, GM_registerMenuCommand, GM_unregisterMenuCommand, GM_getValue, GM_deleteValue, GM_setValue, GM_addStyle, GM_xmlhttpRequest, GM_getResourceText, GM_download, GM_listValues */
  123.  
  124. let $listeners = [],
  125. $hasStorEvListener = false;
  126.  
  127. const $polyfills = {
  128. // 以下 polyfills 修改自 NullMonkey,使用 MPL-2.0 发布
  129. /* This Source Code Form is subject to the terms of the
  130. * Mozilla Public License, v. 2.0. If a copy of the MPL
  131. * was not distributed with this file, You can obtain
  132. * one at https://mozilla.org/MPL/2.0/. */
  133. GM_info:
  134. typeof GM_info == "object"
  135. ? GM_info
  136. : {
  137. script: {
  138. author: "Lemon399",
  139. copyright: "GPL-3.0",
  140. description: "Parse ABP Cosmetic rules to CSS and apply it.",
  141. downloadURL: null,
  142. excludes: [],
  143. excludeMatches: [],
  144. grant: [
  145. "unsafeWindow",
  146. "GM_registerMenuCommand",
  147. "GM.registerMenuCommand",
  148. "GM_unregisterMenuCommand",
  149. "GM.unregisterMenuCommand",
  150. "GM_getValue",
  151. "GM.getValue",
  152. "GM_deleteValue",
  153. "GM.deleteValue",
  154. "GM_setValue",
  155. "GM.setValue",
  156. "GM_addStyle",
  157. "GM.addStyle",
  158. "GM_xmlhttpRequest",
  159. "GM.xmlHttpRequest",
  160. "GM_getResourceText",
  161. "GM.getResourceText",
  162. "GM_download",
  163. "GM.download",
  164. "GM_listValues",
  165. "GM.listValues",
  166. ],
  167. homepage: null,
  168. icon: null,
  169. icon64: null,
  170. includes: [],
  171. matches: ["*://*/*"],
  172. name: "AdBlock Script for WebView",
  173. namespace: "https://lemon399-bitbucket-io.vercel.app/",
  174. noframes: false,
  175. "run-at": "document-start",
  176. resources: [
  177. {
  178. name: "jiekouAD",
  179. url: "https://raw.fastgit.ixmu.net/damengzhu/banad/main/jiekouAD.txt",
  180. },
  181. {
  182. name: "CSSRule",
  183. url: "https://raw.fastgit.ixmu.net/damengzhu/abpmerge/main/CSSRule.txt",
  184. },
  185. ],
  186. supportURL: null,
  187. unwrap: false,
  188. updateURL: null,
  189. version: "2.6.3",
  190. webRequest: null,
  191. },
  192. scriptWillUpdate: false,
  193. },
  194. parseValue: function parseValue(stored) {
  195. const value =
  196. typeof stored == "string" &&
  197. stored.startsWith("[") &&
  198. stored.endsWith("]")
  199. ? JSON.parse(stored)[0]
  200. : void 0;
  201. return value === "__$NaN"
  202. ? NaN
  203. : value === "__$UdF"
  204. ? undefined
  205. : value === "__$FnT"
  206. ? Infinity
  207. : value === "__$XnT"
  208. ? -Infinity
  209. : value;
  210. },
  211. unsafeWindow: typeof unsafeWindow == "object" ? unsafeWindow : window,
  212. GM_registerMenuCommand:
  213. typeof GM_registerMenuCommand == "function"
  214. ? GM_registerMenuCommand
  215. : void 0,
  216. GM_unregisterMenuCommand:
  217. typeof GM_unregisterMenuCommand == "function"
  218. ? GM_unregisterMenuCommand
  219. : void 0,
  220. GM_getValue:
  221. typeof GM_getValue == "function"
  222. ? GM_getValue
  223. : function DM_getValue(key, defaultValue) {
  224. const stor = window.localStorage.getItem(
  225. "$DMValue$AdBlock Script for WebView$" + key
  226. );
  227. return typeof stor == "string" &&
  228. stor.startsWith("[") &&
  229. stor.endsWith("]")
  230. ? $polyfills.parseValue(stor)
  231. : defaultValue;
  232. },
  233. GM_deleteValue:
  234. typeof GM_deleteValue == "function"
  235. ? GM_deleteValue
  236. : function DM_deleteValue(key) {
  237. $listeners.forEach((listenerArray, id) => {
  238. if (listenerArray[0] === key) {
  239. const oldValue = $polyfills.GM_getValue(key);
  240. listenerArray[1].call(
  241. {
  242. id,
  243. key,
  244. cb: listenerArray[1],
  245. },
  246. key,
  247. oldValue,
  248. undefined,
  249. false
  250. );
  251. }
  252. });
  253. window.localStorage.removeItem(
  254. "$DMValue$AdBlock Script for WebView$" + key
  255. );
  256. },
  257. GM_setValue:
  258. typeof GM_setValue == "function"
  259. ? GM_setValue
  260. : function DM_setValue(key, value) {
  261. const packed = JSON.stringify([
  262. typeof value == "function"
  263. ? value.toString()
  264. : typeof value == "number" && isNaN(value)
  265. ? "__$NaN"
  266. : typeof value == "number" && !isFinite(value)
  267. ? value > 0
  268. ? "__$FnT"
  269. : "__$XnT"
  270. : typeof value == "undefined"
  271. ? "__$UdF"
  272. : typeof value == "bigint"
  273. ? value.toString()
  274. : value,
  275. ]);
  276. $listeners.forEach((listenerArray, id) => {
  277. if (listenerArray[0] === key) {
  278. const oldValue = $polyfills.GM_getValue(key);
  279. listenerArray[1].call(
  280. {
  281. id,
  282. key,
  283. cb: listenerArray[1],
  284. },
  285. key,
  286. oldValue,
  287. value,
  288. false
  289. );
  290. }
  291. });
  292. window.localStorage.setItem(
  293. "$DMValue$AdBlock Script for WebView$" + key,
  294. packed
  295. );
  296. },
  297. GM_addStyle:
  298. typeof GM_addStyle == "function"
  299. ? GM_addStyle
  300. : function DM_addStyle(css) {
  301. const styleEl = document.createElement("style");
  302. styleEl.innerText = css;
  303. (
  304. document.head ||
  305. document.body ||
  306. document.documentElement
  307. ).appendChild(styleEl);
  308. return styleEl;
  309. },
  310. GM_xmlhttpRequest:
  311. typeof GM_xmlhttpRequest == "function" ? GM_xmlhttpRequest : void 0,
  312. GM_getResourceText:
  313. typeof GM_getResourceText == "function" ? GM_getResourceText : void 0,
  314. GM_download:
  315. // 以下浏览器的 GM_download 不支持 blob: 需要使用 Polyfill
  316. typeof GM_download == "function" &&
  317. // X 浏览器
  318. !GM_download.toString().includes("mbrowser.GM_download") &&
  319. // Via 浏览器
  320. !GM_download.toString().includes("via_gm.download") &&
  321. // MDM 浏览器
  322. !(
  323. typeof window.moe == "object" &&
  324. typeof window.moe.download == "function"
  325. ) &&
  326. // 海阔世界 / 嗅觉
  327. !GM_download.toString().includes("window.open") &&
  328. // Rains 浏览器
  329. !Array.isArray(GM_download.toString().match(/load\(\) {};$/))
  330. ? GM_download
  331. : function DM_download(objOrURL, filename) {
  332. var _a;
  333. const linkEl = document.createElement("a");
  334. if (typeof objOrURL == "object") {
  335. linkEl.href = objOrURL.url;
  336. linkEl.download = objOrURL.name;
  337. linkEl.onclick =
  338. (_a = objOrURL.onload) !== null && _a !== void 0 ? _a : null;
  339. } else {
  340. linkEl.href = objOrURL;
  341. linkEl.download =
  342. filename !== null && filename !== void 0 ? filename : "";
  343. }
  344. linkEl.style.cssText = "position:absolute;top:-100%";
  345. document.body.appendChild(linkEl);
  346. setTimeout(() => {
  347. linkEl.click();
  348. linkEl.remove();
  349. }, 0);
  350. return {
  351. abort: () => void 0,
  352. };
  353. },
  354. GM_listValues:
  355. typeof GM_listValues == "function"
  356. ? GM_listValues
  357. : function DM_listValues() {
  358. const keysArray = [];
  359. for (let i = 0; i < window.localStorage.length; i++) {
  360. const key = window.localStorage.key(i);
  361. if (
  362. key === null || key === void 0
  363. ? void 0
  364. : key.startsWith("$DMValue$AdBlock Script for WebView$")
  365. )
  366. keysArray.push(
  367. key.replace("$DMValue$AdBlock Script for WebView$", "")
  368. );
  369. }
  370. return keysArray;
  371. },
  372. GM:
  373. typeof GM == "object"
  374. ? GM
  375. : {
  376. getValue: function DM_getValue4(...args) {
  377. return Promise.resolve($polyfills.GM_getValue(...args));
  378. },
  379. deleteValue: function DM_deleteValue4(...args) {
  380. return Promise.resolve($polyfills.GM_deleteValue(...args));
  381. },
  382. setValue: function DM_setValue4(...args) {
  383. return Promise.resolve($polyfills.GM_setValue(...args));
  384. },
  385. addStyle: function DM_addStyle4(...args) {
  386. return Promise.resolve($polyfills.GM_addStyle(...args));
  387. },
  388. download: function DM_download4(...args) {
  389. return Promise.resolve($polyfills.GM_download(...args));
  390. },
  391. listValues: function DM_listValues4(...args) {
  392. return Promise.resolve($polyfills.GM_listValues(...args));
  393. },
  394. },
  395. // polyfills 结束
  396. };
  397.  
  398. (function (preset, tm) {
  399. "use strict";
  400.  
  401. /******************************************************************************
  402. Copyright (c) Microsoft Corporation.
  403. Permission to use, copy, modify, and/or distribute this software for any
  404. purpose with or without fee is hereby granted.
  405. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  406. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  407. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  408. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  409. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  410. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  411. PERFORMANCE OF THIS SOFTWARE.
  412. ***************************************************************************** */
  413. /* global Reflect, Promise, SuppressedError, Symbol */
  414. function __awaiter(thisArg, _arguments, P, generator) {
  415. function adopt(value) {
  416. return value instanceof P
  417. ? value
  418. : new P(function (resolve) {
  419. resolve(value);
  420. });
  421. }
  422. return new (P || (P = Promise))(function (resolve, reject) {
  423. function fulfilled(value) {
  424. try {
  425. step(generator.next(value));
  426. } catch (e) {
  427. reject(e);
  428. }
  429. }
  430. function rejected(value) {
  431. try {
  432. step(generator["throw"](value));
  433. } catch (e) {
  434. reject(e);
  435. }
  436. }
  437. function step(result) {
  438. result.done
  439. ? resolve(result.value)
  440. : adopt(result.value).then(fulfilled, rejected);
  441. }
  442. step((generator = generator.apply(thisArg, _arguments || [])).next());
  443. });
  444. }
  445. typeof SuppressedError === "function"
  446. ? SuppressedError
  447. : function (error, suppressed, message) {
  448. var e = new Error(message);
  449. return (
  450. (e.name = "SuppressedError"),
  451. (e.error = error),
  452. (e.suppressed = suppressed),
  453. e
  454. );
  455. };
  456. var _a, _b, _c;
  457. function makeRuleBox() {
  458. return {
  459. black: [],
  460. white: [],
  461. };
  462. }
  463. const data = {
  464. isFrame: tm.unsafeWindow.self !== tm.unsafeWindow.top,
  465. isClean: false,
  466. disabled: false,
  467. saved: false,
  468. update: true,
  469. updating: false,
  470. alertLog: false,
  471. receivedRules: "",
  472. customRules:
  473. preset.defaultRules +
  474. ("\n" +
  475. ((_c =
  476. (_b =
  477. (_a = tm.GM_info.script) === null || _a === void 0
  478. ? void 0
  479. : _a.options) === null || _b === void 0
  480. ? void 0
  481. : _b.comment) !== null && _c !== void 0
  482. ? _c
  483. : "")),
  484. allRules: "",
  485. genHideCss: "",
  486. genExtraCss: "",
  487. spcHideCss: "",
  488. spcExtraCss: "",
  489. selectors: makeRuleBox(),
  490. extSelectors: makeRuleBox(),
  491. styles: makeRuleBox(),
  492. extStyles: makeRuleBox(),
  493. bRules: [],
  494. appliedLevel: 0,
  495. appliedCount: 0,
  496. mutex: "__lemon__abp__parser__$__",
  497. preset: preset.userConfig.css,
  498. timeout: preset.userConfig.timeout,
  499. headTimeout: preset.userConfig.headTimeout,
  500. tryCount: preset.userConfig.tryCount,
  501. tryTimeout: preset.userConfig.tryTimeout,
  502. };
  503. const defaultValues = {
  504. get black() {
  505. return "";
  506. },
  507. get rules() {
  508. return {};
  509. },
  510. get css() {
  511. return {
  512. needUpdate: true,
  513. genHideCss: "",
  514. genExtraCss: "",
  515. spcHideCss: "",
  516. spcExtraCss: "",
  517. };
  518. },
  519. get time() {
  520. return "0/0/0 0:0:0";
  521. },
  522. get etags() {
  523. return {};
  524. },
  525. get brules() {
  526. return [];
  527. },
  528. get hash() {
  529. return "";
  530. },
  531. };
  532. const values = {
  533. black(value) {
  534. var _a;
  535. return __awaiter(this, void 0, void 0, function* () {
  536. if (typeof value == "undefined") {
  537. const arrStr = yield gmValue(
  538. "get",
  539. false,
  540. "ajs_disabled_domains",
  541. defaultValues.black
  542. );
  543. return typeof arrStr == "string" && arrStr.length > 0
  544. ? arrStr.split(",")
  545. : [];
  546. } else {
  547. return yield gmValue(
  548. "set",
  549. false,
  550. "ajs_disabled_domains",
  551. (_a =
  552. value === null || value === void 0
  553. ? void 0
  554. : value.join()) !== null && _a !== void 0
  555. ? _a
  556. : defaultValues.black
  557. );
  558. }
  559. });
  560. },
  561. rules(value) {
  562. return __awaiter(this, void 0, void 0, function* () {
  563. return typeof value == "undefined"
  564. ? yield gmValue(
  565. "get",
  566. true,
  567. "ajs_saved_abprules",
  568. defaultValues.rules
  569. )
  570. : yield gmValue(
  571. "set",
  572. true,
  573. "ajs_saved_abprules",
  574. value !== null && value !== void 0
  575. ? value
  576. : defaultValues.rules
  577. );
  578. });
  579. },
  580. css(value, host = location.hostname) {
  581. return __awaiter(this, void 0, void 0, function* () {
  582. return typeof value == "undefined"
  583. ? yield gmValue(
  584. "get",
  585. true,
  586. `ajs_saved_styles_${host}`,
  587. defaultValues.css
  588. )
  589. : yield gmValue(
  590. "set",
  591. true,
  592. `ajs_saved_styles_${host}`,
  593. value !== null && value !== void 0 ? value : defaultValues.css
  594. );
  595. });
  596. },
  597. time(value) {
  598. return __awaiter(this, void 0, void 0, function* () {
  599. return typeof value == "undefined"
  600. ? yield gmValue("get", false, "ajs_rules_ver", defaultValues.time)
  601. : yield gmValue(
  602. "set",
  603. false,
  604. "ajs_rules_ver",
  605. value !== null && value !== void 0
  606. ? value
  607. : defaultValues.time
  608. );
  609. });
  610. },
  611. etags(value) {
  612. return __awaiter(this, void 0, void 0, function* () {
  613. return typeof value == "undefined"
  614. ? yield gmValue(
  615. "get",
  616. true,
  617. "ajs_rules_etags",
  618. defaultValues.etags
  619. )
  620. : yield gmValue(
  621. "set",
  622. true,
  623. "ajs_rules_etags",
  624. value !== null && value !== void 0
  625. ? value
  626. : defaultValues.etags
  627. );
  628. });
  629. },
  630. brules(value) {
  631. return __awaiter(this, void 0, void 0, function* () {
  632. return typeof value == "undefined"
  633. ? yield gmValue(
  634. "get",
  635. true,
  636. "ajs_modifier_rules",
  637. defaultValues.brules
  638. )
  639. : yield gmValue(
  640. "set",
  641. true,
  642. "ajs_modifier_rules",
  643. value !== null && value !== void 0
  644. ? value
  645. : defaultValues.brules
  646. );
  647. });
  648. },
  649. hash(value) {
  650. return __awaiter(this, void 0, void 0, function* () {
  651. return typeof value == "undefined"
  652. ? yield gmValue(
  653. "get",
  654. false,
  655. "ajs_custom_hash",
  656. defaultValues.hash
  657. )
  658. : yield gmValue(
  659. "set",
  660. false,
  661. "ajs_custom_hash",
  662. value !== null && value !== void 0
  663. ? value
  664. : defaultValues.hash
  665. );
  666. });
  667. },
  668. },
  669. menus = {
  670. disable: {
  671. id: undefined,
  672. text() {
  673. return __awaiter(this, void 0, void 0, function* () {
  674. return `在此域名${data.disabled ? "启用" : "禁用"}拦截`;
  675. });
  676. },
  677. },
  678. update: {
  679. id: undefined,
  680. text() {
  681. return __awaiter(this, void 0, void 0, function* () {
  682. const time = yield values.time();
  683. return data.updating
  684. ? "正在更新..."
  685. : `点击更新 ${
  686. (time === null || time === void 0
  687. ? void 0
  688. : time.slice(0, 1)) === "0"
  689. ? "未知时间"
  690. : time
  691. }`;
  692. });
  693. },
  694. },
  695. count: {
  696. id: undefined,
  697. text() {
  698. return __awaiter(this, void 0, void 0, function* () {
  699. let cssCount = "";
  700. if (!data.disabled) {
  701. if ((data.appliedLevel & 1) == 0)
  702. cssCount += data.genHideCss + data.genExtraCss;
  703. if ((data.appliedLevel & 2) == 0)
  704. cssCount += data.spcHideCss + data.spcExtraCss;
  705. }
  706. return data.isClean
  707. ? `已清空,点击刷新${data.disabled ? "网页" : "重新加载规则"}`
  708. : data.disabled
  709. ? "点击清空存储规则"
  710. : `点击清空 ${
  711. data.saved
  712. ? "CSS " + (cssCount.split("*/").length - 1)
  713. : "规则 " +
  714. data.appliedCount +
  715. "/" +
  716. data.allRules.split("\n").length
  717. }`;
  718. });
  719. },
  720. },
  721. export: {
  722. id: undefined,
  723. text() {
  724. return __awaiter(this, void 0, void 0, function* () {
  725. return "下载统计报告";
  726. });
  727. },
  728. },
  729. };
  730. function gmChooser(gm1, gm4) {
  731. const gm1dm =
  732. gm1 === null || gm1 === void 0 ? void 0 : gm1.name.startsWith("DM_");
  733. const gm4dm =
  734. gm4 === null || gm4 === void 0 ? void 0 : gm4.name.startsWith("DM_");
  735. if (gm1 && gm4) {
  736. if (gm1dm !== gm4dm) {
  737. return gm1dm ? gm4 : gm1;
  738. } else {
  739. return gm1;
  740. }
  741. } else {
  742. return gm1 ? gm1 : gm4 ? gm4 : undefined;
  743. }
  744. }
  745. function gmMenu(name, cb) {
  746. var _a;
  747. return __awaiter(this, void 0, void 0, function* () {
  748. const id =
  749. (_a = menus[name].id) !== null && _a !== void 0 ? _a : undefined;
  750. const gmr = gmChooser(
  751. tm.GM_registerMenuCommand,
  752. tm.GM === null || tm.GM === void 0
  753. ? void 0
  754. : tm.GM.registerMenuCommand
  755. );
  756. const gmu = gmChooser(
  757. tm.GM_unregisterMenuCommand,
  758. tm.GM === null || tm.GM === void 0
  759. ? void 0
  760. : tm.GM.unregisterMenuCommand
  761. );
  762. if (typeof gmr != "function" || data.isFrame) return;
  763. if (typeof id != "undefined" && typeof gmu == "function") {
  764. menus[name].id = undefined;
  765. yield gmu(id);
  766. }
  767. if (typeof cb == "function") {
  768. menus[name].id = yield gmr(yield menus[name].text(), cb);
  769. }
  770. });
  771. }
  772. function gmValue(action, json, key, value) {
  773. var _a, _b, _c, _d;
  774. return __awaiter(this, void 0, void 0, function* () {
  775. switch (action) {
  776. case "get":
  777. try {
  778. let v =
  779. (_a = gmChooser(
  780. tm.GM_getValue,
  781. tm.GM === null || tm.GM === void 0 ? void 0 : tm.GM.getValue
  782. )) === null || _a === void 0
  783. ? void 0
  784. : _a(key, json ? JSON.stringify(value) : value);
  785. v = v instanceof Promise ? yield v : v;
  786. return Promise.resolve(
  787. json && typeof v == "string" ? JSON.parse(v) : v
  788. );
  789. } catch (error) {
  790. return Promise.resolve(value);
  791. }
  792. case "set":
  793. try {
  794. return value === null || value === undefined
  795. ? Promise.resolve(
  796. (_b = gmChooser(
  797. tm.GM_deleteValue,
  798. tm.GM === null || tm.GM === void 0
  799. ? void 0
  800. : tm.GM.deleteValue
  801. )) === null || _b === void 0
  802. ? void 0
  803. : _b(key)
  804. )
  805. : Promise.resolve(
  806. (_c = gmChooser(
  807. tm.GM_setValue,
  808. tm.GM === null || tm.GM === void 0
  809. ? void 0
  810. : tm.GM.setValue
  811. )) === null || _c === void 0
  812. ? void 0
  813. : _c(key, json ? JSON.stringify(value) : value)
  814. );
  815. } catch (error) {
  816. Promise.reject(
  817. (_d = gmChooser(
  818. tm.GM_deleteValue,
  819. tm.GM === null || tm.GM === void 0
  820. ? void 0
  821. : tm.GM.deleteValue
  822. )) === null || _d === void 0
  823. ? void 0
  824. : _d(key)
  825. );
  826. }
  827. break;
  828. }
  829. });
  830. }
  831. function getUserConfig(prop) {
  832. var _a;
  833. return __awaiter(this, void 0, void 0, function* () {
  834. {
  835. return (_a = yield gmValue("get", false, `配置.${prop}`)) !== null &&
  836. _a !== void 0
  837. ? _a
  838. : preset.userConfig[prop];
  839. }
  840. });
  841. }
  842. function addStyle(css, pass = 0) {
  843. var _a;
  844. return __awaiter(this, void 0, void 0, function* () {
  845. if (pass >= data.tryCount) return;
  846. const el = yield (_a = gmChooser(
  847. tm.GM_addStyle,
  848. tm.GM === null || tm.GM === void 0 ? void 0 : tm.GM.addStyle
  849. )) === null || _a === void 0
  850. ? void 0
  851. : _a(css);
  852. if (!el || !document.documentElement.contains(el)) {
  853. setTimeout(() => {
  854. addStyle(css, pass + 1);
  855. }, data.tryTimeout);
  856. }
  857. });
  858. }
  859. function promiseXhr(details) {
  860. return __awaiter(this, void 0, void 0, function* () {
  861. let loaded = false;
  862. const gmXhr = gmChooser(
  863. tm.GM_xmlhttpRequest,
  864. tm.GM === null || tm.GM === void 0 ? void 0 : tm.GM.xmlHttpRequest
  865. );
  866. if (typeof gmXhr != "function")
  867. return Promise.reject({
  868. error: "noxhr",
  869. });
  870. return yield new Promise((resolve, reject) => {
  871. gmXhr(
  872. Object.assign(
  873. {
  874. onload(e) {
  875. loaded = true;
  876. resolve(e);
  877. },
  878. onabort(e) {
  879. loaded = true;
  880. reject({
  881. error: "abort",
  882. resp: e,
  883. });
  884. },
  885. onerror(e) {
  886. loaded = true;
  887. reject({
  888. error: "error",
  889. resp: e,
  890. });
  891. },
  892. ontimeout(e) {
  893. loaded = true;
  894. reject({
  895. error: "timeout",
  896. resp: e,
  897. });
  898. },
  899. onreadystatechange(e) {
  900. // Via 浏览器超时中断,不给成功状态...
  901. if (
  902. (e === null || e === void 0 ? void 0 : e.readyState) === 3
  903. ) {
  904. setTimeout(
  905. () => {
  906. if (!loaded)
  907. reject({
  908. error: "Via timeout",
  909. resp: e,
  910. });
  911. },
  912. details.method === "HEAD"
  913. ? data.headTimeout
  914. : data.timeout
  915. );
  916. }
  917. },
  918. timeout:
  919. details.method === "HEAD" ? data.headTimeout : data.timeout,
  920. },
  921. details
  922. )
  923. );
  924. });
  925. });
  926. }
  927. function getRuleFromResource(key) {
  928. var _a;
  929. return __awaiter(this, void 0, void 0, function* () {
  930. try {
  931. return yield (_a = gmChooser(
  932. tm.GM_getResourceText,
  933. tm.GM === null || tm.GM === void 0 ? void 0 : tm.GM.getResourceText
  934. )) === null || _a === void 0
  935. ? void 0
  936. : _a(key);
  937. } catch (error) {
  938. return null;
  939. }
  940. });
  941. }
  942. function runOnce(key, func) {
  943. if (key in tm.unsafeWindow) return Promise.reject();
  944. tm.unsafeWindow[key] = true;
  945. return func();
  946. }
  947. function downUrl(url, name) {
  948. tm.GM_download === null || tm.GM_download === void 0
  949. ? void 0
  950. : tm.GM_download({
  951. url,
  952. name,
  953. });
  954. }
  955. function getSavedHosts(host) {
  956. var _a, _b;
  957. return __awaiter(this, void 0, void 0, function* () {
  958. const keys =
  959. (_b = yield (_a = gmChooser(
  960. tm.GM_listValues,
  961. tm.GM === null || tm.GM === void 0 ? void 0 : tm.GM.listValues
  962. )) === null || _a === void 0
  963. ? void 0
  964. : _a()) !== null && _b !== void 0
  965. ? _b
  966. : [];
  967. const domains = (
  968. Array.isArray(keys)
  969. ? keys
  970. : // Rains
  971. Object.keys(keys)
  972. )
  973. .filter((key) => key.startsWith("ajs_saved_styles_"))
  974. .map((key) => key.replace("ajs_saved_styles_", ""));
  975. return host ? domains.includes(host) : domains;
  976. });
  977. }
  978. const CRRE =
  979. /^(\[\$domain=)?(~?[\w-]+(?:\.[\w-]+)*(?:\.[\w-]+|\.\*)(?:(?:,|\|)~?[\w-]+(?:\.[\w-]+)*(?:\.[\w-]+|\.\*))*)?(?:])?(#@?\$?\??#)([^\s^+].*)/,
  980. BRRE =
  981. /^(?:@@?)(?:\/(.*[^\\])\/|(\|\|?)?(https?:\/\/)?([^\s"<>`]+?[|^]?))?\$((?:(?:~?[\w-]+(?:=[^$]+)?|_+)(?:[^\\],|$))+)/,
  982. CCRE =
  983. /^\/\*\s(\d)(\|)?(.+?)\s\*\/\s((.+?)\s*(?:\{\s*[a-zA-Z-]+\s*:\s*.+\}|,))\s*$/,
  984. CMRE = /\/\*\s*\d.+?\s*\*\//g,
  985. BROpts = [
  986. "elemhide",
  987. "ehide",
  988. "specifichide",
  989. "shide",
  990. "generichide",
  991. "ghide",
  992. ],
  993. CRFlags = ["##", "#@#", "#?#", "#@?#", "#$#", "#@$#", "#$?#", "#@$?#"],
  994. styleBoxes = ["genHideCss", "genExtraCss", "spcHideCss", "spcExtraCss"],
  995. dataBoxes = ["selectors", "extSelectors", "styles", "extStyles"];
  996. function bRuleSpliter(rule) {
  997. const group = rule.match(BRRE);
  998. if (!group) return null;
  999. const [, regex, pipe, proto, body, option] = group,
  1000. options = option.split(","),
  1001. sepChar = "[^\\w\\.%-]",
  1002. anyChar = '(?:[^\\s"<>`]*)',
  1003. eh = hasSome(options, ["elemhide", "ehide"]),
  1004. sh = hasSome(options, ["specifichide", "shide"]),
  1005. gh = hasSome(options, ["generichide", "ghide"]);
  1006. let domains = [];
  1007. options.forEach((opt) => {
  1008. if (opt.startsWith("domain=")) {
  1009. domains = opt.split("=")[1].split("|");
  1010. }
  1011. });
  1012. let match = "";
  1013. if (regex) {
  1014. match = regex;
  1015. } else if (body) {
  1016. match += pipe
  1017. ? proto
  1018. ? `^${proto}`
  1019. : `^https?://(?:[\\w-]+\\.)*?`
  1020. : `^${anyChar}`;
  1021. match += body
  1022. .replace(/[-\\$+.()[\]{}]/g, "\\$&")
  1023. .replaceAll("^", "$^")
  1024. .replace(/\|$/, "$")
  1025. .replaceAll("|", "\\|")
  1026. .replace(/\*$/, "")
  1027. .replaceAll("*", anyChar)
  1028. .replace(/\$\^$/, `(?:${sepChar}.*|$)`)
  1029. .replaceAll("$^", sepChar);
  1030. } else if (domains.length > 0) {
  1031. match = domains;
  1032. }
  1033. return [
  1034. {
  1035. rule,
  1036. match,
  1037. level: eh || (gh && sh) ? 3 : sh ? 2 : gh ? 1 : 0,
  1038. },
  1039. options.includes("badfilter"),
  1040. ];
  1041. }
  1042. function isBasicRule(rule) {
  1043. return BRRE.test(rule) && hasSome(rule, BROpts);
  1044. }
  1045. function bRuleParser(rule, url = location.href) {
  1046. return rule
  1047. ? (Array.isArray(rule.match) && domainChecker(rule.match)[0]) ||
  1048. (!Array.isArray(rule.match) && new RegExp(rule.match).test(url))
  1049. ? rule.level
  1050. : 0
  1051. : 0;
  1052. }
  1053. function getEtag(header) {
  1054. var _a;
  1055. let result = null;
  1056. if (!header) return null;
  1057. [
  1058. /[e|E][t|T]ag:\s(?:W\/)?"(\w+)"/,
  1059. // WebView-GM 系
  1060. /[e|E][t|T]ag:\s\[(?:W\/)?"(\w+)"\]/,
  1061. // 书签地球
  1062. /[e|E][t|T]ag=(?:W\/)?"(\w+)"/,
  1063. // 海阔世界
  1064. /^(?:W\/)?"(\w+)"/,
  1065. ].forEach((re) => {
  1066. result !== null && result !== void 0
  1067. ? result
  1068. : (result = header.match(re));
  1069. });
  1070. return (_a =
  1071. result === null || result === void 0 ? void 0 : result[1]) !== null &&
  1072. _a !== void 0
  1073. ? _a
  1074. : null;
  1075. }
  1076. function domainChecker(domains) {
  1077. const results = [],
  1078. invResults = [],
  1079. currDomain = location.hostname,
  1080. urlSuffix = /\.+?[\w-]+$/.exec(currDomain);
  1081. let totalResult = [0, false],
  1082. black = false,
  1083. white = false,
  1084. match = false;
  1085. domains.forEach((domain) => {
  1086. const invert = domain[0] === "~";
  1087. if (invert) domain = domain.slice(1);
  1088. if (domain.endsWith(".*") && Array.isArray(urlSuffix)) {
  1089. domain = domain.replace(".*", urlSuffix[0]);
  1090. }
  1091. const result = currDomain.endsWith(domain);
  1092. if (invert) {
  1093. if (result) white = true;
  1094. invResults.push([domain.length, !result]);
  1095. } else {
  1096. if (result) black = true;
  1097. results.push([domain.length, result]);
  1098. }
  1099. });
  1100. if (results.length > 0 && !black) {
  1101. match = false;
  1102. } else if (invResults.length > 0 && !white) {
  1103. match = true;
  1104. } else {
  1105. results.forEach((r) => {
  1106. if (r[0] >= totalResult[0] && r[1]) {
  1107. totalResult = r;
  1108. }
  1109. });
  1110. invResults.forEach((r) => {
  1111. if (r[0] >= totalResult[0] && !r[1]) {
  1112. totalResult = r;
  1113. }
  1114. });
  1115. match = totalResult[1];
  1116. }
  1117. return [match, results.length === 0];
  1118. }
  1119. function hasSome(str, arr) {
  1120. return arr.some((word) => str.includes(word));
  1121. }
  1122. function ruleSpliter(rule) {
  1123. const group = rule.match(CRRE);
  1124. if (group) {
  1125. const [, isDomain, place = "*", flag, sel] = group,
  1126. type = CRFlags.indexOf(flag),
  1127. matchResult =
  1128. place === "*"
  1129. ? [true, true]
  1130. : domainChecker(place.split(isDomain ? "|" : ","));
  1131. if (sel && matchResult[0]) {
  1132. return {
  1133. black: type % 2 ? "white" : "black",
  1134. type: Math.floor(type / 2),
  1135. place: (isDomain ? "|" : "") + place,
  1136. generic: matchResult[1],
  1137. sel,
  1138. };
  1139. }
  1140. }
  1141. }
  1142. function ruleLoader(rule) {
  1143. if (
  1144. hasSome(rule, [
  1145. ":matches-path(",
  1146. ":min-text-length(",
  1147. ":watch-attr(",
  1148. ":-abp-properties(",
  1149. ":matches-property(",
  1150. ])
  1151. )
  1152. return;
  1153. // 去掉开头末尾空格
  1154. rule = rule.trim();
  1155. // 如果 #$# 不包含 {} 就排除
  1156. // 可以尽量排除 Snippet Filters
  1157. if (
  1158. /(?:\w|\*|]|^)#\$#/.test(rule) &&
  1159. !/{\s*[a-zA-Z-]+\s*:\s*.+}\s*$/.test(rule)
  1160. )
  1161. return;
  1162. // ## -> #?#
  1163. if (
  1164. /(?:\w|\*|]|^)#@?\$?#/.test(rule) &&
  1165. hasSome(rule, [
  1166. ":has(",
  1167. ":-abp-has(",
  1168. "[-ext-has=",
  1169. ":has-text(",
  1170. ":contains(",
  1171. ":-abp-contains(",
  1172. "[-ext-contains=",
  1173. ":matches-css(",
  1174. "[-ext-matches-css=",
  1175. ":matches-css-before(",
  1176. "[-ext-matches-css-before=",
  1177. ":matches-css-after(",
  1178. "[-ext-matches-css-after=",
  1179. ":matches-attr(",
  1180. ":nth-ancestor(",
  1181. ":upward(",
  1182. ":xpath(",
  1183. ":remove()",
  1184. ":not(",
  1185. ])
  1186. ) {
  1187. rule = rule.replace(/(\w|\*|]|^)#(@?\$?)#/, "$1#$2?#");
  1188. }
  1189. // :style(...) 转换
  1190. // example.com#?##id:style(color: red)
  1191. // example.com#$?##id { color: red }
  1192. if (rule.includes(":style(")) {
  1193. rule = rule
  1194. .replace(/(\w|\*|]|^)#(@?)(\??)#/, "$1#$2$$$3#")
  1195. .replace(/:style\(\s*/, " { ")
  1196. .replace(/\s*\)$/, " }");
  1197. }
  1198. return ruleSpliter(rule);
  1199. }
  1200. function ruleToCss(rule, preset, full) {
  1201. var _a, _b;
  1202. const isStyle = /}\s*$/.test(rule.sel);
  1203. return [
  1204. `/* ${rule.type}${rule.place} */ ${
  1205. rule.sel +
  1206. (!isStyle
  1207. ? full
  1208. ? " " + preset.replace(/^\s{2,}/g, " ").replaceAll("\n", "")
  1209. : ","
  1210. : "")
  1211. } \n`,
  1212. isStyle
  1213. ? (_b =
  1214. (_a = rule.sel.match(/^(.+?)\s*{\s*[a-zA-Z-]+\s*:\s*.+}\s*$/)) ===
  1215. null || _a === void 0
  1216. ? void 0
  1217. : _a[1]) !== null && _b !== void 0
  1218. ? _b
  1219. : rule.sel
  1220. : rule.sel,
  1221. isStyle,
  1222. ];
  1223. }
  1224. function cssToAbp(css) {
  1225. var _a;
  1226. const flags = ["##", "#?#", "#$#", "#$?#"];
  1227. const [, typeStr, isDomain, place, style, sel] =
  1228. (_a = css.match(CCRE)) !== null && _a !== void 0 ? _a : [];
  1229. if (typeStr === undefined) return null;
  1230. const type = parseInt(typeStr);
  1231. return [
  1232. `${place === "*" ? "" : isDomain ? `[$domain=${place}]` : place}${
  1233. flags[type]
  1234. }${type >= 2 ? style : sel}`,
  1235. type,
  1236. sel,
  1237. ];
  1238. }
  1239. // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#bypassing_the_cache
  1240. function addTimeParam(url) {
  1241. return url + (url.includes("?") ? "&" : "?") + new Date().getTime();
  1242. }
  1243. function saveCss() {
  1244. return __awaiter(this, void 0, void 0, function* () {
  1245. const styles = {
  1246. needUpdate: false,
  1247. genHideCss: data.genHideCss,
  1248. genExtraCss: data.genExtraCss,
  1249. spcHideCss: data.spcHideCss,
  1250. spcExtraCss: data.spcExtraCss,
  1251. };
  1252. yield values.css(styles);
  1253. });
  1254. }
  1255. function readCss() {
  1256. var _a;
  1257. return __awaiter(this, void 0, void 0, function* () {
  1258. const styles =
  1259. (_a = yield values.css()) !== null && _a !== void 0
  1260. ? _a
  1261. : defaultValues.css;
  1262. if (!hasSome(Object.keys(styles), styleBoxes)) {
  1263. yield values.css(defaultValues.css);
  1264. return;
  1265. }
  1266. styleBoxes.forEach((sname) => {
  1267. var _a;
  1268. if (styles[sname].length > 0) {
  1269. data.saved = true;
  1270. data.update =
  1271. (_a = styles.needUpdate) !== null && _a !== void 0 ? _a : true;
  1272. data[sname] = styles[sname];
  1273. }
  1274. });
  1275. });
  1276. }
  1277.  
  1278. /**
  1279. * @adguard/extended-css - v2.0.52 - Fri Apr 14 2023
  1280. * https://github.com/AdguardTeam/ExtendedCss#homepage
  1281. * Copyright (c) 2023 AdGuard. Licensed GPL-3.0
  1282. */
  1283. function _defineProperty(obj, key, value) {
  1284. if (key in obj) {
  1285. Object.defineProperty(obj, key, {
  1286. value: value,
  1287. enumerable: true,
  1288. configurable: true,
  1289. writable: true,
  1290. });
  1291. } else {
  1292. obj[key] = value;
  1293. }
  1294. return obj;
  1295. }
  1296. /**
  1297. * Possible ast node types.
  1298. *
  1299. * IMPORTANT: it is used as 'const' instead of 'enum' to avoid side effects
  1300. * during ExtendedCss import into other libraries.
  1301. */
  1302. const NODE = {
  1303. SELECTOR_LIST: "SelectorList",
  1304. SELECTOR: "Selector",
  1305. REGULAR_SELECTOR: "RegularSelector",
  1306. EXTENDED_SELECTOR: "ExtendedSelector",
  1307. ABSOLUTE_PSEUDO_CLASS: "AbsolutePseudoClass",
  1308. RELATIVE_PSEUDO_CLASS: "RelativePseudoClass",
  1309. };
  1310. /**
  1311. * Class needed for creating ast nodes while selector parsing.
  1312. * Used for SelectorList, Selector, ExtendedSelector.
  1313. */
  1314. class AnySelectorNode {
  1315. /**
  1316. * Creates new ast node.
  1317. *
  1318. * @param type Ast node type.
  1319. */
  1320. constructor(type) {
  1321. _defineProperty(this, "children", []);
  1322. this.type = type;
  1323. }
  1324. /**
  1325. * Adds child node to children array.
  1326. *
  1327. * @param child Ast node.
  1328. */
  1329. addChild(child) {
  1330. this.children.push(child);
  1331. }
  1332. }
  1333. /**
  1334. * Class needed for creating RegularSelector ast node while selector parsing.
  1335. */
  1336. class RegularSelectorNode extends AnySelectorNode {
  1337. /**
  1338. * Creates RegularSelector ast node.
  1339. *
  1340. * @param value Value of RegularSelector node.
  1341. */
  1342. constructor(value) {
  1343. super(NODE.REGULAR_SELECTOR);
  1344. this.value = value;
  1345. }
  1346. }
  1347. /**
  1348. * Class needed for creating RelativePseudoClass ast node while selector parsing.
  1349. */
  1350. class RelativePseudoClassNode extends AnySelectorNode {
  1351. /**
  1352. * Creates RegularSelector ast node.
  1353. *
  1354. * @param name Name of RelativePseudoClass node.
  1355. */
  1356. constructor(name) {
  1357. super(NODE.RELATIVE_PSEUDO_CLASS);
  1358. this.name = name;
  1359. }
  1360. }
  1361. /**
  1362. * Class needed for creating AbsolutePseudoClass ast node while selector parsing.
  1363. */
  1364. class AbsolutePseudoClassNode extends AnySelectorNode {
  1365. /**
  1366. * Creates AbsolutePseudoClass ast node.
  1367. *
  1368. * @param name Name of AbsolutePseudoClass node.
  1369. */
  1370. constructor(name) {
  1371. super(NODE.ABSOLUTE_PSEUDO_CLASS);
  1372. _defineProperty(this, "value", "");
  1373. this.name = name;
  1374. }
  1375. }
  1376. /* eslint-disable jsdoc/require-description-complete-sentence */
  1377. /**
  1378. * Root node.
  1379. *
  1380. * SelectorList
  1381. * : Selector
  1382. * ...
  1383. * ;
  1384. */
  1385. /**
  1386. * Selector node.
  1387. *
  1388. * Selector
  1389. * : RegularSelector
  1390. * | ExtendedSelector
  1391. * ...
  1392. * ;
  1393. */
  1394. /**
  1395. * Regular selector node.
  1396. * It can be selected by querySelectorAll().
  1397. *
  1398. * RegularSelector
  1399. * : type
  1400. * : value
  1401. * ;
  1402. */
  1403. /**
  1404. * Extended selector node.
  1405. *
  1406. * ExtendedSelector
  1407. * : AbsolutePseudoClass
  1408. * | RelativePseudoClass
  1409. * ;
  1410. */
  1411. /**
  1412. * Absolute extended pseudo-class node,
  1413. * i.e. none-selector args.
  1414. *
  1415. * AbsolutePseudoClass
  1416. * : type
  1417. * : name
  1418. * : value
  1419. * ;
  1420. */
  1421. /**
  1422. * Relative extended pseudo-class node
  1423. * i.e. selector as arg.
  1424. *
  1425. * RelativePseudoClass
  1426. * : type
  1427. * : name
  1428. * : SelectorList
  1429. * ;
  1430. */
  1431. //
  1432. // ast example
  1433. //
  1434. // div.banner > div:has(span, p), a img.ad
  1435. //
  1436. // SelectorList - div.banner > div:has(span, p), a img.ad
  1437. // Selector - div.banner > div:has(span, p)
  1438. // RegularSelector - div.banner > div
  1439. // ExtendedSelector - :has(span, p)
  1440. // PseudoClassSelector - :has
  1441. // SelectorList - span, p
  1442. // Selector - span
  1443. // RegularSelector - span
  1444. // Selector - p
  1445. // RegularSelector - p
  1446. // Selector - a img.ad
  1447. // RegularSelector - a img.ad
  1448. //
  1449. const LEFT_SQUARE_BRACKET = "[";
  1450. const RIGHT_SQUARE_BRACKET = "]";
  1451. const LEFT_PARENTHESIS = "(";
  1452. const RIGHT_PARENTHESIS = ")";
  1453. const LEFT_CURLY_BRACKET = "{";
  1454. const RIGHT_CURLY_BRACKET = "}";
  1455. const BRACKET = {
  1456. SQUARE: {
  1457. LEFT: LEFT_SQUARE_BRACKET,
  1458. RIGHT: RIGHT_SQUARE_BRACKET,
  1459. },
  1460. PARENTHESES: {
  1461. LEFT: LEFT_PARENTHESIS,
  1462. RIGHT: RIGHT_PARENTHESIS,
  1463. },
  1464. CURLY: {
  1465. LEFT: LEFT_CURLY_BRACKET,
  1466. RIGHT: RIGHT_CURLY_BRACKET,
  1467. },
  1468. };
  1469. const SLASH = "/";
  1470. const BACKSLASH = "\\";
  1471. const SPACE = " ";
  1472. const COMMA = ",";
  1473. const DOT = ".";
  1474. const SEMICOLON = ";";
  1475. const COLON = ":";
  1476. const SINGLE_QUOTE = "'";
  1477. const DOUBLE_QUOTE = '"'; // do not consider hyphen `-` as separated mark
  1478. // to avoid pseudo-class names splitting
  1479. // e.g. 'matches-css' or 'if-not'
  1480. const CARET = "^";
  1481. const DOLLAR_SIGN = "$";
  1482. const EQUAL_SIGN = "=";
  1483. const TAB = "\t";
  1484. const CARRIAGE_RETURN = "\r";
  1485. const LINE_FEED = "\n";
  1486. const FORM_FEED = "\f";
  1487. const WHITE_SPACE_CHARACTERS = [
  1488. SPACE,
  1489. TAB,
  1490. CARRIAGE_RETURN,
  1491. LINE_FEED,
  1492. FORM_FEED,
  1493. ]; // for universal selector and attributes
  1494. const ASTERISK = "*";
  1495. const ID_MARKER = "#";
  1496. const CLASS_MARKER = DOT;
  1497. const DESCENDANT_COMBINATOR = SPACE;
  1498. const CHILD_COMBINATOR = ">";
  1499. const NEXT_SIBLING_COMBINATOR = "+";
  1500. const SUBSEQUENT_SIBLING_COMBINATOR = "~";
  1501. const COMBINATORS = [
  1502. DESCENDANT_COMBINATOR,
  1503. CHILD_COMBINATOR,
  1504. NEXT_SIBLING_COMBINATOR,
  1505. SUBSEQUENT_SIBLING_COMBINATOR,
  1506. ];
  1507. const SUPPORTED_SELECTOR_MARKS = [
  1508. LEFT_SQUARE_BRACKET,
  1509. RIGHT_SQUARE_BRACKET,
  1510. LEFT_PARENTHESIS,
  1511. RIGHT_PARENTHESIS,
  1512. LEFT_CURLY_BRACKET,
  1513. RIGHT_CURLY_BRACKET,
  1514. SLASH,
  1515. BACKSLASH,
  1516. SEMICOLON,
  1517. COLON,
  1518. COMMA,
  1519. SINGLE_QUOTE,
  1520. DOUBLE_QUOTE,
  1521. CARET,
  1522. DOLLAR_SIGN,
  1523. ASTERISK,
  1524. ID_MARKER,
  1525. CLASS_MARKER,
  1526. DESCENDANT_COMBINATOR,
  1527. CHILD_COMBINATOR,
  1528. NEXT_SIBLING_COMBINATOR,
  1529. SUBSEQUENT_SIBLING_COMBINATOR,
  1530. TAB,
  1531. CARRIAGE_RETURN,
  1532. LINE_FEED,
  1533. FORM_FEED,
  1534. ];
  1535. const SUPPORTED_STYLE_DECLARATION_MARKS = [
  1536. // divider between property and value in declaration
  1537. COLON,
  1538. // divider between declarations
  1539. SEMICOLON,
  1540. // sometimes is needed for value wrapping
  1541. // e.g. 'content: "-"'
  1542. SINGLE_QUOTE,
  1543. DOUBLE_QUOTE,
  1544. // needed for quote escaping inside the same-type quotes
  1545. BACKSLASH,
  1546. // whitespaces
  1547. SPACE,
  1548. TAB,
  1549. CARRIAGE_RETURN,
  1550. LINE_FEED,
  1551. FORM_FEED,
  1552. ]; // absolute:
  1553. const CONTAINS_PSEUDO = "contains";
  1554. const HAS_TEXT_PSEUDO = "has-text";
  1555. const ABP_CONTAINS_PSEUDO = "-abp-contains";
  1556. const MATCHES_CSS_PSEUDO = "matches-css";
  1557. const MATCHES_CSS_BEFORE_PSEUDO = "matches-css-before";
  1558. const MATCHES_CSS_AFTER_PSEUDO = "matches-css-after";
  1559. const MATCHES_ATTR_PSEUDO_CLASS_MARKER = "matches-attr";
  1560. const MATCHES_PROPERTY_PSEUDO_CLASS_MARKER = "matches-property";
  1561. const XPATH_PSEUDO_CLASS_MARKER = "xpath";
  1562. const NTH_ANCESTOR_PSEUDO_CLASS_MARKER = "nth-ancestor";
  1563. const CONTAINS_PSEUDO_NAMES = [
  1564. CONTAINS_PSEUDO,
  1565. HAS_TEXT_PSEUDO,
  1566. ABP_CONTAINS_PSEUDO,
  1567. ];
  1568. /**
  1569. * Pseudo-class :upward() can get number or selector arg
  1570. * and if the arg is selector it should be standard, not extended
  1571. * so :upward pseudo-class is always absolute.
  1572. */
  1573. const UPWARD_PSEUDO_CLASS_MARKER = "upward";
  1574. /**
  1575. * Pseudo-class `:remove()` and pseudo-property `remove`
  1576. * are used for element actions, not for element selecting.
  1577. *
  1578. * Selector text should not contain the pseudo-class
  1579. * so selector parser should consider it as invalid
  1580. * and both are handled by stylesheet parser.
  1581. */
  1582. const REMOVE_PSEUDO_MARKER = "remove"; // relative:
  1583. const HAS_PSEUDO_CLASS_MARKER = "has";
  1584. const ABP_HAS_PSEUDO_CLASS_MARKER = "-abp-has";
  1585. const HAS_PSEUDO_CLASS_MARKERS = [
  1586. HAS_PSEUDO_CLASS_MARKER,
  1587. ABP_HAS_PSEUDO_CLASS_MARKER,
  1588. ];
  1589. const IS_PSEUDO_CLASS_MARKER = "is";
  1590. const NOT_PSEUDO_CLASS_MARKER = "not";
  1591. const ABSOLUTE_PSEUDO_CLASSES = [
  1592. CONTAINS_PSEUDO,
  1593. HAS_TEXT_PSEUDO,
  1594. ABP_CONTAINS_PSEUDO,
  1595. MATCHES_CSS_PSEUDO,
  1596. MATCHES_CSS_BEFORE_PSEUDO,
  1597. MATCHES_CSS_AFTER_PSEUDO,
  1598. MATCHES_ATTR_PSEUDO_CLASS_MARKER,
  1599. MATCHES_PROPERTY_PSEUDO_CLASS_MARKER,
  1600. XPATH_PSEUDO_CLASS_MARKER,
  1601. NTH_ANCESTOR_PSEUDO_CLASS_MARKER,
  1602. UPWARD_PSEUDO_CLASS_MARKER,
  1603. ];
  1604. const RELATIVE_PSEUDO_CLASSES = [
  1605. ...HAS_PSEUDO_CLASS_MARKERS,
  1606. IS_PSEUDO_CLASS_MARKER,
  1607. NOT_PSEUDO_CLASS_MARKER,
  1608. ];
  1609. const SUPPORTED_PSEUDO_CLASSES = [
  1610. ...ABSOLUTE_PSEUDO_CLASSES,
  1611. ...RELATIVE_PSEUDO_CLASSES,
  1612. ]; // these pseudo-classes should be part of RegularSelector value
  1613. // if its arg does not contain extended selectors.
  1614. // the ast will be checked after the selector is completely parsed
  1615. const OPTIMIZATION_PSEUDO_CLASSES = [
  1616. NOT_PSEUDO_CLASS_MARKER,
  1617. IS_PSEUDO_CLASS_MARKER,
  1618. ];
  1619. /**
  1620. * ':scope' is used for extended pseudo-class :has(), if-not(), :is() and :not().
  1621. */
  1622. const SCOPE_CSS_PSEUDO_CLASS = ":scope";
  1623. /**
  1624. * ':after' and ':before' are needed for :matches-css() pseudo-class
  1625. * all other are needed for :has() limitation after regular pseudo-elements.
  1626. *
  1627. * @see {@link https://bugs.chromium.org/p/chromium/issues/detail?id=669058#c54} [case 3]
  1628. */
  1629. const REGULAR_PSEUDO_ELEMENTS = {
  1630. AFTER: "after",
  1631. BACKDROP: "backdrop",
  1632. BEFORE: "before",
  1633. CUE: "cue",
  1634. CUE_REGION: "cue-region",
  1635. FIRST_LETTER: "first-letter",
  1636. FIRST_LINE: "first-line",
  1637. FILE_SELECTION_BUTTON: "file-selector-button",
  1638. GRAMMAR_ERROR: "grammar-error",
  1639. MARKER: "marker",
  1640. PART: "part",
  1641. PLACEHOLDER: "placeholder",
  1642. SELECTION: "selection",
  1643. SLOTTED: "slotted",
  1644. SPELLING_ERROR: "spelling-error",
  1645. TARGET_TEXT: "target-text",
  1646. }; // ExtendedCss does not support at-rules
  1647. // https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule
  1648. const AT_RULE_MARKER = "@";
  1649. const CONTENT_CSS_PROPERTY = "content";
  1650. const PSEUDO_PROPERTY_POSITIVE_VALUE = "true";
  1651. const DEBUG_PSEUDO_PROPERTY_GLOBAL_VALUE = "global";
  1652. const NO_SELECTOR_ERROR_PREFIX = "Selector should be defined";
  1653. const STYLE_ERROR_PREFIX = {
  1654. NO_STYLE: "No style declaration found",
  1655. NO_SELECTOR: `${NO_SELECTOR_ERROR_PREFIX} before style declaration in stylesheet`,
  1656. INVALID_STYLE: "Invalid style declaration",
  1657. UNCLOSED_STYLE: "Unclosed style declaration",
  1658. NO_PROPERTY: "Missing style property in declaration",
  1659. NO_VALUE: "Missing style value in declaration",
  1660. NO_STYLE_OR_REMOVE:
  1661. "Style should be declared or :remove() pseudo-class should used",
  1662. NO_COMMENT: "Comments are not supported",
  1663. };
  1664. const NO_AT_RULE_ERROR_PREFIX = "At-rules are not supported";
  1665. const REMOVE_ERROR_PREFIX = {
  1666. INVALID_REMOVE: "Invalid :remove() pseudo-class in selector",
  1667. NO_TARGET_SELECTOR: `${NO_SELECTOR_ERROR_PREFIX} before :remove() pseudo-class`,
  1668. MULTIPLE_USAGE:
  1669. "Pseudo-class :remove() appears more than once in selector",
  1670. INVALID_POSITION:
  1671. "Pseudo-class :remove() should be at the end of selector",
  1672. };
  1673. const MATCHING_ELEMENT_ERROR_PREFIX = "Error while matching element";
  1674. const MAX_STYLE_PROTECTION_COUNT = 50;
  1675. /**
  1676. * Regexp that matches backward compatible syntaxes.
  1677. */
  1678. const REGEXP_VALID_OLD_SYNTAX =
  1679. /\[-(?:ext)-([a-z-_]+)=(["'])((?:(?=(\\?))\4.)*?)\2\]/g;
  1680. /**
  1681. * Marker for checking invalid selector after old-syntax normalizing by selector converter.
  1682. */
  1683. const INVALID_OLD_SYNTAX_MARKER = "[-ext-";
  1684. /**
  1685. * Complex replacement function.
  1686. * Undo quote escaping inside of an extended selector.
  1687. *
  1688. * @param match Whole matched string.
  1689. * @param name Group 1.
  1690. * @param quoteChar Group 2.
  1691. * @param rawValue Group 3.
  1692. *
  1693. * @returns Converted string.
  1694. */
  1695. const evaluateMatch = (match, name, quoteChar, rawValue) => {
  1696. // Unescape quotes
  1697. const re = new RegExp(`([^\\\\]|^)\\\\${quoteChar}`, "g");
  1698. const value = rawValue.replace(re, `$1${quoteChar}`);
  1699. return `:${name}(${value})`;
  1700. }; // ':scope' pseudo may be at start of :has() argument
  1701. // but ExtCssDocument.querySelectorAll() already use it for selecting exact element descendants
  1702. const SCOPE_MARKER_REGEXP = /\(:scope >/g;
  1703. const SCOPE_REPLACER = "(>";
  1704. const MATCHES_CSS_PSEUDO_ELEMENT_REGEXP =
  1705. /(:matches-css)-(before|after)\(/g;
  1706. const convertMatchesCss = (
  1707. match,
  1708. extendedPseudoClass,
  1709. regularPseudoElement
  1710. ) => {
  1711. // ':matches-css-before(' --> ':matches-css(before, '
  1712. // ':matches-css-after(' --> ':matches-css(after, '
  1713. return `${extendedPseudoClass}${BRACKET.PARENTHESES.LEFT}${regularPseudoElement}${COMMA}`;
  1714. };
  1715. /**
  1716. * Handles old syntax and :scope inside :has().
  1717. *
  1718. * @param selector Trimmed selector to normalize.
  1719. *
  1720. * @returns Normalized selector.
  1721. * @throws An error on invalid old extended syntax selector.
  1722. */
  1723. const normalize = (selector) => {
  1724. const normalizedSelector = selector
  1725. .replace(REGEXP_VALID_OLD_SYNTAX, evaluateMatch)
  1726. .replace(SCOPE_MARKER_REGEXP, SCOPE_REPLACER)
  1727. .replace(MATCHES_CSS_PSEUDO_ELEMENT_REGEXP, convertMatchesCss); // validate old syntax after normalizing
  1728. // e.g. '[-ext-matches-css-before=\'content: /^[A-Z][a-z]'
  1729. if (normalizedSelector.includes(INVALID_OLD_SYNTAX_MARKER)) {
  1730. throw new Error(
  1731. `Invalid extended-css old syntax selector: '${selector}'`
  1732. );
  1733. }
  1734. return normalizedSelector;
  1735. };
  1736. /**
  1737. * Prepares the rawSelector before tokenization:
  1738. * 1. Trims it.
  1739. * 2. Converts old syntax `[-ext-pseudo-class="..."]` to new one `:pseudo-class(...)`.
  1740. * 3. Handles :scope pseudo inside :has() pseudo-class arg.
  1741. *
  1742. * @param rawSelector Selector with no style declaration.
  1743. * @returns Prepared selector with no style declaration.
  1744. */
  1745. const convert = (rawSelector) => {
  1746. const trimmedSelector = rawSelector.trim();
  1747. return normalize(trimmedSelector);
  1748. };
  1749. /**
  1750. * Possible token types.
  1751. *
  1752. * IMPORTANT: it is used as 'const' instead of 'enum' to avoid side effects
  1753. * during ExtendedCss import into other libraries.
  1754. */
  1755. const TOKEN_TYPE = {
  1756. MARK: "mark",
  1757. WORD: "word",
  1758. };
  1759. /**
  1760. * Splits `input` string into tokens.
  1761. *
  1762. * @param input Input string to tokenize.
  1763. * @param supportedMarks Array of supported marks to considered as `TOKEN_TYPE.MARK`;
  1764. * all other will be considered as `TOKEN_TYPE.WORD`.
  1765. *
  1766. * @returns Array of tokens.
  1767. */
  1768. const tokenize = (input, supportedMarks) => {
  1769. // buffer is needed for words collecting while iterating
  1770. let wordBuffer = ""; // result collection
  1771. const tokens = [];
  1772. const selectorSymbols = input.split(""); // iterate through selector chars and collect tokens
  1773. selectorSymbols.forEach((symbol) => {
  1774. if (supportedMarks.includes(symbol)) {
  1775. // if anything was collected to the buffer before
  1776. if (wordBuffer.length > 0) {
  1777. // now it is time to stop buffer collecting and save is as "word"
  1778. tokens.push({
  1779. type: TOKEN_TYPE.WORD,
  1780. value: wordBuffer,
  1781. }); // reset the buffer
  1782. wordBuffer = "";
  1783. } // save current symbol as "mark"
  1784. tokens.push({
  1785. type: TOKEN_TYPE.MARK,
  1786. value: symbol,
  1787. });
  1788. return;
  1789. } // otherwise collect symbol to the buffer
  1790. wordBuffer += symbol;
  1791. }); // save the last collected word
  1792. if (wordBuffer.length > 0) {
  1793. tokens.push({
  1794. type: TOKEN_TYPE.WORD,
  1795. value: wordBuffer,
  1796. });
  1797. }
  1798. return tokens;
  1799. };
  1800. /**
  1801. * Prepares `rawSelector` and splits it into tokens.
  1802. *
  1803. * @param rawSelector Raw css selector.
  1804. *
  1805. * @returns Array of tokens supported for selector.
  1806. */
  1807. const tokenizeSelector = (rawSelector) => {
  1808. const selector = convert(rawSelector);
  1809. return tokenize(selector, SUPPORTED_SELECTOR_MARKS);
  1810. };
  1811. /**
  1812. * Splits `attribute` into tokens.
  1813. *
  1814. * @param attribute Input attribute.
  1815. *
  1816. * @returns Array of tokens supported for attribute.
  1817. */
  1818. const tokenizeAttribute = (attribute) => {
  1819. // equal sigh `=` in attribute is considered as `TOKEN_TYPE.MARK`
  1820. return tokenize(attribute, [...SUPPORTED_SELECTOR_MARKS, EQUAL_SIGN]);
  1821. };
  1822. /**
  1823. * Some browsers do not support Array.prototype.flat()
  1824. * e.g. Opera 42 which is used for browserstack tests.
  1825. *
  1826. * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat}
  1827. *
  1828. * @param input Array needed to be flatten.
  1829. *
  1830. * @returns Flatten array.
  1831. * @throws An error if array cannot be flatten.
  1832. */
  1833. const flatten = (input) => {
  1834. const stack = [];
  1835. input.forEach((el) => stack.push(el));
  1836. const res = [];
  1837. while (stack.length) {
  1838. // pop value from stack
  1839. const next = stack.pop();
  1840. if (!next) {
  1841. throw new Error("Unable to make array flat");
  1842. }
  1843. if (Array.isArray(next)) {
  1844. // push back array items, won't modify the original input
  1845. next.forEach((el) => stack.push(el));
  1846. } else {
  1847. res.push(next);
  1848. }
  1849. } // reverse to restore input order
  1850. return res.reverse();
  1851. };
  1852. /**
  1853. * Returns first item from `array`.
  1854. *
  1855. * @param array Input array.
  1856. *
  1857. * @returns First array item, or `undefined` if there is no such item.
  1858. */
  1859. const getFirst = (array) => {
  1860. return array[0];
  1861. };
  1862. /**
  1863. * Returns last item from array.
  1864. *
  1865. * @param array Input array.
  1866. *
  1867. * @returns Last array item, or `undefined` if there is no such item.
  1868. */
  1869. const getLast = (array) => {
  1870. return array[array.length - 1];
  1871. };
  1872. /**
  1873. * Returns array item which is previous to the last one
  1874. * e.g. for `[5, 6, 7, 8]` returns `7`.
  1875. *
  1876. * @param array Input array.
  1877. *
  1878. * @returns Previous to last array item, or `undefined` if there is no such item.
  1879. */
  1880. const getPrevToLast = (array) => {
  1881. return array[array.length - 2];
  1882. };
  1883. /**
  1884. * Takes array of ast node `children` and returns the child by the `index`.
  1885. *
  1886. * @param array Array of ast node children.
  1887. * @param index Index of needed child in the array.
  1888. * @param errorMessage Optional error message to throw.
  1889. *
  1890. * @returns Array item at `index` position.
  1891. * @throws An error if there is no child with specified `index` in array.
  1892. */
  1893. const getItemByIndex = (array, index, errorMessage) => {
  1894. const indexChild = array[index];
  1895. if (!indexChild) {
  1896. throw new Error(
  1897. errorMessage || `No array item found by index ${index}`
  1898. );
  1899. }
  1900. return indexChild;
  1901. };
  1902. const NO_REGULAR_SELECTOR_ERROR =
  1903. "At least one of Selector node children should be RegularSelector";
  1904. /**
  1905. * Checks whether the type of `astNode` is SelectorList.
  1906. *
  1907. * @param astNode Ast node.
  1908. *
  1909. * @returns True if astNode.type === SelectorList.
  1910. */
  1911. const isSelectorListNode = (astNode) => {
  1912. return (
  1913. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  1914. NODE.SELECTOR_LIST
  1915. );
  1916. };
  1917. /**
  1918. * Checks whether the type of `astNode` is Selector.
  1919. *
  1920. * @param astNode Ast node.
  1921. *
  1922. * @returns True if astNode.type === Selector.
  1923. */
  1924. const isSelectorNode = (astNode) => {
  1925. return (
  1926. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  1927. NODE.SELECTOR
  1928. );
  1929. };
  1930. /**
  1931. * Checks whether the type of `astNode` is RegularSelector.
  1932. *
  1933. * @param astNode Ast node.
  1934. *
  1935. * @returns True if astNode.type === RegularSelector.
  1936. */
  1937. const isRegularSelectorNode = (astNode) => {
  1938. return (
  1939. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  1940. NODE.REGULAR_SELECTOR
  1941. );
  1942. };
  1943. /**
  1944. * Checks whether the type of `astNode` is ExtendedSelector.
  1945. *
  1946. * @param astNode Ast node.
  1947. *
  1948. * @returns True if astNode.type === ExtendedSelector.
  1949. */
  1950. const isExtendedSelectorNode = (astNode) => {
  1951. return astNode.type === NODE.EXTENDED_SELECTOR;
  1952. };
  1953. /**
  1954. * Checks whether the type of `astNode` is AbsolutePseudoClass.
  1955. *
  1956. * @param astNode Ast node.
  1957. *
  1958. * @returns True if astNode.type === AbsolutePseudoClass.
  1959. */
  1960. const isAbsolutePseudoClassNode = (astNode) => {
  1961. return (
  1962. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  1963. NODE.ABSOLUTE_PSEUDO_CLASS
  1964. );
  1965. };
  1966. /**
  1967. * Checks whether the type of `astNode` is RelativePseudoClass.
  1968. *
  1969. * @param astNode Ast node.
  1970. *
  1971. * @returns True if astNode.type === RelativePseudoClass.
  1972. */
  1973. const isRelativePseudoClassNode = (astNode) => {
  1974. return (
  1975. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  1976. NODE.RELATIVE_PSEUDO_CLASS
  1977. );
  1978. };
  1979. /**
  1980. * Returns name of `astNode`.
  1981. *
  1982. * @param astNode AbsolutePseudoClass or RelativePseudoClass node.
  1983. *
  1984. * @returns Name of `astNode`.
  1985. * @throws An error on unsupported ast node or no name found.
  1986. */
  1987. const getNodeName = (astNode) => {
  1988. if (astNode === null) {
  1989. throw new Error("Ast node should be defined");
  1990. }
  1991. if (
  1992. !isAbsolutePseudoClassNode(astNode) &&
  1993. !isRelativePseudoClassNode(astNode)
  1994. ) {
  1995. throw new Error(
  1996. "Only AbsolutePseudoClass or RelativePseudoClass ast node can have a name"
  1997. );
  1998. }
  1999. if (!astNode.name) {
  2000. throw new Error("Extended pseudo-class should have a name");
  2001. }
  2002. return astNode.name;
  2003. };
  2004. /**
  2005. * Returns value of `astNode`.
  2006. *
  2007. * @param astNode RegularSelector or AbsolutePseudoClass node.
  2008. * @param errorMessage Optional error message if no value found.
  2009. *
  2010. * @returns Value of `astNode`.
  2011. * @throws An error on unsupported ast node or no value found.
  2012. */
  2013. const getNodeValue = (astNode, errorMessage) => {
  2014. if (astNode === null) {
  2015. throw new Error("Ast node should be defined");
  2016. }
  2017. if (
  2018. !isRegularSelectorNode(astNode) &&
  2019. !isAbsolutePseudoClassNode(astNode)
  2020. ) {
  2021. throw new Error(
  2022. "Only RegularSelector ot AbsolutePseudoClass ast node can have a value"
  2023. );
  2024. }
  2025. if (!astNode.value) {
  2026. throw new Error(
  2027. errorMessage ||
  2028. "Ast RegularSelector ot AbsolutePseudoClass node should have a value"
  2029. );
  2030. }
  2031. return astNode.value;
  2032. };
  2033. /**
  2034. * Returns only RegularSelector nodes from `children`.
  2035. *
  2036. * @param children Array of ast node children.
  2037. *
  2038. * @returns Array of RegularSelector nodes.
  2039. */
  2040. const getRegularSelectorNodes = (children) => {
  2041. return children.filter(isRegularSelectorNode);
  2042. };
  2043. /**
  2044. * Returns the first RegularSelector node from `children`.
  2045. *
  2046. * @param children Array of ast node children.
  2047. * @param errorMessage Optional error message if no value found.
  2048. *
  2049. * @returns Ast RegularSelector node.
  2050. * @throws An error if no RegularSelector node found.
  2051. */
  2052. const getFirstRegularChild = (children, errorMessage) => {
  2053. const regularSelectorNodes = getRegularSelectorNodes(children);
  2054. const firstRegularSelectorNode = getFirst(regularSelectorNodes);
  2055. if (!firstRegularSelectorNode) {
  2056. throw new Error(errorMessage || NO_REGULAR_SELECTOR_ERROR);
  2057. }
  2058. return firstRegularSelectorNode;
  2059. };
  2060. /**
  2061. * Returns the last RegularSelector node from `children`.
  2062. *
  2063. * @param children Array of ast node children.
  2064. *
  2065. * @returns Ast RegularSelector node.
  2066. * @throws An error if no RegularSelector node found.
  2067. */
  2068. const getLastRegularChild = (children) => {
  2069. const regularSelectorNodes = getRegularSelectorNodes(children);
  2070. const lastRegularSelectorNode = getLast(regularSelectorNodes);
  2071. if (!lastRegularSelectorNode) {
  2072. throw new Error(NO_REGULAR_SELECTOR_ERROR);
  2073. }
  2074. return lastRegularSelectorNode;
  2075. };
  2076. /**
  2077. * Returns the only child of `node`.
  2078. *
  2079. * @param node Ast node.
  2080. * @param errorMessage Error message.
  2081. *
  2082. * @returns The only child of ast node.
  2083. * @throws An error if none or more than one child found.
  2084. */
  2085. const getNodeOnlyChild = (node, errorMessage) => {
  2086. if (node.children.length !== 1) {
  2087. throw new Error(errorMessage);
  2088. }
  2089. const onlyChild = getFirst(node.children);
  2090. if (!onlyChild) {
  2091. throw new Error(errorMessage);
  2092. }
  2093. return onlyChild;
  2094. };
  2095. /**
  2096. * Takes ExtendedSelector node and returns its only child.
  2097. *
  2098. * @param extendedSelectorNode ExtendedSelector ast node.
  2099. *
  2100. * @returns AbsolutePseudoClass or RelativePseudoClass.
  2101. * @throws An error if there is no specific pseudo-class ast node.
  2102. */
  2103. const getPseudoClassNode = (extendedSelectorNode) => {
  2104. return getNodeOnlyChild(
  2105. extendedSelectorNode,
  2106. "Extended selector should be specified"
  2107. );
  2108. };
  2109. /**
  2110. * Takes RelativePseudoClass node and returns its only child
  2111. * which is relative SelectorList node.
  2112. *
  2113. * @param pseudoClassNode RelativePseudoClass.
  2114. *
  2115. * @returns Relative SelectorList node.
  2116. * @throws An error if no selector list found.
  2117. */
  2118. const getRelativeSelectorListNode = (pseudoClassNode) => {
  2119. if (!isRelativePseudoClassNode(pseudoClassNode)) {
  2120. throw new Error(
  2121. "Only RelativePseudoClass node can have relative SelectorList node as child"
  2122. );
  2123. }
  2124. return getNodeOnlyChild(
  2125. pseudoClassNode,
  2126. `Missing arg for :${getNodeName(pseudoClassNode)}() pseudo-class`
  2127. );
  2128. };
  2129. const ATTRIBUTE_CASE_INSENSITIVE_FLAG = "i";
  2130. /**
  2131. * Limited list of available symbols before slash `/`
  2132. * to check whether it is valid regexp pattern opening.
  2133. */
  2134. const POSSIBLE_MARKS_BEFORE_REGEXP = {
  2135. COMMON: [
  2136. // e.g. ':matches-attr(/data-/)'
  2137. BRACKET.PARENTHESES.LEFT,
  2138. // e.g. `:matches-attr('/data-/')`
  2139. SINGLE_QUOTE,
  2140. // e.g. ':matches-attr("/data-/")'
  2141. DOUBLE_QUOTE,
  2142. // e.g. ':matches-attr(check=/data-v-/)'
  2143. EQUAL_SIGN,
  2144. // e.g. ':matches-property(inner./_test/=null)'
  2145. DOT,
  2146. // e.g. ':matches-css(height:/20px/)'
  2147. COLON,
  2148. // ':matches-css-after( content : /(\\d+\\s)*me/ )'
  2149. SPACE,
  2150. ],
  2151. CONTAINS: [
  2152. // e.g. ':contains(/text/)'
  2153. BRACKET.PARENTHESES.LEFT,
  2154. // e.g. `:contains('/text/')`
  2155. SINGLE_QUOTE,
  2156. // e.g. ':contains("/text/")'
  2157. DOUBLE_QUOTE,
  2158. ],
  2159. };
  2160. /**
  2161. * Checks whether the passed token is supported extended pseudo-class.
  2162. *
  2163. * @param tokenValue Token value to check.
  2164. *
  2165. * @returns True if `tokenValue` is one of supported extended pseudo-class names.
  2166. */
  2167. const isSupportedPseudoClass = (tokenValue) => {
  2168. return SUPPORTED_PSEUDO_CLASSES.includes(tokenValue);
  2169. };
  2170. /**
  2171. * Checks whether the passed pseudo-class `name` should be optimized,
  2172. * i.e. :not() and :is().
  2173. *
  2174. * @param name Pseudo-class name.
  2175. *
  2176. * @returns True if `name` is one if pseudo-class which should be optimized.
  2177. */
  2178. const isOptimizationPseudoClass = (name) => {
  2179. return OPTIMIZATION_PSEUDO_CLASSES.includes(name);
  2180. };
  2181. /**
  2182. * Checks whether next to "space" token is a continuation of regular selector being processed.
  2183. *
  2184. * @param nextTokenType Type of token next to current one.
  2185. * @param nextTokenValue Value of token next to current one.
  2186. *
  2187. * @returns True if next token seems to be a part of current regular selector.
  2188. */
  2189. const doesRegularContinueAfterSpace = (nextTokenType, nextTokenValue) => {
  2190. // regular selector does not continues after the current token
  2191. if (!nextTokenType || !nextTokenValue) {
  2192. return false;
  2193. }
  2194. return (
  2195. COMBINATORS.includes(nextTokenValue) ||
  2196. nextTokenType === TOKEN_TYPE.WORD || // e.g. '#main *:has(> .ad)'
  2197. nextTokenValue === ASTERISK ||
  2198. nextTokenValue === ID_MARKER ||
  2199. nextTokenValue === CLASS_MARKER || // e.g. 'div :where(.content)'
  2200. nextTokenValue === COLON || // e.g. "div[class*=' ']"
  2201. nextTokenValue === SINGLE_QUOTE || // e.g. 'div[class*=" "]'
  2202. nextTokenValue === DOUBLE_QUOTE ||
  2203. nextTokenValue === BRACKET.SQUARE.LEFT
  2204. );
  2205. };
  2206. /**
  2207. * Checks whether the regexp pattern for pseudo-class arg starts.
  2208. * Needed for `context.isRegexpOpen` flag.
  2209. *
  2210. * @param context Selector parser context.
  2211. * @param prevTokenValue Value of previous token.
  2212. * @param bufferNodeValue Value of bufferNode.
  2213. *
  2214. * @returns True if current token seems to be a start of regexp pseudo-class arg pattern.
  2215. * @throws An error on invalid regexp pattern.
  2216. */
  2217. const isRegexpOpening = (context, prevTokenValue, bufferNodeValue) => {
  2218. const lastExtendedPseudoClassName = getLast(
  2219. context.extendedPseudoNamesStack
  2220. );
  2221. if (!lastExtendedPseudoClassName) {
  2222. throw new Error(
  2223. "Regexp pattern allowed only in arg of extended pseudo-class"
  2224. );
  2225. } // for regexp pattens the slash should not be escaped
  2226. // const isRegexpPatternSlash = prevTokenValue !== BACKSLASH;
  2227. // regexp pattern can be set as arg of pseudo-class
  2228. // which means limited list of available symbols before slash `/`;
  2229. // for :contains() pseudo-class regexp pattern should be at the beginning of arg
  2230. if (CONTAINS_PSEUDO_NAMES.includes(lastExtendedPseudoClassName)) {
  2231. return POSSIBLE_MARKS_BEFORE_REGEXP.CONTAINS.includes(prevTokenValue);
  2232. }
  2233. if (
  2234. prevTokenValue === SLASH &&
  2235. lastExtendedPseudoClassName !== XPATH_PSEUDO_CLASS_MARKER
  2236. ) {
  2237. const rawArgDesc = bufferNodeValue
  2238. ? `in arg part: '${bufferNodeValue}'`
  2239. : "arg";
  2240. throw new Error(
  2241. `Invalid regexp pattern for :${lastExtendedPseudoClassName}() pseudo-class ${rawArgDesc}`
  2242. );
  2243. } // for other pseudo-classes regexp pattern can be either the whole arg or its part
  2244. return POSSIBLE_MARKS_BEFORE_REGEXP.COMMON.includes(prevTokenValue);
  2245. };
  2246. /**
  2247. * Checks whether the attribute starts.
  2248. *
  2249. * @param tokenValue Value of current token.
  2250. * @param prevTokenValue Previous token value.
  2251. *
  2252. * @returns True if combination of current and previous token seems to be **a start** of attribute.
  2253. */
  2254. const isAttributeOpening = (tokenValue, prevTokenValue) => {
  2255. return tokenValue === BRACKET.SQUARE.LEFT && prevTokenValue !== BACKSLASH;
  2256. };
  2257. /**
  2258. * Checks whether the attribute ends.
  2259. *
  2260. * @param context Selector parser context.
  2261. *
  2262. * @returns True if combination of current and previous token seems to be **an end** of attribute.
  2263. * @throws An error on invalid attribute.
  2264. */
  2265. const isAttributeClosing = (context) => {
  2266. var _getPrevToLast;
  2267. if (!context.isAttributeBracketsOpen) {
  2268. return false;
  2269. } // valid attributes may have extra spaces inside.
  2270. // we get rid of them just to simplify the checking and they are skipped only here:
  2271. // - spaces will be collected to the ast with spaces as they were declared is selector
  2272. // - extra spaces in attribute are not relevant to attribute syntax validity
  2273. // e.g. 'a[ title ]' is the same as 'a[title]'
  2274. // 'div[style *= "MARGIN" i]' is the same as 'div[style*="MARGIN"i]'
  2275. const noSpaceAttr = context.attributeBuffer.split(SPACE).join(""); // tokenize the prepared attribute string
  2276. const attrTokens = tokenizeAttribute(noSpaceAttr);
  2277. const firstAttrToken = getFirst(attrTokens);
  2278. const firstAttrTokenType =
  2279. firstAttrToken === null || firstAttrToken === void 0
  2280. ? void 0
  2281. : firstAttrToken.type;
  2282. const firstAttrTokenValue =
  2283. firstAttrToken === null || firstAttrToken === void 0
  2284. ? void 0
  2285. : firstAttrToken.value; // signal an error on any mark-type token except backslash
  2286. // e.g. '[="margin"]'
  2287. if (
  2288. firstAttrTokenType === TOKEN_TYPE.MARK && // backslash is allowed at start of attribute
  2289. // e.g. '[\\:data-service-slot]'
  2290. firstAttrTokenValue !== BACKSLASH
  2291. ) {
  2292. // eslint-disable-next-line max-len
  2293. throw new Error(
  2294. `'[${context.attributeBuffer}]' is not a valid attribute due to '${firstAttrTokenValue}' at start of it`
  2295. );
  2296. }
  2297. const lastAttrToken = getLast(attrTokens);
  2298. const lastAttrTokenType =
  2299. lastAttrToken === null || lastAttrToken === void 0
  2300. ? void 0
  2301. : lastAttrToken.type;
  2302. const lastAttrTokenValue =
  2303. lastAttrToken === null || lastAttrToken === void 0
  2304. ? void 0
  2305. : lastAttrToken.value;
  2306. if (lastAttrTokenValue === EQUAL_SIGN) {
  2307. // e.g. '[style=]'
  2308. throw new Error(
  2309. `'[${context.attributeBuffer}]' is not a valid attribute due to '${EQUAL_SIGN}'`
  2310. );
  2311. }
  2312. const equalSignIndex = attrTokens.findIndex((token) => {
  2313. return token.type === TOKEN_TYPE.MARK && token.value === EQUAL_SIGN;
  2314. });
  2315. const prevToLastAttrTokenValue =
  2316. (_getPrevToLast = getPrevToLast(attrTokens)) === null ||
  2317. _getPrevToLast === void 0
  2318. ? void 0
  2319. : _getPrevToLast.value;
  2320. if (equalSignIndex === -1) {
  2321. // if there is no '=' inside attribute,
  2322. // it must be just attribute name which means the word-type token before closing bracket
  2323. // e.g. 'div[style]'
  2324. if (lastAttrTokenType === TOKEN_TYPE.WORD) {
  2325. return true;
  2326. }
  2327. return (
  2328. prevToLastAttrTokenValue === BACKSLASH && // some weird attribute are valid too
  2329. // e.g. '[class\\"ads-article\\"]'
  2330. (lastAttrTokenValue === DOUBLE_QUOTE || // e.g. "[class\\'ads-article\\']"
  2331. lastAttrTokenValue === SINGLE_QUOTE)
  2332. );
  2333. } // get the value of token next to `=`
  2334. const nextToEqualSignToken = getItemByIndex(
  2335. attrTokens,
  2336. equalSignIndex + 1
  2337. );
  2338. const nextToEqualSignTokenValue = nextToEqualSignToken.value; // check whether the attribute value wrapper in quotes
  2339. const isAttrValueQuote =
  2340. nextToEqualSignTokenValue === SINGLE_QUOTE ||
  2341. nextToEqualSignTokenValue === DOUBLE_QUOTE; // for no quotes after `=` the last token before `]` should be a word-type one
  2342. // e.g. 'div[style*=margin]'
  2343. // 'div[style*=MARGIN i]'
  2344. if (!isAttrValueQuote) {
  2345. if (lastAttrTokenType === TOKEN_TYPE.WORD) {
  2346. return true;
  2347. } // otherwise signal an error
  2348. // e.g. 'table[style*=border: 0px"]'
  2349. throw new Error(
  2350. `'[${context.attributeBuffer}]' is not a valid attribute`
  2351. );
  2352. } // otherwise if quotes for value are present
  2353. // the last token before `]` can still be word-type token
  2354. // e.g. 'div[style*="MARGIN" i]'
  2355. if (
  2356. lastAttrTokenType === TOKEN_TYPE.WORD &&
  2357. (lastAttrTokenValue === null || lastAttrTokenValue === void 0
  2358. ? void 0
  2359. : lastAttrTokenValue.toLocaleLowerCase()) ===
  2360. ATTRIBUTE_CASE_INSENSITIVE_FLAG
  2361. ) {
  2362. return prevToLastAttrTokenValue === nextToEqualSignTokenValue;
  2363. } // eventually if there is quotes for attribute value and last token is not a word,
  2364. // the closing mark should be the same quote as opening one
  2365. return lastAttrTokenValue === nextToEqualSignTokenValue;
  2366. };
  2367. /**
  2368. * Checks whether the `tokenValue` is a whitespace character.
  2369. *
  2370. * @param tokenValue Token value.
  2371. *
  2372. * @returns True if `tokenValue` is a whitespace character.
  2373. */
  2374. const isWhiteSpaceChar = (tokenValue) => {
  2375. if (!tokenValue) {
  2376. return false;
  2377. }
  2378. return WHITE_SPACE_CHARACTERS.includes(tokenValue);
  2379. };
  2380. /**
  2381. * Checks whether the passed `str` is a name of supported absolute extended pseudo-class,
  2382. * e.g. :contains(), :matches-css() etc.
  2383. *
  2384. * @param str Token value to check.
  2385. *
  2386. * @returns True if `str` is one of absolute extended pseudo-class names.
  2387. */
  2388. const isAbsolutePseudoClass = (str) => {
  2389. return ABSOLUTE_PSEUDO_CLASSES.includes(str);
  2390. };
  2391. /**
  2392. * Checks whether the passed `str` is a name of supported relative extended pseudo-class,
  2393. * e.g. :has(), :not() etc.
  2394. *
  2395. * @param str Token value to check.
  2396. *
  2397. * @returns True if `str` is one of relative extended pseudo-class names.
  2398. */
  2399. const isRelativePseudoClass = (str) => {
  2400. return RELATIVE_PSEUDO_CLASSES.includes(str);
  2401. };
  2402. /**
  2403. * Returns the node which is being collected
  2404. * or null if there is no such one.
  2405. *
  2406. * @param context Selector parser context.
  2407. *
  2408. * @returns Buffer node or null.
  2409. */
  2410. const getBufferNode = (context) => {
  2411. if (context.pathToBufferNode.length === 0) {
  2412. return null;
  2413. } // buffer node is always the last in the pathToBufferNode stack
  2414. return getLast(context.pathToBufferNode) || null;
  2415. };
  2416. /**
  2417. * Returns the parent node to the 'buffer node' — which is the one being collected —
  2418. * or null if there is no such one.
  2419. *
  2420. * @param context Selector parser context.
  2421. *
  2422. * @returns Parent node of buffer node or null.
  2423. */
  2424. const getBufferNodeParent = (context) => {
  2425. // at least two nodes should exist — the buffer node and its parent
  2426. // otherwise return null
  2427. if (context.pathToBufferNode.length < 2) {
  2428. return null;
  2429. } // since the buffer node is always the last in the pathToBufferNode stack
  2430. // its parent is previous to it in the stack
  2431. return getPrevToLast(context.pathToBufferNode) || null;
  2432. };
  2433. /**
  2434. * Returns last RegularSelector ast node.
  2435. * Needed for parsing of the complex selector with extended pseudo-class inside it.
  2436. *
  2437. * @param context Selector parser context.
  2438. *
  2439. * @returns Ast RegularSelector node.
  2440. * @throws An error if:
  2441. * - bufferNode is absent;
  2442. * - type of bufferNode is unsupported;
  2443. * - no RegularSelector in bufferNode.
  2444. */
  2445. const getContextLastRegularSelectorNode = (context) => {
  2446. const bufferNode = getBufferNode(context);
  2447. if (!bufferNode) {
  2448. throw new Error("No bufferNode found");
  2449. }
  2450. if (!isSelectorNode(bufferNode)) {
  2451. throw new Error("Unsupported bufferNode type");
  2452. }
  2453. const lastRegularSelectorNode = getLastRegularChild(bufferNode.children);
  2454. context.pathToBufferNode.push(lastRegularSelectorNode);
  2455. return lastRegularSelectorNode;
  2456. };
  2457. /**
  2458. * Updates needed buffer node value while tokens iterating.
  2459. * For RegularSelector also collects token values to context.attributeBuffer
  2460. * for proper attribute parsing.
  2461. *
  2462. * @param context Selector parser context.
  2463. * @param tokenValue Value of current token.
  2464. *
  2465. * @throws An error if:
  2466. * - no bufferNode;
  2467. * - bufferNode.type is not RegularSelector or AbsolutePseudoClass.
  2468. */
  2469. const updateBufferNode = (context, tokenValue) => {
  2470. const bufferNode = getBufferNode(context);
  2471. if (bufferNode === null) {
  2472. throw new Error("No bufferNode to update");
  2473. }
  2474. if (isAbsolutePseudoClassNode(bufferNode)) {
  2475. bufferNode.value += tokenValue;
  2476. } else if (isRegularSelectorNode(bufferNode)) {
  2477. bufferNode.value += tokenValue;
  2478. if (context.isAttributeBracketsOpen) {
  2479. context.attributeBuffer += tokenValue;
  2480. }
  2481. } else {
  2482. // eslint-disable-next-line max-len
  2483. throw new Error(
  2484. `${bufferNode.type} node cannot be updated. Only RegularSelector and AbsolutePseudoClass are supported`
  2485. );
  2486. }
  2487. };
  2488. /**
  2489. * Adds SelectorList node to context.ast at the start of ast collecting.
  2490. *
  2491. * @param context Selector parser context.
  2492. */
  2493. const addSelectorListNode = (context) => {
  2494. const selectorListNode = new AnySelectorNode(NODE.SELECTOR_LIST);
  2495. context.ast = selectorListNode;
  2496. context.pathToBufferNode.push(selectorListNode);
  2497. };
  2498. /**
  2499. * Adds new node to buffer node children.
  2500. * New added node will be considered as buffer node after it.
  2501. *
  2502. * @param context Selector parser context.
  2503. * @param type Type of node to add.
  2504. * @param tokenValue Optional, defaults to `''`, value of processing token.
  2505. *
  2506. * @throws An error if no bufferNode.
  2507. */
  2508. const addAstNodeByType = function (context, type) {
  2509. let tokenValue =
  2510. arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
  2511. const bufferNode = getBufferNode(context);
  2512. if (bufferNode === null) {
  2513. throw new Error("No buffer node");
  2514. }
  2515. let node;
  2516. if (type === NODE.REGULAR_SELECTOR) {
  2517. node = new RegularSelectorNode(tokenValue);
  2518. } else if (type === NODE.ABSOLUTE_PSEUDO_CLASS) {
  2519. node = new AbsolutePseudoClassNode(tokenValue);
  2520. } else if (type === NODE.RELATIVE_PSEUDO_CLASS) {
  2521. node = new RelativePseudoClassNode(tokenValue);
  2522. } else {
  2523. // SelectorList || Selector || ExtendedSelector
  2524. node = new AnySelectorNode(type);
  2525. }
  2526. bufferNode.addChild(node);
  2527. context.pathToBufferNode.push(node);
  2528. };
  2529. /**
  2530. * The very beginning of ast collecting.
  2531. *
  2532. * @param context Selector parser context.
  2533. * @param tokenValue Value of regular selector.
  2534. */
  2535. const initAst = (context, tokenValue) => {
  2536. addSelectorListNode(context);
  2537. addAstNodeByType(context, NODE.SELECTOR); // RegularSelector node is always the first child of Selector node
  2538. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  2539. };
  2540. /**
  2541. * Inits selector list subtree for relative extended pseudo-classes, e.g. :has(), :not().
  2542. *
  2543. * @param context Selector parser context.
  2544. * @param tokenValue Optional, defaults to `''`, value of inner regular selector.
  2545. */
  2546. const initRelativeSubtree = function (context) {
  2547. let tokenValue =
  2548. arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  2549. addAstNodeByType(context, NODE.SELECTOR_LIST);
  2550. addAstNodeByType(context, NODE.SELECTOR);
  2551. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  2552. };
  2553. /**
  2554. * Goes to closest parent specified by type.
  2555. * Actually updates path to buffer node for proper ast collecting of selectors while parsing.
  2556. *
  2557. * @param context Selector parser context.
  2558. * @param parentType Type of needed parent node in ast.
  2559. */
  2560. const upToClosest = (context, parentType) => {
  2561. for (let i = context.pathToBufferNode.length - 1; i >= 0; i -= 1) {
  2562. var _context$pathToBuffer;
  2563. if (
  2564. ((_context$pathToBuffer = context.pathToBufferNode[i]) === null ||
  2565. _context$pathToBuffer === void 0
  2566. ? void 0
  2567. : _context$pathToBuffer.type) === parentType
  2568. ) {
  2569. context.pathToBufferNode = context.pathToBufferNode.slice(0, i + 1);
  2570. break;
  2571. }
  2572. }
  2573. };
  2574. /**
  2575. * Returns needed buffer node updated due to complex selector parsing.
  2576. *
  2577. * @param context Selector parser context.
  2578. *
  2579. * @returns Ast node for following selector parsing.
  2580. * @throws An error if there is no upper SelectorNode is ast.
  2581. */
  2582. const getUpdatedBufferNode = (context) => {
  2583. // it may happen during the parsing of selector list
  2584. // which is an argument of relative pseudo-class
  2585. // e.g. '.banner:has(~span, ~p)'
  2586. // parser position is here ↑
  2587. // so if after the comma the buffer node type is SelectorList and parent type is RelativePseudoClass
  2588. // we should simply return the current buffer node
  2589. const bufferNode = getBufferNode(context);
  2590. if (
  2591. bufferNode &&
  2592. isSelectorListNode(bufferNode) &&
  2593. isRelativePseudoClassNode(getBufferNodeParent(context))
  2594. ) {
  2595. return bufferNode;
  2596. }
  2597. upToClosest(context, NODE.SELECTOR);
  2598. const selectorNode = getBufferNode(context);
  2599. if (!selectorNode) {
  2600. throw new Error(
  2601. "No SelectorNode, impossible to continue selector parsing by ExtendedCss"
  2602. );
  2603. }
  2604. const lastSelectorNodeChild = getLast(selectorNode.children);
  2605. const hasExtended =
  2606. lastSelectorNodeChild &&
  2607. isExtendedSelectorNode(lastSelectorNodeChild) && // parser position might be inside standard pseudo-class brackets which has space
  2608. // e.g. 'div:contains(/а/):nth-child(100n + 2)'
  2609. context.standardPseudoBracketsStack.length === 0;
  2610. const supposedPseudoClassNode =
  2611. hasExtended && getFirst(lastSelectorNodeChild.children);
  2612. let newNeededBufferNode = selectorNode;
  2613. if (supposedPseudoClassNode) {
  2614. // name of pseudo-class for last extended-node child for Selector node
  2615. const lastExtendedPseudoName =
  2616. hasExtended && supposedPseudoClassNode.name;
  2617. const isLastExtendedNameRelative =
  2618. lastExtendedPseudoName &&
  2619. isRelativePseudoClass(lastExtendedPseudoName);
  2620. const isLastExtendedNameAbsolute =
  2621. lastExtendedPseudoName &&
  2622. isAbsolutePseudoClass(lastExtendedPseudoName);
  2623. const hasRelativeExtended =
  2624. isLastExtendedNameRelative &&
  2625. context.extendedPseudoBracketsStack.length > 0 &&
  2626. context.extendedPseudoBracketsStack.length ===
  2627. context.extendedPseudoNamesStack.length;
  2628. const hasAbsoluteExtended =
  2629. isLastExtendedNameAbsolute &&
  2630. lastExtendedPseudoName === getLast(context.extendedPseudoNamesStack);
  2631. if (hasRelativeExtended) {
  2632. // return relative selector node to update later
  2633. context.pathToBufferNode.push(lastSelectorNodeChild);
  2634. newNeededBufferNode = supposedPseudoClassNode;
  2635. } else if (hasAbsoluteExtended) {
  2636. // return absolute selector node to update later
  2637. context.pathToBufferNode.push(lastSelectorNodeChild);
  2638. newNeededBufferNode = supposedPseudoClassNode;
  2639. }
  2640. } else if (hasExtended) {
  2641. // return selector node to add new regular selector node later
  2642. newNeededBufferNode = selectorNode;
  2643. } else {
  2644. // otherwise return last regular selector node to update later
  2645. newNeededBufferNode = getContextLastRegularSelectorNode(context);
  2646. } // update the path to buffer node properly
  2647. context.pathToBufferNode.push(newNeededBufferNode);
  2648. return newNeededBufferNode;
  2649. };
  2650. /**
  2651. * Checks values of few next tokens on colon token `:` and:
  2652. * - updates buffer node for following standard pseudo-class;
  2653. * - adds extended selector ast node for following extended pseudo-class;
  2654. * - validates some cases of `:remove()` and `:has()` usage.
  2655. *
  2656. * @param context Selector parser context.
  2657. * @param selector Selector.
  2658. * @param tokenValue Value of current token.
  2659. * @param nextTokenValue Value of token next to current one.
  2660. * @param nextToNextTokenValue Value of token next to next to current one.
  2661. *
  2662. * @throws An error on :remove() pseudo-class in selector
  2663. * or :has() inside regular pseudo limitation.
  2664. */
  2665. const handleNextTokenOnColon = (
  2666. context,
  2667. selector,
  2668. tokenValue,
  2669. nextTokenValue,
  2670. nextToNextTokenValue
  2671. ) => {
  2672. if (!nextTokenValue) {
  2673. throw new Error(
  2674. `Invalid colon ':' at the end of selector: '${selector}'`
  2675. );
  2676. }
  2677. if (!isSupportedPseudoClass(nextTokenValue.toLowerCase())) {
  2678. if (nextTokenValue.toLowerCase() === REMOVE_PSEUDO_MARKER) {
  2679. // :remove() pseudo-class should be handled before
  2680. // as it is not about element selecting but actions with elements
  2681. // e.g. 'body > div:empty:remove()'
  2682. throw new Error(
  2683. `${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`
  2684. );
  2685. } // if following token is not an extended pseudo
  2686. // the colon should be collected to value of RegularSelector
  2687. // e.g. '.entry_text:nth-child(2)'
  2688. updateBufferNode(context, tokenValue); // check the token after the pseudo and do balance parentheses later
  2689. // only if it is functional pseudo-class (standard with brackets, e.g. ':lang()').
  2690. // no brackets balance needed for such case,
  2691. // parser position is on first colon after the 'div':
  2692. // e.g. 'div:last-child:has(button.privacy-policy__btn)'
  2693. if (
  2694. nextToNextTokenValue &&
  2695. nextToNextTokenValue === BRACKET.PARENTHESES.LEFT && // no brackets balance needed for parentheses inside attribute value
  2696. // e.g. 'a[href="javascript:void(0)"]' <-- parser position is on colon `:`
  2697. // before `void` ↑
  2698. !context.isAttributeBracketsOpen
  2699. ) {
  2700. context.standardPseudoNamesStack.push(nextTokenValue);
  2701. }
  2702. } else {
  2703. // it is supported extended pseudo-class.
  2704. // Disallow :has() inside the pseudos accepting only compound selectors
  2705. // https://bugs.chromium.org/p/chromium/issues/detail?id=669058#c54 [2]
  2706. if (
  2707. HAS_PSEUDO_CLASS_MARKERS.includes(nextTokenValue) &&
  2708. context.standardPseudoNamesStack.length > 0
  2709. ) {
  2710. // eslint-disable-next-line max-len
  2711. throw new Error(
  2712. `Usage of :${nextTokenValue}() pseudo-class is not allowed inside regular pseudo: '${getLast(
  2713. context.standardPseudoNamesStack
  2714. )}'`
  2715. );
  2716. } else {
  2717. // stop RegularSelector value collecting
  2718. upToClosest(context, NODE.SELECTOR); // add ExtendedSelector to Selector children
  2719. addAstNodeByType(context, NODE.EXTENDED_SELECTOR);
  2720. }
  2721. }
  2722. };
  2723. // e.g. ':is(.page, .main) > .banner' or '*:not(span):not(p)'
  2724. const IS_OR_NOT_PSEUDO_SELECTING_ROOT = `html ${ASTERISK}`;
  2725. /**
  2726. * Checks if there are any ExtendedSelector node in selector list.
  2727. *
  2728. * @param selectorList Ast SelectorList node.
  2729. *
  2730. * @returns True if `selectorList` has any inner ExtendedSelector node.
  2731. */
  2732. const hasExtendedSelector = (selectorList) => {
  2733. return selectorList.children.some((selectorNode) => {
  2734. return selectorNode.children.some((selectorNodeChild) => {
  2735. return isExtendedSelectorNode(selectorNodeChild);
  2736. });
  2737. });
  2738. };
  2739. /**
  2740. * Converts selector list of RegularSelector nodes to string.
  2741. *
  2742. * @param selectorList Ast SelectorList node.
  2743. *
  2744. * @returns String representation for selector list of regular selectors.
  2745. */
  2746. const selectorListOfRegularsToString = (selectorList) => {
  2747. // if there is no ExtendedSelector in relative SelectorList
  2748. // it means that each Selector node has single child — RegularSelector node
  2749. // and their values should be combined to string
  2750. const standardCssSelectors = selectorList.children.map((selectorNode) => {
  2751. const selectorOnlyChild = getNodeOnlyChild(
  2752. selectorNode,
  2753. "Ast Selector node should have RegularSelector node"
  2754. );
  2755. return getNodeValue(selectorOnlyChild);
  2756. });
  2757. return standardCssSelectors.join(`${COMMA}${SPACE}`);
  2758. };
  2759. /**
  2760. * Updates children of `node` replacing them with `newChildren`.
  2761. * Important: modifies input `node` which is passed by reference.
  2762. *
  2763. * @param node Ast node to update.
  2764. * @param newChildren Array of new children for ast node.
  2765. *
  2766. * @returns Updated ast node.
  2767. */
  2768. const updateNodeChildren = (node, newChildren) => {
  2769. node.children = newChildren;
  2770. return node;
  2771. };
  2772. /**
  2773. * Recursively checks whether the ExtendedSelector node should be optimized.
  2774. * It has to be recursive because RelativePseudoClass has inner SelectorList node.
  2775. *
  2776. * @param currExtendedSelectorNode Ast ExtendedSelector node.
  2777. *
  2778. * @returns True is ExtendedSelector should be optimized.
  2779. */
  2780. const shouldOptimizeExtendedSelector = (currExtendedSelectorNode) => {
  2781. if (currExtendedSelectorNode === null) {
  2782. return false;
  2783. }
  2784. const extendedPseudoClassNode = getPseudoClassNode(
  2785. currExtendedSelectorNode
  2786. );
  2787. const pseudoName = getNodeName(extendedPseudoClassNode);
  2788. if (isAbsolutePseudoClass(pseudoName)) {
  2789. return false;
  2790. }
  2791. const relativeSelectorList = getRelativeSelectorListNode(
  2792. extendedPseudoClassNode
  2793. );
  2794. const innerSelectorNodes = relativeSelectorList.children; // simple checking for standard selectors in arg of :not() or :is() pseudo-class
  2795. // e.g. 'div > *:is(div, a, span)'
  2796. if (isOptimizationPseudoClass(pseudoName)) {
  2797. const areAllSelectorNodeChildrenRegular = innerSelectorNodes.every(
  2798. (selectorNode) => {
  2799. try {
  2800. const selectorOnlyChild = getNodeOnlyChild(
  2801. selectorNode,
  2802. "Selector node should have RegularSelector"
  2803. ); // it means that the only child is RegularSelector and it can be optimized
  2804. return isRegularSelectorNode(selectorOnlyChild);
  2805. } catch (e) {
  2806. return false;
  2807. }
  2808. }
  2809. );
  2810. if (areAllSelectorNodeChildrenRegular) {
  2811. return true;
  2812. }
  2813. } // for other extended pseudo-classes than :not() and :is()
  2814. return innerSelectorNodes.some((selectorNode) => {
  2815. return selectorNode.children.some((selectorNodeChild) => {
  2816. if (!isExtendedSelectorNode(selectorNodeChild)) {
  2817. return false;
  2818. } // check inner ExtendedSelector recursively
  2819. // e.g. 'div:has(*:not(.header))'
  2820. return shouldOptimizeExtendedSelector(selectorNodeChild);
  2821. });
  2822. });
  2823. };
  2824. /**
  2825. * Returns optimized ExtendedSelector node if it can be optimized
  2826. * or null if ExtendedSelector is fully optimized while function execution
  2827. * which means that value of `prevRegularSelectorNode` is updated.
  2828. *
  2829. * @param currExtendedSelectorNode Current ExtendedSelector node to optimize.
  2830. * @param prevRegularSelectorNode Previous RegularSelector node.
  2831. *
  2832. * @returns Ast node or null.
  2833. */
  2834. const getOptimizedExtendedSelector = (
  2835. currExtendedSelectorNode,
  2836. prevRegularSelectorNode
  2837. ) => {
  2838. if (!currExtendedSelectorNode) {
  2839. return null;
  2840. }
  2841. const extendedPseudoClassNode = getPseudoClassNode(
  2842. currExtendedSelectorNode
  2843. );
  2844. const relativeSelectorList = getRelativeSelectorListNode(
  2845. extendedPseudoClassNode
  2846. );
  2847. const hasInnerExtendedSelector =
  2848. hasExtendedSelector(relativeSelectorList);
  2849. if (!hasInnerExtendedSelector) {
  2850. // if there is no extended selectors for :not() or :is()
  2851. // e.g. 'div:not(.content, .main)'
  2852. const relativeSelectorListStr =
  2853. selectorListOfRegularsToString(relativeSelectorList);
  2854. const pseudoName = getNodeName(extendedPseudoClassNode); // eslint-disable-next-line max-len
  2855. const optimizedExtendedStr = `${COLON}${pseudoName}${BRACKET.PARENTHESES.LEFT}${relativeSelectorListStr}${BRACKET.PARENTHESES.RIGHT}`;
  2856. prevRegularSelectorNode.value = `${getNodeValue(
  2857. prevRegularSelectorNode
  2858. )}${optimizedExtendedStr}`;
  2859. return null;
  2860. } // eslint-disable-next-line @typescript-eslint/no-use-before-define
  2861. const optimizedRelativeSelectorList =
  2862. optimizeSelectorListNode(relativeSelectorList);
  2863. const optimizedExtendedPseudoClassNode = updateNodeChildren(
  2864. extendedPseudoClassNode,
  2865. [optimizedRelativeSelectorList]
  2866. );
  2867. return updateNodeChildren(currExtendedSelectorNode, [
  2868. optimizedExtendedPseudoClassNode,
  2869. ]);
  2870. };
  2871. /**
  2872. * Combines values of `previous` and `current` RegularSelector nodes.
  2873. * It may happen during the optimization when ExtendedSelector between RegularSelector node was optimized.
  2874. *
  2875. * @param current Current RegularSelector node.
  2876. * @param previous Previous RegularSelector node.
  2877. */
  2878. const optimizeCurrentRegularSelector = (current, previous) => {
  2879. previous.value = `${getNodeValue(previous)}${SPACE}${getNodeValue(
  2880. current
  2881. )}`;
  2882. };
  2883. /**
  2884. * Optimizes ast Selector node.
  2885. *
  2886. * @param selectorNode Ast Selector node.
  2887. *
  2888. * @returns Optimized ast node.
  2889. * @throws An error while collecting optimized nodes.
  2890. */
  2891. const optimizeSelectorNode = (selectorNode) => {
  2892. // non-optimized list of SelectorNode children
  2893. const rawSelectorNodeChildren = selectorNode.children; // for collecting optimized children list
  2894. const optimizedChildrenList = [];
  2895. let currentIndex = 0; // iterate through all children in non-optimized ast Selector node
  2896. while (currentIndex < rawSelectorNodeChildren.length) {
  2897. const currentChild = getItemByIndex(
  2898. rawSelectorNodeChildren,
  2899. currentIndex,
  2900. "currentChild should be specified"
  2901. ); // no need to optimize the very first child which is always RegularSelector node
  2902. if (currentIndex === 0) {
  2903. optimizedChildrenList.push(currentChild);
  2904. } else {
  2905. const prevRegularChild = getLastRegularChild(optimizedChildrenList);
  2906. if (isExtendedSelectorNode(currentChild)) {
  2907. // start checking with point is null
  2908. let optimizedExtendedSelector = null; // check whether the optimization is needed
  2909. let isOptimizationNeeded =
  2910. shouldOptimizeExtendedSelector(currentChild); // update optimizedExtendedSelector so it can be optimized recursively
  2911. // i.e. `getOptimizedExtendedSelector(optimizedExtendedSelector)` below
  2912. optimizedExtendedSelector = currentChild;
  2913. while (isOptimizationNeeded) {
  2914. // recursively optimize ExtendedSelector until no optimization needed
  2915. // e.g. div > *:is(.banner:not(.block))
  2916. optimizedExtendedSelector = getOptimizedExtendedSelector(
  2917. optimizedExtendedSelector,
  2918. prevRegularChild
  2919. );
  2920. isOptimizationNeeded = shouldOptimizeExtendedSelector(
  2921. optimizedExtendedSelector
  2922. );
  2923. } // if it was simple :not() of :is() with standard selector arg
  2924. // e.g. 'div:not([class][id])'
  2925. // or '.main > *:is([data-loaded], .banner)'
  2926. // after the optimization the ExtendedSelector node become part of RegularSelector
  2927. // so nothing to save eventually
  2928. // otherwise the optimized ExtendedSelector should be saved
  2929. // e.g. 'div:has(:not([class]))'
  2930. if (optimizedExtendedSelector !== null) {
  2931. optimizedChildrenList.push(optimizedExtendedSelector); // if optimization is not needed
  2932. const optimizedPseudoClass = getPseudoClassNode(
  2933. optimizedExtendedSelector
  2934. );
  2935. const optimizedPseudoName = getNodeName(optimizedPseudoClass); // parent element checking is used to apply :is() and :not() pseudo-classes as extended.
  2936. // as there is no parentNode for root element (html)
  2937. // so element selection should be limited to it's children
  2938. // e.g. '*:is(:has(.page))' -> 'html *:is(has(.page))'
  2939. // or '*:not(:has(span))' -> 'html *:not(:has(span))'
  2940. if (
  2941. getNodeValue(prevRegularChild) === ASTERISK &&
  2942. isOptimizationPseudoClass(optimizedPseudoName)
  2943. ) {
  2944. prevRegularChild.value = IS_OR_NOT_PSEUDO_SELECTING_ROOT;
  2945. }
  2946. }
  2947. } else if (isRegularSelectorNode(currentChild)) {
  2948. // in non-optimized ast, RegularSelector node may follow ExtendedSelector which should be optimized
  2949. // for example, for 'div:not(.content) > .banner' schematically it looks like
  2950. // non-optimized ast: [
  2951. // 1. RegularSelector: 'div'
  2952. // 2. ExtendedSelector: 'not(.content)'
  2953. // 3. RegularSelector: '> .banner'
  2954. // ]
  2955. // which after the ExtendedSelector looks like
  2956. // partly optimized ast: [
  2957. // 1. RegularSelector: 'div:not(.content)'
  2958. // 2. RegularSelector: '> .banner'
  2959. // ]
  2960. // so second RegularSelector value should be combined with first one
  2961. // optimized ast: [
  2962. // 1. RegularSelector: 'div:not(.content) > .banner'
  2963. // ]
  2964. // here we check **children of selectorNode** after previous optimization if it was
  2965. const lastOptimizedChild = getLast(optimizedChildrenList) || null;
  2966. if (isRegularSelectorNode(lastOptimizedChild)) {
  2967. optimizeCurrentRegularSelector(currentChild, prevRegularChild);
  2968. }
  2969. }
  2970. }
  2971. currentIndex += 1;
  2972. }
  2973. return updateNodeChildren(selectorNode, optimizedChildrenList);
  2974. };
  2975. /**
  2976. * Optimizes ast SelectorList node.
  2977. *
  2978. * @param selectorListNode SelectorList node.
  2979. *
  2980. * @returns Optimized ast node.
  2981. */
  2982. const optimizeSelectorListNode = (selectorListNode) => {
  2983. return updateNodeChildren(
  2984. selectorListNode,
  2985. selectorListNode.children.map((s) => optimizeSelectorNode(s))
  2986. );
  2987. };
  2988. /**
  2989. * Optimizes ast:
  2990. * If arg of :not() and :is() pseudo-classes does not contain extended selectors,
  2991. * native Document.querySelectorAll() can be used to query elements.
  2992. * It means that ExtendedSelector ast nodes can be removed
  2993. * and value of relevant RegularSelector node should be updated accordingly.
  2994. *
  2995. * @param ast Non-optimized ast.
  2996. *
  2997. * @returns Optimized ast.
  2998. */
  2999. const optimizeAst = (ast) => {
  3000. // ast is basically the selector list of selectors
  3001. return optimizeSelectorListNode(ast);
  3002. };
  3003. // https://github.com/AdguardTeam/ExtendedCss/issues/115
  3004. const XPATH_PSEUDO_SELECTING_ROOT = "body";
  3005. const NO_WHITESPACE_ERROR_PREFIX =
  3006. "No white space is allowed before or after extended pseudo-class name in selector";
  3007. /**
  3008. * Parses selector into ast for following element selection.
  3009. *
  3010. * @param selector Selector to parse.
  3011. *
  3012. * @returns Parsed ast.
  3013. * @throws An error on invalid selector.
  3014. */
  3015. const parse = (selector) => {
  3016. const tokens = tokenizeSelector(selector);
  3017. const context = {
  3018. ast: null,
  3019. pathToBufferNode: [],
  3020. extendedPseudoNamesStack: [],
  3021. extendedPseudoBracketsStack: [],
  3022. standardPseudoNamesStack: [],
  3023. standardPseudoBracketsStack: [],
  3024. isAttributeBracketsOpen: false,
  3025. attributeBuffer: "",
  3026. isRegexpOpen: false,
  3027. shouldOptimize: false,
  3028. };
  3029. let i = 0;
  3030. while (i < tokens.length) {
  3031. const token = tokens[i];
  3032. if (!token) {
  3033. break;
  3034. } // Token to process
  3035. const { type: tokenType, value: tokenValue } = token; // needed for SPACE and COLON tokens checking
  3036. const nextToken = tokens[i + 1];
  3037. const nextTokenType =
  3038. nextToken === null || nextToken === void 0 ? void 0 : nextToken.type;
  3039. const nextTokenValue =
  3040. nextToken === null || nextToken === void 0 ? void 0 : nextToken.value; // needed for limitations
  3041. // - :not() and :is() root element
  3042. // - :has() usage
  3043. // - white space before and after pseudo-class name
  3044. const nextToNextToken = tokens[i + 2];
  3045. const nextToNextTokenValue =
  3046. nextToNextToken === null || nextToNextToken === void 0
  3047. ? void 0
  3048. : nextToNextToken.value; // needed for COLON token checking for none-specified regular selector before extended one
  3049. // e.g. 'p, :hover'
  3050. // or '.banner, :contains(ads)'
  3051. const previousToken = tokens[i - 1];
  3052. const prevTokenType =
  3053. previousToken === null || previousToken === void 0
  3054. ? void 0
  3055. : previousToken.type;
  3056. const prevTokenValue =
  3057. previousToken === null || previousToken === void 0
  3058. ? void 0
  3059. : previousToken.value; // needed for proper parsing of regexp pattern arg
  3060. // e.g. ':matches-css(background-image: /^url\(https:\/\/example\.org\//)'
  3061. const previousToPreviousToken = tokens[i - 2];
  3062. const prevToPrevTokenValue =
  3063. previousToPreviousToken === null || previousToPreviousToken === void 0
  3064. ? void 0
  3065. : previousToPreviousToken.value;
  3066. let bufferNode = getBufferNode(context);
  3067. switch (tokenType) {
  3068. case TOKEN_TYPE.WORD:
  3069. if (bufferNode === null) {
  3070. // there is no buffer node only in one case — no ast collecting has been started
  3071. initAst(context, tokenValue);
  3072. } else if (isSelectorListNode(bufferNode)) {
  3073. // add new selector to selector list
  3074. addAstNodeByType(context, NODE.SELECTOR);
  3075. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  3076. } else if (isRegularSelectorNode(bufferNode)) {
  3077. updateBufferNode(context, tokenValue);
  3078. } else if (isExtendedSelectorNode(bufferNode)) {
  3079. // No white space is allowed between the name of extended pseudo-class
  3080. // and its opening parenthesis
  3081. // https://www.w3.org/TR/selectors-4/#pseudo-classes
  3082. // e.g. 'span:contains (text)'
  3083. if (
  3084. isWhiteSpaceChar(nextTokenValue) &&
  3085. nextToNextTokenValue === BRACKET.PARENTHESES.LEFT
  3086. ) {
  3087. throw new Error(`${NO_WHITESPACE_ERROR_PREFIX}: '${selector}'`);
  3088. }
  3089. const lowerCaseTokenValue = tokenValue.toLowerCase(); // save pseudo-class name for brackets balance checking
  3090. context.extendedPseudoNamesStack.push(lowerCaseTokenValue); // extended pseudo-class name are parsed in lower case
  3091. // as they should be case-insensitive
  3092. // https://www.w3.org/TR/selectors-4/#pseudo-classes
  3093. if (isAbsolutePseudoClass(lowerCaseTokenValue)) {
  3094. addAstNodeByType(
  3095. context,
  3096. NODE.ABSOLUTE_PSEUDO_CLASS,
  3097. lowerCaseTokenValue
  3098. );
  3099. } else {
  3100. // if it is not absolute pseudo-class, it must be relative one
  3101. // add RelativePseudoClass with tokenValue as pseudo-class name to ExtendedSelector children
  3102. addAstNodeByType(
  3103. context,
  3104. NODE.RELATIVE_PSEUDO_CLASS,
  3105. lowerCaseTokenValue
  3106. ); // for :not() and :is() pseudo-classes parsed ast should be optimized later
  3107. if (isOptimizationPseudoClass(lowerCaseTokenValue)) {
  3108. context.shouldOptimize = true;
  3109. }
  3110. }
  3111. } else if (isAbsolutePseudoClassNode(bufferNode)) {
  3112. // collect absolute pseudo-class arg
  3113. updateBufferNode(context, tokenValue);
  3114. } else if (isRelativePseudoClassNode(bufferNode)) {
  3115. initRelativeSubtree(context, tokenValue);
  3116. }
  3117. break;
  3118. case TOKEN_TYPE.MARK:
  3119. switch (tokenValue) {
  3120. case COMMA:
  3121. if (
  3122. !bufferNode ||
  3123. (typeof bufferNode !== "undefined" && !nextTokenValue)
  3124. ) {
  3125. // consider the selector is invalid if there is no bufferNode yet (e.g. ', a')
  3126. // or there is nothing after the comma while bufferNode is defined (e.g. 'div, ')
  3127. throw new Error(`'${selector}' is not a valid selector`);
  3128. } else if (isRegularSelectorNode(bufferNode)) {
  3129. if (context.isAttributeBracketsOpen) {
  3130. // the comma might be inside element attribute value
  3131. // e.g. 'div[data-comma="0,1"]'
  3132. updateBufferNode(context, tokenValue);
  3133. } else {
  3134. // new Selector should be collected to upper SelectorList
  3135. upToClosest(context, NODE.SELECTOR_LIST);
  3136. }
  3137. } else if (isAbsolutePseudoClassNode(bufferNode)) {
  3138. // the comma inside arg of absolute extended pseudo
  3139. // e.g. 'div:xpath(//h3[contains(text(),"Share it!")]/..)'
  3140. updateBufferNode(context, tokenValue);
  3141. } else if (isSelectorNode(bufferNode)) {
  3142. // new Selector should be collected to upper SelectorList
  3143. // if parser position is on Selector node
  3144. upToClosest(context, NODE.SELECTOR_LIST);
  3145. }
  3146. break;
  3147. case SPACE:
  3148. // it might be complex selector with extended pseudo-class inside it
  3149. // and the space is between that complex selector and following regular selector
  3150. // parser position is on ` ` before `span` now:
  3151. // e.g. 'div:has(img).banner span'
  3152. // so we need to check whether the new ast node should be added (example above)
  3153. // or previous regular selector node should be updated
  3154. if (
  3155. isRegularSelectorNode(bufferNode) && // no need to update the buffer node if attribute value is being parsed
  3156. // e.g. 'div:not([id])[style="position: absolute; z-index: 10000;"]'
  3157. // parser position inside attribute ↑
  3158. !context.isAttributeBracketsOpen
  3159. ) {
  3160. bufferNode = getUpdatedBufferNode(context);
  3161. }
  3162. if (isRegularSelectorNode(bufferNode)) {
  3163. // standard selectors with white space between colon and name of pseudo
  3164. // are invalid for native document.querySelectorAll() anyway,
  3165. // so throwing the error here is better
  3166. // than proper parsing of invalid selector and passing it further.
  3167. // first of all do not check attributes
  3168. // e.g. div[style="text-align: center"]
  3169. if (
  3170. !context.isAttributeBracketsOpen && // check the space after the colon and before the pseudo
  3171. // e.g. '.block: nth-child(2)
  3172. ((prevTokenValue === COLON &&
  3173. nextTokenType === TOKEN_TYPE.WORD) || // or after the pseudo and before the opening parenthesis
  3174. // e.g. '.block:nth-child (2)
  3175. (prevTokenType === TOKEN_TYPE.WORD &&
  3176. nextTokenValue === BRACKET.PARENTHESES.LEFT))
  3177. ) {
  3178. throw new Error(`'${selector}' is not a valid selector`);
  3179. } // collect current tokenValue to value of RegularSelector
  3180. // if it is the last token or standard selector continues after the space.
  3181. // otherwise it will be skipped
  3182. if (
  3183. !nextTokenValue ||
  3184. doesRegularContinueAfterSpace(
  3185. nextTokenType,
  3186. nextTokenValue
  3187. ) || // we also should collect space inside attribute value
  3188. // e.g. `[onclick^="window.open ('https://example.com/share?url="]`
  3189. // parser position ↑
  3190. context.isAttributeBracketsOpen
  3191. ) {
  3192. updateBufferNode(context, tokenValue);
  3193. }
  3194. }
  3195. if (isAbsolutePseudoClassNode(bufferNode)) {
  3196. // space inside extended pseudo-class arg
  3197. // e.g. 'span:contains(some text)'
  3198. updateBufferNode(context, tokenValue);
  3199. }
  3200. if (isRelativePseudoClassNode(bufferNode)) {
  3201. // init with empty value RegularSelector
  3202. // as the space is not needed for selector value
  3203. // e.g. 'p:not( .content )'
  3204. initRelativeSubtree(context);
  3205. }
  3206. if (isSelectorNode(bufferNode)) {
  3207. // do NOT add RegularSelector if parser position on space BEFORE the comma in selector list
  3208. // e.g. '.block:has(> img) , .banner)'
  3209. if (
  3210. doesRegularContinueAfterSpace(nextTokenType, nextTokenValue)
  3211. ) {
  3212. // regular selector might be after the extended one.
  3213. // extra space before combinator or selector should not be collected
  3214. // e.g. '.banner:upward(2) .block'
  3215. // '.banner:upward(2) > .block'
  3216. // so no tokenValue passed to addAnySelectorNode()
  3217. addAstNodeByType(context, NODE.REGULAR_SELECTOR);
  3218. }
  3219. }
  3220. break;
  3221. case DESCENDANT_COMBINATOR:
  3222. case CHILD_COMBINATOR:
  3223. case NEXT_SIBLING_COMBINATOR:
  3224. case SUBSEQUENT_SIBLING_COMBINATOR:
  3225. case SEMICOLON:
  3226. case SLASH:
  3227. case BACKSLASH:
  3228. case SINGLE_QUOTE:
  3229. case DOUBLE_QUOTE:
  3230. case CARET:
  3231. case DOLLAR_SIGN:
  3232. case BRACKET.CURLY.LEFT:
  3233. case BRACKET.CURLY.RIGHT:
  3234. case ASTERISK:
  3235. case ID_MARKER:
  3236. case CLASS_MARKER:
  3237. case BRACKET.SQUARE.LEFT:
  3238. // it might be complex selector with extended pseudo-class inside it
  3239. // and the space is between that complex selector and following regular selector
  3240. // e.g. 'div:has(img).banner' // parser position is on `.` before `banner` now
  3241. // 'div:has(img)[attr]' // parser position is on `[` before `attr` now
  3242. // so we need to check whether the new ast node should be added (example above)
  3243. // or previous regular selector node should be updated
  3244. if (COMBINATORS.includes(tokenValue)) {
  3245. if (bufferNode === null) {
  3246. // cases where combinator at very beginning of a selector
  3247. // e.g. '> div'
  3248. // or '~ .banner'
  3249. // or even '+js(overlay-buster)' which not a selector at all
  3250. // but may be validated by FilterCompiler so error message should be appropriate
  3251. throw new Error(`'${selector}' is not a valid selector`);
  3252. }
  3253. bufferNode = getUpdatedBufferNode(context);
  3254. }
  3255. if (bufferNode === null) {
  3256. // no ast collecting has been started
  3257. // e.g. '.banner > p'
  3258. // or '#top > div.ad'
  3259. // or '[class][style][attr]'
  3260. // or '*:not(span)'
  3261. initAst(context, tokenValue);
  3262. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  3263. // e.g. '[class^="banner-"]'
  3264. context.isAttributeBracketsOpen = true;
  3265. }
  3266. } else if (isRegularSelectorNode(bufferNode)) {
  3267. if (
  3268. tokenValue === BRACKET.CURLY.LEFT &&
  3269. !(context.isAttributeBracketsOpen || context.isRegexpOpen)
  3270. ) {
  3271. // e.g. 'div { content: "'
  3272. throw new Error(`'${selector}' is not a valid selector`);
  3273. } // collect the mark to the value of RegularSelector node
  3274. updateBufferNode(context, tokenValue);
  3275. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  3276. // needed for proper handling element attribute value with comma
  3277. // e.g. 'div[data-comma="0,1"]'
  3278. context.isAttributeBracketsOpen = true;
  3279. }
  3280. } else if (isAbsolutePseudoClassNode(bufferNode)) {
  3281. // collect the mark to the arg of AbsolutePseudoClass node
  3282. updateBufferNode(context, tokenValue); // 'isRegexpOpen' flag is needed for brackets balancing inside extended pseudo-class arg
  3283. if (
  3284. tokenValue === SLASH &&
  3285. context.extendedPseudoNamesStack.length > 0
  3286. ) {
  3287. if (
  3288. prevTokenValue === SLASH &&
  3289. prevToPrevTokenValue === BACKSLASH
  3290. ) {
  3291. // it may be specific url regexp pattern in arg of pseudo-class
  3292. // e.g. ':matches-css(background-image: /^url\(https:\/\/example\.org\//)'
  3293. // parser position is on final slash before `)` ↑
  3294. context.isRegexpOpen = false;
  3295. } else if (prevTokenValue && prevTokenValue !== BACKSLASH) {
  3296. if (
  3297. isRegexpOpening(
  3298. context,
  3299. prevTokenValue,
  3300. getNodeValue(bufferNode)
  3301. )
  3302. ) {
  3303. context.isRegexpOpen = !context.isRegexpOpen;
  3304. } else {
  3305. // otherwise force `isRegexpOpen` flag to `false`
  3306. context.isRegexpOpen = false;
  3307. }
  3308. }
  3309. }
  3310. } else if (isRelativePseudoClassNode(bufferNode)) {
  3311. // add SelectorList to children of RelativePseudoClass node
  3312. initRelativeSubtree(context, tokenValue);
  3313. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  3314. // besides of creating the relative subtree
  3315. // opening square bracket means start of attribute
  3316. // e.g. 'div:not([class="content"])'
  3317. // 'div:not([href*="window.print()"])'
  3318. context.isAttributeBracketsOpen = true;
  3319. }
  3320. } else if (isSelectorNode(bufferNode)) {
  3321. // after the extended pseudo closing parentheses
  3322. // parser position is on Selector node
  3323. // and regular selector can be after the extended one
  3324. // e.g. '.banner:upward(2)> .block'
  3325. // or '.inner:nth-ancestor(1)~ .banner'
  3326. if (COMBINATORS.includes(tokenValue)) {
  3327. addAstNodeByType(
  3328. context,
  3329. NODE.REGULAR_SELECTOR,
  3330. tokenValue
  3331. );
  3332. } else if (!context.isRegexpOpen) {
  3333. // it might be complex selector with extended pseudo-class inside it.
  3334. // parser position is on `.` now:
  3335. // e.g. 'div:has(img).banner'
  3336. // so we need to get last regular selector node and update its value
  3337. bufferNode = getContextLastRegularSelectorNode(context);
  3338. updateBufferNode(context, tokenValue);
  3339. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  3340. // handle attribute in compound selector after extended pseudo-class
  3341. // e.g. 'div:not(.top)[style="z-index: 10000;"]'
  3342. // parser position ↑
  3343. context.isAttributeBracketsOpen = true;
  3344. }
  3345. }
  3346. } else if (isSelectorListNode(bufferNode)) {
  3347. // add Selector to SelectorList
  3348. addAstNodeByType(context, NODE.SELECTOR); // and RegularSelector as it is always the first child of Selector
  3349. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  3350. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  3351. // handle simple attribute selector in selector list
  3352. // e.g. '.banner, [class^="ad-"]'
  3353. context.isAttributeBracketsOpen = true;
  3354. }
  3355. }
  3356. break;
  3357. case BRACKET.SQUARE.RIGHT:
  3358. if (isRegularSelectorNode(bufferNode)) {
  3359. // unescaped `]` in regular selector allowed only inside attribute value
  3360. if (
  3361. !context.isAttributeBracketsOpen &&
  3362. prevTokenValue !== BACKSLASH
  3363. ) {
  3364. // e.g. 'div]'
  3365. // eslint-disable-next-line max-len
  3366. throw new Error(
  3367. `'${selector}' is not a valid selector due to '${tokenValue}' after '${getNodeValue(
  3368. bufferNode
  3369. )}'`
  3370. );
  3371. } // needed for proper parsing regular selectors after the attributes with comma
  3372. // e.g. 'div[data-comma="0,1"] > img'
  3373. if (isAttributeClosing(context)) {
  3374. context.isAttributeBracketsOpen = false; // reset attribute buffer on closing `]`
  3375. context.attributeBuffer = "";
  3376. } // collect the bracket to the value of RegularSelector node
  3377. updateBufferNode(context, tokenValue);
  3378. }
  3379. if (isAbsolutePseudoClassNode(bufferNode)) {
  3380. // :xpath() expended pseudo-class arg might contain square bracket
  3381. // so it should be collected
  3382. // e.g. 'div:xpath(//h3[contains(text(),"Share it!")]/..)'
  3383. updateBufferNode(context, tokenValue);
  3384. }
  3385. break;
  3386. case COLON:
  3387. // No white space is allowed between the colon and the following name of the pseudo-class
  3388. // https://www.w3.org/TR/selectors-4/#pseudo-classes
  3389. // e.g. 'span: contains(text)'
  3390. if (
  3391. isWhiteSpaceChar(nextTokenValue) &&
  3392. nextToNextTokenValue &&
  3393. SUPPORTED_PSEUDO_CLASSES.includes(nextToNextTokenValue)
  3394. ) {
  3395. throw new Error(
  3396. `${NO_WHITESPACE_ERROR_PREFIX}: '${selector}'`
  3397. );
  3398. }
  3399. if (bufferNode === null) {
  3400. // no ast collecting has been started
  3401. if (nextTokenValue === XPATH_PSEUDO_CLASS_MARKER) {
  3402. // limit applying of "naked" :xpath pseudo-class
  3403. // https://github.com/AdguardTeam/ExtendedCss/issues/115
  3404. initAst(context, XPATH_PSEUDO_SELECTING_ROOT);
  3405. } else if (
  3406. nextTokenValue === UPWARD_PSEUDO_CLASS_MARKER ||
  3407. nextTokenValue === NTH_ANCESTOR_PSEUDO_CLASS_MARKER
  3408. ) {
  3409. // selector should be specified before :nth-ancestor() or :upward()
  3410. // e.g. ':nth-ancestor(3)'
  3411. // or ':upward(span)'
  3412. throw new Error(
  3413. `${NO_SELECTOR_ERROR_PREFIX} before :${nextTokenValue}() pseudo-class`
  3414. );
  3415. } else {
  3416. // make it more obvious if selector starts with pseudo with no tag specified
  3417. // e.g. ':has(a)' -> '*:has(a)'
  3418. // or ':empty' -> '*:empty'
  3419. initAst(context, ASTERISK);
  3420. } // bufferNode should be updated for following checking
  3421. bufferNode = getBufferNode(context);
  3422. }
  3423. if (isSelectorListNode(bufferNode)) {
  3424. // bufferNode is SelectorList after comma has been parsed.
  3425. // parser position is on colon now:
  3426. // e.g. 'img,:not(.content)'
  3427. addAstNodeByType(context, NODE.SELECTOR); // add empty value RegularSelector anyway as any selector should start with it
  3428. // and check previous token on the next step
  3429. addAstNodeByType(context, NODE.REGULAR_SELECTOR); // bufferNode should be updated for following checking
  3430. bufferNode = getBufferNode(context);
  3431. }
  3432. if (isRegularSelectorNode(bufferNode)) {
  3433. // it can be extended or standard pseudo
  3434. // e.g. '#share, :contains(share it)'
  3435. // or 'div,:hover'
  3436. // of 'div:has(+:contains(text))' // position is after '+'
  3437. if (
  3438. (prevTokenValue && COMBINATORS.includes(prevTokenValue)) ||
  3439. prevTokenValue === COMMA
  3440. ) {
  3441. // case with colon at the start of string - e.g. ':contains(text)'
  3442. // is covered by 'bufferNode === null' above at start of COLON checking
  3443. updateBufferNode(context, ASTERISK);
  3444. }
  3445. handleNextTokenOnColon(
  3446. context,
  3447. selector,
  3448. tokenValue,
  3449. nextTokenValue,
  3450. nextToNextTokenValue
  3451. );
  3452. }
  3453. if (isSelectorNode(bufferNode)) {
  3454. // e.g. 'div:contains(text):'
  3455. if (!nextTokenValue) {
  3456. throw new Error(
  3457. `Invalid colon ':' at the end of selector: '${selector}'`
  3458. );
  3459. } // after the extended pseudo closing parentheses
  3460. // parser position is on Selector node
  3461. // and there is might be another extended selector.
  3462. // parser position is on colon before 'upward':
  3463. // e.g. 'p:contains(PR):upward(2)'
  3464. if (isSupportedPseudoClass(nextTokenValue.toLowerCase())) {
  3465. // if supported extended pseudo-class is next to colon
  3466. // add ExtendedSelector to Selector children
  3467. addAstNodeByType(context, NODE.EXTENDED_SELECTOR);
  3468. } else if (
  3469. nextTokenValue.toLowerCase() === REMOVE_PSEUDO_MARKER
  3470. ) {
  3471. // :remove() pseudo-class should be handled before
  3472. // as it is not about element selecting but actions with elements
  3473. // e.g. '#banner:upward(2):remove()'
  3474. throw new Error(
  3475. `${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`
  3476. );
  3477. } else {
  3478. // otherwise it is standard pseudo after extended pseudo-class in complex selector
  3479. // and colon should be collected to value of previous RegularSelector
  3480. // e.g. 'body *:not(input)::selection'
  3481. // 'input:matches-css(padding: 10):checked'
  3482. bufferNode = getContextLastRegularSelectorNode(context);
  3483. handleNextTokenOnColon(
  3484. context,
  3485. selector,
  3486. tokenValue,
  3487. nextTokenType,
  3488. nextToNextTokenValue
  3489. );
  3490. }
  3491. }
  3492. if (isAbsolutePseudoClassNode(bufferNode)) {
  3493. // :xpath() pseudo-class should be the last of extended pseudo-classes
  3494. if (
  3495. getNodeName(bufferNode) === XPATH_PSEUDO_CLASS_MARKER &&
  3496. nextTokenValue &&
  3497. SUPPORTED_PSEUDO_CLASSES.includes(nextTokenValue) &&
  3498. nextToNextTokenValue === BRACKET.PARENTHESES.LEFT
  3499. ) {
  3500. throw new Error(
  3501. `:xpath() pseudo-class should be the last in selector: '${selector}'`
  3502. );
  3503. } // collecting arg for absolute pseudo-class
  3504. // e.g. 'div:matches-css(width:400px)'
  3505. updateBufferNode(context, tokenValue);
  3506. }
  3507. if (isRelativePseudoClassNode(bufferNode)) {
  3508. if (!nextTokenValue) {
  3509. // e.g. 'div:has(:'
  3510. throw new Error(
  3511. `Invalid pseudo-class arg at the end of selector: '${selector}'`
  3512. );
  3513. } // make it more obvious if selector starts with pseudo with no tag specified
  3514. // parser position is on colon inside :has() arg
  3515. // e.g. 'div:has(:contains(text))'
  3516. // or 'div:not(:empty)'
  3517. initRelativeSubtree(context, ASTERISK);
  3518. if (!isSupportedPseudoClass(nextTokenValue.toLowerCase())) {
  3519. // collect the colon to value of RegularSelector
  3520. // e.g. 'div:not(:empty)'
  3521. updateBufferNode(context, tokenValue); // parentheses should be balanced only for functional pseudo-classes
  3522. // e.g. '.yellow:not(:nth-child(3))'
  3523. if (nextToNextTokenValue === BRACKET.PARENTHESES.LEFT) {
  3524. context.standardPseudoNamesStack.push(nextTokenValue);
  3525. }
  3526. } else {
  3527. // add ExtendedSelector to Selector children
  3528. // e.g. 'div:has(:contains(text))'
  3529. upToClosest(context, NODE.SELECTOR);
  3530. addAstNodeByType(context, NODE.EXTENDED_SELECTOR);
  3531. }
  3532. }
  3533. break;
  3534. case BRACKET.PARENTHESES.LEFT:
  3535. // start of pseudo-class arg
  3536. if (isAbsolutePseudoClassNode(bufferNode)) {
  3537. // no brackets balancing needed inside
  3538. // 1. :xpath() extended pseudo-class arg
  3539. // 2. regexp arg for other extended pseudo-classes
  3540. if (
  3541. getNodeName(bufferNode) !== XPATH_PSEUDO_CLASS_MARKER &&
  3542. context.isRegexpOpen
  3543. ) {
  3544. // if the parentheses is escaped it should be part of regexp
  3545. // collect it to arg of AbsolutePseudoClass
  3546. // e.g. 'div:matches-css(background-image: /^url\\("data:image\\/gif;base64.+/)'
  3547. updateBufferNode(context, tokenValue);
  3548. } else {
  3549. // otherwise brackets should be balanced
  3550. // e.g. 'div:xpath(//h3[contains(text(),"Share it!")]/..)'
  3551. context.extendedPseudoBracketsStack.push(tokenValue); // eslint-disable-next-line max-len
  3552. if (
  3553. context.extendedPseudoBracketsStack.length >
  3554. context.extendedPseudoNamesStack.length
  3555. ) {
  3556. updateBufferNode(context, tokenValue);
  3557. }
  3558. }
  3559. }
  3560. if (isRegularSelectorNode(bufferNode)) {
  3561. // continue RegularSelector value collecting for standard pseudo-classes
  3562. // e.g. '.banner:where(div)'
  3563. if (context.standardPseudoNamesStack.length > 0) {
  3564. updateBufferNode(context, tokenValue);
  3565. context.standardPseudoBracketsStack.push(tokenValue);
  3566. } // parentheses inside attribute value should be part of RegularSelector value
  3567. // e.g. 'div:not([href*="window.print()"])' <-- parser position
  3568. // is on the `(` after `print` ↑
  3569. if (context.isAttributeBracketsOpen) {
  3570. updateBufferNode(context, tokenValue);
  3571. }
  3572. }
  3573. if (isRelativePseudoClassNode(bufferNode)) {
  3574. // save opening bracket for balancing
  3575. // e.g. 'div:not()' // position is on `(`
  3576. context.extendedPseudoBracketsStack.push(tokenValue);
  3577. }
  3578. break;
  3579. case BRACKET.PARENTHESES.RIGHT:
  3580. if (isAbsolutePseudoClassNode(bufferNode)) {
  3581. // no brackets balancing needed inside
  3582. // 1. :xpath() extended pseudo-class arg
  3583. // 2. regexp arg for other extended pseudo-classes
  3584. if (
  3585. getNodeName(bufferNode) !== XPATH_PSEUDO_CLASS_MARKER &&
  3586. context.isRegexpOpen
  3587. ) {
  3588. // if closing bracket is part of regexp
  3589. // simply save it to pseudo-class arg
  3590. updateBufferNode(context, tokenValue);
  3591. } else {
  3592. // remove stacked open parentheses for brackets balance
  3593. // e.g. 'h3:contains((Ads))'
  3594. // or 'div:xpath(//h3[contains(text(),"Share it!")]/..)'
  3595. context.extendedPseudoBracketsStack.pop();
  3596. if (getNodeName(bufferNode) !== XPATH_PSEUDO_CLASS_MARKER) {
  3597. // for all other absolute pseudo-classes except :xpath()
  3598. // remove stacked name of extended pseudo-class
  3599. context.extendedPseudoNamesStack.pop(); // eslint-disable-next-line max-len
  3600. if (
  3601. context.extendedPseudoBracketsStack.length >
  3602. context.extendedPseudoNamesStack.length
  3603. ) {
  3604. // if brackets stack is not empty yet,
  3605. // save tokenValue to arg of AbsolutePseudoClass
  3606. // parser position on first closing bracket after 'Ads':
  3607. // e.g. 'h3:contains((Ads))'
  3608. updateBufferNode(context, tokenValue);
  3609. } else if (
  3610. context.extendedPseudoBracketsStack.length >= 0 &&
  3611. context.extendedPseudoNamesStack.length >= 0
  3612. ) {
  3613. // assume it is combined extended pseudo-classes
  3614. // parser position on first closing bracket after 'advert':
  3615. // e.g. 'div:has(.banner, :contains(advert))'
  3616. upToClosest(context, NODE.SELECTOR);
  3617. }
  3618. } else {
  3619. // for :xpath()
  3620. // eslint-disable-next-line max-len
  3621. if (
  3622. context.extendedPseudoBracketsStack.length <
  3623. context.extendedPseudoNamesStack.length
  3624. ) {
  3625. // remove stacked name of extended pseudo-class
  3626. // if there are less brackets than pseudo-class names
  3627. // with means last removes bracket was closing for pseudo-class
  3628. context.extendedPseudoNamesStack.pop();
  3629. } else {
  3630. // otherwise the bracket is part of arg
  3631. updateBufferNode(context, tokenValue);
  3632. }
  3633. }
  3634. }
  3635. }
  3636. if (isRegularSelectorNode(bufferNode)) {
  3637. if (context.isAttributeBracketsOpen) {
  3638. // parentheses inside attribute value should be part of RegularSelector value
  3639. // e.g. 'div:not([href*="window.print()"])' <-- parser position
  3640. // is on the `)` after `print(` ↑
  3641. updateBufferNode(context, tokenValue);
  3642. } else if (
  3643. context.standardPseudoNamesStack.length > 0 &&
  3644. context.standardPseudoBracketsStack.length > 0
  3645. ) {
  3646. // standard pseudo-class was processing.
  3647. // collect the closing bracket to value of RegularSelector
  3648. // parser position is on bracket after 'class' now:
  3649. // e.g. 'div:where(.class)'
  3650. updateBufferNode(context, tokenValue); // remove bracket and pseudo name from stacks
  3651. context.standardPseudoBracketsStack.pop();
  3652. const lastStandardPseudo =
  3653. context.standardPseudoNamesStack.pop();
  3654. if (!lastStandardPseudo) {
  3655. // standard pseudo should be in standardPseudoNamesStack
  3656. // as related to standardPseudoBracketsStack
  3657. throw new Error(
  3658. `Parsing error. Invalid selector: ${selector}`
  3659. );
  3660. } // Disallow :has() after regular pseudo-elements
  3661. // https://bugs.chromium.org/p/chromium/issues/detail?id=669058#c54 [3]
  3662. if (
  3663. Object.values(REGULAR_PSEUDO_ELEMENTS).includes(
  3664. lastStandardPseudo
  3665. ) && // check token which is next to closing parentheses and token after it
  3666. // parser position is on bracket after 'foo' now:
  3667. // e.g. '::part(foo):has(.a)'
  3668. nextTokenValue === COLON &&
  3669. nextToNextTokenValue &&
  3670. HAS_PSEUDO_CLASS_MARKERS.includes(nextToNextTokenValue)
  3671. ) {
  3672. // eslint-disable-next-line max-len
  3673. throw new Error(
  3674. `Usage of :${nextToNextTokenValue}() pseudo-class is not allowed after any regular pseudo-element: '${lastStandardPseudo}'`
  3675. );
  3676. }
  3677. } else {
  3678. // extended pseudo-class was processing.
  3679. // e.g. 'div:has(h3)'
  3680. // remove bracket and pseudo name from stacks
  3681. context.extendedPseudoBracketsStack.pop();
  3682. context.extendedPseudoNamesStack.pop();
  3683. upToClosest(context, NODE.EXTENDED_SELECTOR); // go to upper selector for possible selector continuation after extended pseudo-class
  3684. // e.g. 'div:has(h3) > img'
  3685. upToClosest(context, NODE.SELECTOR);
  3686. }
  3687. }
  3688. if (isSelectorNode(bufferNode)) {
  3689. // after inner extended pseudo-class bufferNode is Selector.
  3690. // parser position is on last bracket now:
  3691. // e.g. 'div:has(.banner, :contains(ads))'
  3692. context.extendedPseudoBracketsStack.pop();
  3693. context.extendedPseudoNamesStack.pop();
  3694. upToClosest(context, NODE.EXTENDED_SELECTOR);
  3695. upToClosest(context, NODE.SELECTOR);
  3696. }
  3697. if (isRelativePseudoClassNode(bufferNode)) {
  3698. // save opening bracket for balancing
  3699. // e.g. 'div:not()' // position is on `)`
  3700. // context.extendedPseudoBracketsStack.push(tokenValue);
  3701. if (
  3702. context.extendedPseudoNamesStack.length > 0 &&
  3703. context.extendedPseudoBracketsStack.length > 0
  3704. ) {
  3705. context.extendedPseudoBracketsStack.pop();
  3706. context.extendedPseudoNamesStack.pop();
  3707. }
  3708. }
  3709. break;
  3710. case LINE_FEED:
  3711. case FORM_FEED:
  3712. case CARRIAGE_RETURN:
  3713. // such characters at start and end of selector should be trimmed
  3714. // so is there is one them among tokens, it is not valid selector
  3715. throw new Error(`'${selector}' is not a valid selector`);
  3716. case TAB:
  3717. // allow tab only inside attribute value
  3718. // as there are such valid rules in filter lists
  3719. // e.g. 'div[style^="margin-right: auto; text-align: left;',
  3720. // parser position ↑
  3721. if (
  3722. isRegularSelectorNode(bufferNode) &&
  3723. context.isAttributeBracketsOpen
  3724. ) {
  3725. updateBufferNode(context, tokenValue);
  3726. } else {
  3727. // otherwise not valid
  3728. throw new Error(`'${selector}' is not a valid selector`);
  3729. }
  3730. }
  3731. break;
  3732. // no default statement for Marks as they are limited to SUPPORTED_SELECTOR_MARKS
  3733. // and all other symbol combinations are tokenized as Word
  3734. // so error for invalid Word will be thrown later while element selecting by parsed ast
  3735. default:
  3736. throw new Error(`Unknown type of token: '${tokenValue}'`);
  3737. }
  3738. i += 1;
  3739. }
  3740. if (context.ast === null) {
  3741. throw new Error(`'${selector}' is not a valid selector`);
  3742. }
  3743. if (
  3744. context.extendedPseudoNamesStack.length > 0 ||
  3745. context.extendedPseudoBracketsStack.length > 0
  3746. ) {
  3747. // eslint-disable-next-line max-len
  3748. throw new Error(
  3749. `Unbalanced brackets for extended pseudo-class: '${getLast(
  3750. context.extendedPseudoNamesStack
  3751. )}'`
  3752. );
  3753. }
  3754. if (context.isAttributeBracketsOpen) {
  3755. throw new Error(
  3756. `Unbalanced attribute brackets in selector: '${selector}'`
  3757. );
  3758. }
  3759. return context.shouldOptimize ? optimizeAst(context.ast) : context.ast;
  3760. };
  3761. const natives = {
  3762. MutationObserver:
  3763. window.MutationObserver || window.WebKitMutationObserver,
  3764. };
  3765. /**
  3766. * Class NativeTextContent is needed to intercept and save the native Node textContent getter
  3767. * for proper work of :contains() pseudo-class as it may be mocked.
  3768. *
  3769. * @see {@link https://github.com/AdguardTeam/ExtendedCss/issues/127}
  3770. */
  3771. class NativeTextContent {
  3772. /**
  3773. * Native Node.
  3774. */
  3775. /**
  3776. * Native Node textContent getter.
  3777. */
  3778. /**
  3779. * Stores native node.
  3780. */
  3781. constructor() {
  3782. this.nativeNode = window.Node || Node;
  3783. }
  3784. /**
  3785. * Sets native Node textContext getter to `getter` class field.
  3786. */
  3787. setGetter() {
  3788. var _Object$getOwnPropert;
  3789. this.getter =
  3790. (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(
  3791. this.nativeNode.prototype,
  3792. "textContent"
  3793. )) === null || _Object$getOwnPropert === void 0
  3794. ? void 0
  3795. : _Object$getOwnPropert.get;
  3796. }
  3797. }
  3798. const nativeTextContent = new NativeTextContent();
  3799. /**
  3800. * Returns textContent of passed domElement.
  3801. *
  3802. * @param domElement DOM element.
  3803. *
  3804. * @returns DOM element textContent.
  3805. */
  3806. const getNodeTextContent = (domElement) => {
  3807. if (nativeTextContent.getter) {
  3808. return nativeTextContent.getter.apply(domElement);
  3809. } // if ExtendedCss.init() has not been executed and there is no nodeTextContentGetter,
  3810. // use simple approach, especially when init() is not really needed, e.g. local tests
  3811. return domElement.textContent || "";
  3812. };
  3813. /**
  3814. * Returns element selector text based on it's tagName and attributes.
  3815. *
  3816. * @param element DOM element.
  3817. *
  3818. * @returns String representation of `element`.
  3819. */
  3820. const getElementSelectorDesc = (element) => {
  3821. let selectorText = element.tagName.toLowerCase();
  3822. selectorText += Array.from(element.attributes)
  3823. .map((attr) => {
  3824. return `[${attr.name}="${element.getAttribute(attr.name)}"]`;
  3825. })
  3826. .join("");
  3827. return selectorText;
  3828. };
  3829. /**
  3830. * Returns path to a DOM element as a selector string.
  3831. *
  3832. * @param inputEl Input element.
  3833. *
  3834. * @returns String path to a DOM element.
  3835. * @throws An error if `inputEl` in not instance of `Element`.
  3836. */
  3837. const getElementSelectorPath = (inputEl) => {
  3838. if (!(inputEl instanceof Element)) {
  3839. throw new Error("Function received argument with wrong type");
  3840. }
  3841. let el;
  3842. el = inputEl;
  3843. const path = []; // we need to check '!!el' first because it is possible
  3844. // that some ancestor of the inputEl was removed before it
  3845. while (!!el && el.nodeType === Node.ELEMENT_NODE) {
  3846. let selector = el.nodeName.toLowerCase();
  3847. if (el.id && typeof el.id === "string") {
  3848. selector += `#${el.id}`;
  3849. path.unshift(selector);
  3850. break;
  3851. }
  3852. let sibling = el;
  3853. let nth = 1;
  3854. while (sibling.previousElementSibling) {
  3855. sibling = sibling.previousElementSibling;
  3856. if (
  3857. sibling.nodeType === Node.ELEMENT_NODE &&
  3858. sibling.nodeName.toLowerCase() === selector
  3859. ) {
  3860. nth += 1;
  3861. }
  3862. }
  3863. if (nth !== 1) {
  3864. selector += `:nth-of-type(${nth})`;
  3865. }
  3866. path.unshift(selector);
  3867. el = el.parentElement;
  3868. }
  3869. return path.join(" > ");
  3870. };
  3871. /**
  3872. * Checks whether the element is instance of HTMLElement.
  3873. *
  3874. * @param element Element to check.
  3875. *
  3876. * @returns True if `element` is HTMLElement.
  3877. */
  3878. const isHtmlElement = (element) => {
  3879. return element instanceof HTMLElement;
  3880. };
  3881. /**
  3882. * Takes `element` and returns its parent element.
  3883. *
  3884. * @param element Element.
  3885. * @param errorMessage Optional error message to throw.
  3886. *
  3887. * @returns Parent of `element`.
  3888. * @throws An error if element has no parent element.
  3889. */
  3890. const getParent = (element, errorMessage) => {
  3891. const { parentElement } = element;
  3892. if (!parentElement) {
  3893. throw new Error(errorMessage || "Element does no have parent element");
  3894. }
  3895. return parentElement;
  3896. };
  3897. /**
  3898. * Checks whether the `error` has `message` property which type is string.
  3899. *
  3900. * @param error Error object.
  3901. *
  3902. * @returns True if `error` has message.
  3903. */
  3904. const isErrorWithMessage = (error) => {
  3905. return (
  3906. typeof error === "object" &&
  3907. error !== null &&
  3908. "message" in error &&
  3909. typeof error.message === "string"
  3910. );
  3911. };
  3912. /**
  3913. * Converts `maybeError` to error object with message.
  3914. *
  3915. * @param maybeError Possible error.
  3916. *
  3917. * @returns Error object with defined `message` property.
  3918. */
  3919. const toErrorWithMessage = (maybeError) => {
  3920. if (isErrorWithMessage(maybeError)) {
  3921. return maybeError;
  3922. }
  3923. try {
  3924. return new Error(JSON.stringify(maybeError));
  3925. } catch {
  3926. // fallback in case if there is an error happened during the maybeError stringifying
  3927. // like with circular references for example
  3928. return new Error(String(maybeError));
  3929. }
  3930. };
  3931. /**
  3932. * Returns error message from `error`.
  3933. * May be helpful to handle caught errors.
  3934. *
  3935. * @param error Error object.
  3936. *
  3937. * @returns Message of `error`.
  3938. */
  3939. const getErrorMessage = (error) => {
  3940. return toErrorWithMessage(error).message;
  3941. };
  3942. const logger = {
  3943. /**
  3944. * Safe console.error version.
  3945. */
  3946. error:
  3947. typeof console !== "undefined" && console.error && console.error.bind
  3948. ? console.error.bind(window.console)
  3949. : console.error,
  3950. /**
  3951. * Safe console.info version.
  3952. */
  3953. info:
  3954. typeof console !== "undefined" && console.info && console.info.bind
  3955. ? console.info.bind(window.console)
  3956. : console.info,
  3957. };
  3958. /**
  3959. * Returns string without suffix.
  3960. *
  3961. * @param str Input string.
  3962. * @param suffix Needed to remove.
  3963. *
  3964. * @returns String without suffix.
  3965. */
  3966. const removeSuffix = (str, suffix) => {
  3967. const index = str.indexOf(suffix, str.length - suffix.length);
  3968. if (index >= 0) {
  3969. return str.substring(0, index);
  3970. }
  3971. return str;
  3972. };
  3973. /**
  3974. * Replaces all `pattern`s with `replacement` in `input` string.
  3975. * String.replaceAll() polyfill because it is not supported by old browsers, e.g. Chrome 55.
  3976. *
  3977. * @see {@link https://caniuse.com/?search=String.replaceAll}
  3978. *
  3979. * @param input Input string to process.
  3980. * @param pattern Find in the input string.
  3981. * @param replacement Replace the pattern with.
  3982. *
  3983. * @returns Modified string.
  3984. */
  3985. const replaceAll = (input, pattern, replacement) => {
  3986. if (!input) {
  3987. return input;
  3988. }
  3989. return input.split(pattern).join(replacement);
  3990. };
  3991. /**
  3992. * Converts string pattern to regular expression.
  3993. *
  3994. * @param str String to convert.
  3995. *
  3996. * @returns Regular expression converted from pattern `str`.
  3997. */
  3998. const toRegExp = (str) => {
  3999. if (str.startsWith(SLASH) && str.endsWith(SLASH)) {
  4000. return new RegExp(str.slice(1, -1));
  4001. }
  4002. const escaped = str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  4003. return new RegExp(escaped);
  4004. };
  4005. /**
  4006. * Converts any simple type value to string type,
  4007. * e.g. `undefined` -> `'undefined'`.
  4008. *
  4009. * @param value Any type value.
  4010. *
  4011. * @returns String representation of `value`.
  4012. */
  4013. const convertTypeIntoString = (value) => {
  4014. let output;
  4015. switch (value) {
  4016. case undefined:
  4017. output = "undefined";
  4018. break;
  4019. case null:
  4020. output = "null";
  4021. break;
  4022. default:
  4023. output = value.toString();
  4024. }
  4025. return output;
  4026. };
  4027. /**
  4028. * Converts instance of string value into other simple types,
  4029. * e.g. `'null'` -> `null`, `'true'` -> `true`.
  4030. *
  4031. * @param value String-type value.
  4032. *
  4033. * @returns Its own type representation of string-type `value`.
  4034. */
  4035. const convertTypeFromString = (value) => {
  4036. const numValue = Number(value);
  4037. let output;
  4038. if (!Number.isNaN(numValue)) {
  4039. output = numValue;
  4040. } else {
  4041. switch (value) {
  4042. case "undefined":
  4043. output = undefined;
  4044. break;
  4045. case "null":
  4046. output = null;
  4047. break;
  4048. case "true":
  4049. output = true;
  4050. break;
  4051. case "false":
  4052. output = false;
  4053. break;
  4054. default:
  4055. output = value;
  4056. }
  4057. }
  4058. return output;
  4059. };
  4060. const SAFARI_USER_AGENT_REGEXP =
  4061. /\sVersion\/(\d{2}\.\d)(.+\s|\s)(Safari)\//;
  4062. const isSafariBrowser = SAFARI_USER_AGENT_REGEXP.test(navigator.userAgent);
  4063. /**
  4064. * Checks whether the browser userAgent is supported.
  4065. *
  4066. * @param userAgent User agent of browser.
  4067. *
  4068. * @returns False only for Internet Explorer.
  4069. */
  4070. const isUserAgentSupported = (userAgent) => {
  4071. // do not support Internet Explorer
  4072. if (userAgent.includes("MSIE") || userAgent.includes("Trident/")) {
  4073. return false;
  4074. }
  4075. return true;
  4076. };
  4077. /**
  4078. * Checks whether the current browser is supported.
  4079. *
  4080. * @returns False for Internet Explorer, otherwise true.
  4081. */
  4082. const isBrowserSupported = () => {
  4083. return isUserAgentSupported(navigator.userAgent);
  4084. };
  4085. /**
  4086. * CSS_PROPERTY is needed for style values normalization.
  4087. *
  4088. * IMPORTANT: it is used as 'const' instead of 'enum' to avoid side effects
  4089. * during ExtendedCss import into other libraries.
  4090. */
  4091. const CSS_PROPERTY = {
  4092. BACKGROUND: "background",
  4093. BACKGROUND_IMAGE: "background-image",
  4094. CONTENT: "content",
  4095. OPACITY: "opacity",
  4096. };
  4097. const REGEXP_ANY_SYMBOL = ".*";
  4098. const REGEXP_WITH_FLAGS_REGEXP = /^\s*\/.*\/[gmisuy]*\s*$/;
  4099. /**
  4100. * Removes quotes for specified content value.
  4101. *
  4102. * For example, content style declaration with `::before` can be set as '-' (e.g. unordered list)
  4103. * which displayed as simple dash `-` with no quotes.
  4104. * But CSSStyleDeclaration.getPropertyValue('content') will return value
  4105. * wrapped into quotes, e.g. '"-"', which should be removed
  4106. * because filters maintainers does not use any quotes in real rules.
  4107. *
  4108. * @param str Input string.
  4109. *
  4110. * @returns String with no quotes for content value.
  4111. */
  4112. const removeContentQuotes = (str) => {
  4113. return str.replace(/^(["'])([\s\S]*)\1$/, "$2");
  4114. };
  4115. /**
  4116. * Adds quotes for specified background url value.
  4117. *
  4118. * If background-image is specified **without** quotes:
  4119. * e.g. 'background: url(data:image/gif;base64,R0lGODlhAQA7)'.
  4120. *
  4121. * CSSStyleDeclaration.getPropertyValue('background-image') may return value **with** quotes:
  4122. * e.g. 'background: url("data:image/gif;base64,R0lGODlhAQA7")'.
  4123. *
  4124. * So we add quotes for compatibility since filters maintainers might use quotes in real rules.
  4125. *
  4126. * @param str Input string.
  4127. *
  4128. * @returns String with unified quotes for background url value.
  4129. */
  4130. const addUrlPropertyQuotes = (str) => {
  4131. if (!str.includes('url("')) {
  4132. const re = /url\((.*?)\)/g;
  4133. return str.replace(re, 'url("$1")');
  4134. }
  4135. return str;
  4136. };
  4137. /**
  4138. * Adds quotes to url arg for consistent property value matching.
  4139. */
  4140. const addUrlQuotesTo = {
  4141. regexpArg: (str) => {
  4142. // e.g. /^url\\([a-z]{4}:[a-z]{5}/
  4143. // or /^url\\(data\\:\\image\\/gif;base64.+/
  4144. const re = /(\^)?url(\\)?\\\((\w|\[\w)/g;
  4145. return str.replace(re, '$1url$2\\(\\"?$3');
  4146. },
  4147. noneRegexpArg: addUrlPropertyQuotes,
  4148. };
  4149. /**
  4150. * Escapes regular expression string.
  4151. *
  4152. * @see {@link https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp}
  4153. *
  4154. * @param str Input string.
  4155. *
  4156. * @returns Escaped regular expression string.
  4157. */
  4158. const escapeRegExp = (str) => {
  4159. // should be escaped . * + ? ^ $ { } ( ) | [ ] / \
  4160. // except of * | ^
  4161. const specials = [
  4162. ".",
  4163. "+",
  4164. "?",
  4165. "$",
  4166. "{",
  4167. "}",
  4168. "(",
  4169. ")",
  4170. "[",
  4171. "]",
  4172. "\\",
  4173. "/",
  4174. ];
  4175. const specialsRegex = new RegExp(`[${specials.join("\\")}]`, "g");
  4176. return str.replace(specialsRegex, "\\$&");
  4177. };
  4178. /**
  4179. * Converts :matches-css() arg property value match to regexp.
  4180. *
  4181. * @param rawValue Style match value pattern.
  4182. *
  4183. * @returns Arg of :matches-css() converted to regular expression.
  4184. */
  4185. const convertStyleMatchValueToRegexp = (rawValue) => {
  4186. let value;
  4187. if (rawValue.startsWith(SLASH) && rawValue.endsWith(SLASH)) {
  4188. // For regex patterns double quotes `"` and backslashes `\` should be escaped
  4189. value = addUrlQuotesTo.regexpArg(rawValue);
  4190. value = value.slice(1, -1);
  4191. } else {
  4192. // For non-regex patterns parentheses `(` `)` and square brackets `[` `]`
  4193. // should be unescaped, because their escaping in filter rules is required
  4194. value = addUrlQuotesTo.noneRegexpArg(rawValue);
  4195. value = value.replace(/\\([\\()[\]"])/g, "$1");
  4196. value = escapeRegExp(value); // e.g. div:matches-css(background-image: url(data:*))
  4197. value = replaceAll(value, ASTERISK, REGEXP_ANY_SYMBOL);
  4198. }
  4199. return new RegExp(value, "i");
  4200. };
  4201. /**
  4202. * Makes some properties values compatible.
  4203. *
  4204. * @param propertyName Name of style property.
  4205. * @param propertyValue Value of style property.
  4206. *
  4207. * @returns Normalized values for some CSS properties.
  4208. */
  4209. const normalizePropertyValue = (propertyName, propertyValue) => {
  4210. let normalized = "";
  4211. switch (propertyName) {
  4212. case CSS_PROPERTY.BACKGROUND:
  4213. case CSS_PROPERTY.BACKGROUND_IMAGE:
  4214. // sometimes url property does not have quotes
  4215. // so we add them for consistent matching
  4216. normalized = addUrlPropertyQuotes(propertyValue);
  4217. break;
  4218. case CSS_PROPERTY.CONTENT:
  4219. normalized = removeContentQuotes(propertyValue);
  4220. break;
  4221. case CSS_PROPERTY.OPACITY:
  4222. // https://bugs.webkit.org/show_bug.cgi?id=93445
  4223. normalized = isSafariBrowser
  4224. ? (Math.round(parseFloat(propertyValue) * 100) / 100).toString()
  4225. : propertyValue;
  4226. break;
  4227. default:
  4228. normalized = propertyValue;
  4229. }
  4230. return normalized;
  4231. };
  4232. /**
  4233. * Returns domElement style property value
  4234. * by css property name and standard pseudo-element.
  4235. *
  4236. * @param domElement DOM element.
  4237. * @param propertyName CSS property name.
  4238. * @param regularPseudoElement Standard pseudo-element — '::before', '::after' etc.
  4239. *
  4240. * @returns String containing the value of a specified CSS property.
  4241. */
  4242. const getComputedStylePropertyValue = (
  4243. domElement,
  4244. propertyName,
  4245. regularPseudoElement
  4246. ) => {
  4247. const style = window.getComputedStyle(domElement, regularPseudoElement);
  4248. const propertyValue = style.getPropertyValue(propertyName);
  4249. return normalizePropertyValue(propertyName, propertyValue);
  4250. };
  4251. /**
  4252. * Parses arg of absolute pseudo-class into 'name' and 'value' if set.
  4253. *
  4254. * Used for :matches-css() - with COLON as separator,
  4255. * for :matches-attr() and :matches-property() - with EQUAL_SIGN as separator.
  4256. *
  4257. * @param pseudoArg Arg of pseudo-class.
  4258. * @param separator Divider symbol.
  4259. *
  4260. * @returns Parsed 'matches' pseudo-class arg data.
  4261. */
  4262. const getPseudoArgData = (pseudoArg, separator) => {
  4263. const index = pseudoArg.indexOf(separator);
  4264. let name;
  4265. let value;
  4266. if (index > -1) {
  4267. name = pseudoArg.substring(0, index).trim();
  4268. value = pseudoArg.substring(index + 1).trim();
  4269. } else {
  4270. name = pseudoArg;
  4271. }
  4272. return {
  4273. name,
  4274. value,
  4275. };
  4276. };
  4277. /**
  4278. * Parses :matches-css() pseudo-class arg
  4279. * where regular pseudo-element can be a part of arg
  4280. * e.g. 'div:matches-css(before, color: rgb(255, 255, 255))' <-- obsolete `:matches-css-before()`.
  4281. *
  4282. * @param pseudoName Pseudo-class name.
  4283. * @param rawArg Pseudo-class arg.
  4284. *
  4285. * @returns Parsed :matches-css() pseudo-class arg data.
  4286. * @throws An error on invalid `rawArg`.
  4287. */
  4288. const parseStyleMatchArg = (pseudoName, rawArg) => {
  4289. const { name, value } = getPseudoArgData(rawArg, COMMA);
  4290. let regularPseudoElement = name;
  4291. let styleMatchArg = value; // check whether the string part before the separator is valid regular pseudo-element,
  4292. // otherwise `regularPseudoElement` is null, and `styleMatchArg` is rawArg
  4293. if (!Object.values(REGULAR_PSEUDO_ELEMENTS).includes(name)) {
  4294. regularPseudoElement = null;
  4295. styleMatchArg = rawArg;
  4296. }
  4297. if (!styleMatchArg) {
  4298. throw new Error(
  4299. `Required style property argument part is missing in :${pseudoName}() arg: '${rawArg}'`
  4300. );
  4301. } // if regularPseudoElement is not `null`
  4302. if (regularPseudoElement) {
  4303. // pseudo-element should have two colon marks for Window.getComputedStyle() due to the syntax:
  4304. // https://www.w3.org/TR/selectors-4/#pseudo-element-syntax
  4305. // ':matches-css(before, content: ads)' ->> '::before'
  4306. regularPseudoElement = `${COLON}${COLON}${regularPseudoElement}`;
  4307. }
  4308. return {
  4309. regularPseudoElement,
  4310. styleMatchArg,
  4311. };
  4312. };
  4313. /**
  4314. * Checks whether the domElement is matched by :matches-css() arg.
  4315. *
  4316. * @param argsData Pseudo-class name, arg, and dom element to check.
  4317. *
  4318. @returns True if DOM element is matched.
  4319. * @throws An error on invalid pseudo-class arg.
  4320. */
  4321. const isStyleMatched = (argsData) => {
  4322. const { pseudoName, pseudoArg, domElement } = argsData;
  4323. const { regularPseudoElement, styleMatchArg } = parseStyleMatchArg(
  4324. pseudoName,
  4325. pseudoArg
  4326. );
  4327. const { name: matchName, value: matchValue } = getPseudoArgData(
  4328. styleMatchArg,
  4329. COLON
  4330. );
  4331. if (!matchName || !matchValue) {
  4332. throw new Error(
  4333. `Required property name or value is missing in :${pseudoName}() arg: '${styleMatchArg}'`
  4334. );
  4335. }
  4336. let valueRegexp;
  4337. try {
  4338. valueRegexp = convertStyleMatchValueToRegexp(matchValue);
  4339. } catch (e) {
  4340. logger.error(getErrorMessage(e));
  4341. throw new Error(
  4342. `Invalid argument of :${pseudoName}() pseudo-class: '${styleMatchArg}'`
  4343. );
  4344. }
  4345. const value = getComputedStylePropertyValue(
  4346. domElement,
  4347. matchName,
  4348. regularPseudoElement
  4349. );
  4350. return valueRegexp && valueRegexp.test(value);
  4351. };
  4352. /**
  4353. * Validates string arg for :matches-attr() and :matches-property().
  4354. *
  4355. * @param arg Pseudo-class arg.
  4356. *
  4357. * @returns True if 'matches' pseudo-class string arg is valid.
  4358. */
  4359. const validateStrMatcherArg = (arg) => {
  4360. if (arg.includes(SLASH)) {
  4361. return false;
  4362. }
  4363. if (!/^[\w-]+$/.test(arg)) {
  4364. return false;
  4365. }
  4366. return true;
  4367. };
  4368. /**
  4369. * Returns valid arg for :matches-attr() and :matcher-property().
  4370. *
  4371. * @param rawArg Arg pattern.
  4372. * @param [isWildcardAllowed=false] Flag for wildcard (`*`) using as pseudo-class arg.
  4373. *
  4374. * @returns Valid arg for :matches-attr() and :matcher-property().
  4375. * @throws An error on invalid `rawArg`.
  4376. */
  4377. const getValidMatcherArg = function (rawArg) {
  4378. let isWildcardAllowed =
  4379. arguments.length > 1 && arguments[1] !== undefined
  4380. ? arguments[1]
  4381. : false;
  4382. // if rawArg is missing for pseudo-class
  4383. // e.g. :matches-attr()
  4384. // error will be thrown before getValidMatcherArg() is called:
  4385. // name or arg is missing in AbsolutePseudoClass
  4386. let arg;
  4387. if (
  4388. rawArg.length > 1 &&
  4389. rawArg.startsWith(DOUBLE_QUOTE) &&
  4390. rawArg.endsWith(DOUBLE_QUOTE)
  4391. ) {
  4392. rawArg = rawArg.slice(1, -1);
  4393. }
  4394. if (rawArg === "") {
  4395. // e.g. :matches-property("")
  4396. throw new Error("Argument should be specified. Empty arg is invalid.");
  4397. }
  4398. if (rawArg.startsWith(SLASH) && rawArg.endsWith(SLASH)) {
  4399. // e.g. :matches-property("//")
  4400. if (rawArg.length > 2) {
  4401. arg = toRegExp(rawArg);
  4402. } else {
  4403. throw new Error(`Invalid regexp: '${rawArg}'`);
  4404. }
  4405. } else if (rawArg.includes(ASTERISK)) {
  4406. if (rawArg === ASTERISK && !isWildcardAllowed) {
  4407. // e.g. :matches-attr(*)
  4408. throw new Error(`Argument should be more specific than ${rawArg}`);
  4409. }
  4410. arg = replaceAll(rawArg, ASTERISK, REGEXP_ANY_SYMBOL);
  4411. arg = new RegExp(arg);
  4412. } else {
  4413. if (!validateStrMatcherArg(rawArg)) {
  4414. throw new Error(`Invalid argument: '${rawArg}'`);
  4415. }
  4416. arg = rawArg;
  4417. }
  4418. return arg;
  4419. };
  4420. /**
  4421. * Parses pseudo-class argument and returns parsed data.
  4422. *
  4423. * @param pseudoName Extended pseudo-class name.
  4424. * @param pseudoArg Extended pseudo-class argument.
  4425. *
  4426. * @returns Parsed pseudo-class argument data.
  4427. * @throws An error if attribute name is missing in pseudo-class arg.
  4428. */
  4429. const getRawMatchingData = (pseudoName, pseudoArg) => {
  4430. const { name: rawName, value: rawValue } = getPseudoArgData(
  4431. pseudoArg,
  4432. EQUAL_SIGN
  4433. );
  4434. if (!rawName) {
  4435. throw new Error(
  4436. `Required attribute name is missing in :${pseudoName} arg: ${pseudoArg}`
  4437. );
  4438. }
  4439. return {
  4440. rawName,
  4441. rawValue,
  4442. };
  4443. };
  4444. /**
  4445. * Checks whether the domElement is matched by :matches-attr() arg.
  4446. *
  4447. * @param argsData Pseudo-class name, arg, and dom element to check.
  4448. *
  4449. @returns True if DOM element is matched.
  4450. * @throws An error on invalid arg of pseudo-class.
  4451. */
  4452. const isAttributeMatched = (argsData) => {
  4453. const { pseudoName, pseudoArg, domElement } = argsData;
  4454. const elementAttributes = domElement.attributes; // no match if dom element has no attributes
  4455. if (elementAttributes.length === 0) {
  4456. return false;
  4457. }
  4458. const { rawName: rawAttrName, rawValue: rawAttrValue } =
  4459. getRawMatchingData(pseudoName, pseudoArg);
  4460. let attrNameMatch;
  4461. try {
  4462. attrNameMatch = getValidMatcherArg(rawAttrName);
  4463. } catch (e) {
  4464. const errorMessage = getErrorMessage(e);
  4465. logger.error(errorMessage);
  4466. throw new SyntaxError(errorMessage);
  4467. }
  4468. let isMatched = false;
  4469. let i = 0;
  4470. while (i < elementAttributes.length && !isMatched) {
  4471. const attr = elementAttributes[i];
  4472. if (!attr) {
  4473. break;
  4474. }
  4475. const isNameMatched =
  4476. attrNameMatch instanceof RegExp
  4477. ? attrNameMatch.test(attr.name)
  4478. : attrNameMatch === attr.name;
  4479. if (!rawAttrValue) {
  4480. // for rules with no attribute value specified
  4481. // e.g. :matches-attr("/regex/") or :matches-attr("attr-name")
  4482. isMatched = isNameMatched;
  4483. } else {
  4484. let attrValueMatch;
  4485. try {
  4486. attrValueMatch = getValidMatcherArg(rawAttrValue);
  4487. } catch (e) {
  4488. const errorMessage = getErrorMessage(e);
  4489. logger.error(errorMessage);
  4490. throw new SyntaxError(errorMessage);
  4491. }
  4492. const isValueMatched =
  4493. attrValueMatch instanceof RegExp
  4494. ? attrValueMatch.test(attr.value)
  4495. : attrValueMatch === attr.value;
  4496. isMatched = isNameMatched && isValueMatched;
  4497. }
  4498. i += 1;
  4499. }
  4500. return isMatched;
  4501. };
  4502. /**
  4503. * Parses raw :matches-property() arg which may be chain of properties.
  4504. *
  4505. * @param input Argument of :matches-property().
  4506. *
  4507. * @returns Arg of :matches-property() as array of strings or regular expressions.
  4508. * @throws An error on invalid chain.
  4509. */
  4510. const parseRawPropChain = (input) => {
  4511. if (
  4512. input.length > 1 &&
  4513. input.startsWith(DOUBLE_QUOTE) &&
  4514. input.endsWith(DOUBLE_QUOTE)
  4515. ) {
  4516. input = input.slice(1, -1);
  4517. }
  4518. const chainChunks = input.split(DOT);
  4519. const chainPatterns = [];
  4520. let patternBuffer = "";
  4521. let isRegexpPattern = false;
  4522. let i = 0;
  4523. while (i < chainChunks.length) {
  4524. const chunk = getItemByIndex(
  4525. chainChunks,
  4526. i,
  4527. `Invalid pseudo-class arg: '${input}'`
  4528. );
  4529. if (
  4530. chunk.startsWith(SLASH) &&
  4531. chunk.endsWith(SLASH) &&
  4532. chunk.length > 2
  4533. ) {
  4534. // regexp pattern with no dot in it, e.g. /propName/
  4535. chainPatterns.push(chunk);
  4536. } else if (chunk.startsWith(SLASH)) {
  4537. // if chunk is a start of regexp pattern
  4538. isRegexpPattern = true;
  4539. patternBuffer += chunk;
  4540. } else if (chunk.endsWith(SLASH)) {
  4541. isRegexpPattern = false; // restore dot removed while splitting
  4542. // e.g. testProp./.{1,5}/
  4543. patternBuffer += `.${chunk}`;
  4544. chainPatterns.push(patternBuffer);
  4545. patternBuffer = "";
  4546. } else {
  4547. // if there are few dots in regexp pattern
  4548. // so chunk might be in the middle of it
  4549. if (isRegexpPattern) {
  4550. patternBuffer += chunk;
  4551. } else {
  4552. // otherwise it is string pattern
  4553. chainPatterns.push(chunk);
  4554. }
  4555. }
  4556. i += 1;
  4557. }
  4558. if (patternBuffer.length > 0) {
  4559. throw new Error(`Invalid regexp property pattern '${input}'`);
  4560. }
  4561. const chainMatchPatterns = chainPatterns.map((pattern) => {
  4562. if (pattern.length === 0) {
  4563. // e.g. '.prop.id' or 'nested..test'
  4564. throw new Error(
  4565. `Empty pattern '${pattern}' is invalid in chain '${input}'`
  4566. );
  4567. }
  4568. let validPattern;
  4569. try {
  4570. validPattern = getValidMatcherArg(pattern, true);
  4571. } catch (e) {
  4572. logger.error(getErrorMessage(e));
  4573. throw new Error(
  4574. `Invalid property pattern '${pattern}' in property chain '${input}'`
  4575. );
  4576. }
  4577. return validPattern;
  4578. });
  4579. return chainMatchPatterns;
  4580. };
  4581. /**
  4582. * Checks if the property exists in the base object (recursively).
  4583. *
  4584. * @param base Element to check.
  4585. * @param chain Array of objects - parsed string property chain.
  4586. * @param [output=[]] Result acc.
  4587. *
  4588. * @returns Array of parsed data — representation of `base`-related `chain`.
  4589. */
  4590. const filterRootsByRegexpChain = function (base, chain) {
  4591. let output =
  4592. arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  4593. const tempProp = getFirst(chain);
  4594. if (chain.length === 1) {
  4595. let key;
  4596. for (key in base) {
  4597. if (tempProp instanceof RegExp) {
  4598. if (tempProp.test(key)) {
  4599. output.push({
  4600. base,
  4601. prop: key,
  4602. value: base[key],
  4603. });
  4604. }
  4605. } else if (tempProp === key) {
  4606. output.push({
  4607. base,
  4608. prop: tempProp,
  4609. value: base[key],
  4610. });
  4611. }
  4612. }
  4613. return output;
  4614. } // if there is a regexp prop in input chain
  4615. // e.g. 'unit./^ad.+/.src' for 'unit.ad-1gf2.src unit.ad-fgd34.src'),
  4616. // every base keys should be tested by regexp and it can be more that one results
  4617. if (tempProp instanceof RegExp) {
  4618. const nextProp = chain.slice(1);
  4619. const baseKeys = [];
  4620. for (const key in base) {
  4621. if (tempProp.test(key)) {
  4622. baseKeys.push(key);
  4623. }
  4624. }
  4625. baseKeys.forEach((key) => {
  4626. var _Object$getOwnPropert;
  4627. const item =
  4628. (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(
  4629. base,
  4630. key
  4631. )) === null || _Object$getOwnPropert === void 0
  4632. ? void 0
  4633. : _Object$getOwnPropert.value;
  4634. filterRootsByRegexpChain(item, nextProp, output);
  4635. });
  4636. }
  4637. if (base && typeof tempProp === "string") {
  4638. var _Object$getOwnPropert2;
  4639. const nextBase =
  4640. (_Object$getOwnPropert2 = Object.getOwnPropertyDescriptor(
  4641. base,
  4642. tempProp
  4643. )) === null || _Object$getOwnPropert2 === void 0
  4644. ? void 0
  4645. : _Object$getOwnPropert2.value;
  4646. chain = chain.slice(1);
  4647. if (nextBase !== undefined) {
  4648. filterRootsByRegexpChain(nextBase, chain, output);
  4649. }
  4650. }
  4651. return output;
  4652. };
  4653. /**
  4654. * Checks whether the domElement is matched by :matches-property() arg.
  4655. *
  4656. * @param argsData Pseudo-class name, arg, and dom element to check.
  4657. *
  4658. @returns True if DOM element is matched.
  4659. * @throws An error on invalid prop in chain.
  4660. */
  4661. const isPropertyMatched = (argsData) => {
  4662. const { pseudoName, pseudoArg, domElement } = argsData;
  4663. const { rawName: rawPropertyName, rawValue: rawPropertyValue } =
  4664. getRawMatchingData(pseudoName, pseudoArg); // chained property name cannot include '/' or '.'
  4665. // so regex prop names with such escaped characters are invalid
  4666. if (rawPropertyName.includes("\\/") || rawPropertyName.includes("\\.")) {
  4667. throw new Error(
  4668. `Invalid :${pseudoName} name pattern: ${rawPropertyName}`
  4669. );
  4670. }
  4671. let propChainMatches;
  4672. try {
  4673. propChainMatches = parseRawPropChain(rawPropertyName);
  4674. } catch (e) {
  4675. const errorMessage = getErrorMessage(e);
  4676. logger.error(errorMessage);
  4677. throw new SyntaxError(errorMessage);
  4678. }
  4679. const ownerObjArr = filterRootsByRegexpChain(
  4680. domElement,
  4681. propChainMatches
  4682. );
  4683. if (ownerObjArr.length === 0) {
  4684. return false;
  4685. }
  4686. let isMatched = true;
  4687. if (rawPropertyValue) {
  4688. let propValueMatch;
  4689. try {
  4690. propValueMatch = getValidMatcherArg(rawPropertyValue);
  4691. } catch (e) {
  4692. const errorMessage = getErrorMessage(e);
  4693. logger.error(errorMessage);
  4694. throw new SyntaxError(errorMessage);
  4695. }
  4696. if (propValueMatch) {
  4697. for (let i = 0; i < ownerObjArr.length; i += 1) {
  4698. var _ownerObjArr$i;
  4699. const realValue =
  4700. (_ownerObjArr$i = ownerObjArr[i]) === null ||
  4701. _ownerObjArr$i === void 0
  4702. ? void 0
  4703. : _ownerObjArr$i.value;
  4704. if (propValueMatch instanceof RegExp) {
  4705. isMatched = propValueMatch.test(convertTypeIntoString(realValue));
  4706. } else {
  4707. // handle 'null' and 'undefined' property values set as string
  4708. if (realValue === "null" || realValue === "undefined") {
  4709. isMatched = propValueMatch === realValue;
  4710. break;
  4711. }
  4712. isMatched = convertTypeFromString(propValueMatch) === realValue;
  4713. }
  4714. if (isMatched) {
  4715. break;
  4716. }
  4717. }
  4718. }
  4719. }
  4720. return isMatched;
  4721. };
  4722. /**
  4723. * Checks whether the textContent is matched by :contains arg.
  4724. *
  4725. * @param argsData Pseudo-class name, arg, and dom element to check.
  4726. *
  4727. @returns True if DOM element is matched.
  4728. * @throws An error on invalid arg of pseudo-class.
  4729. */
  4730. const isTextMatched = (argsData) => {
  4731. const { pseudoName, pseudoArg, domElement } = argsData;
  4732. const textContent = getNodeTextContent(domElement);
  4733. let isTextContentMatched;
  4734. let pseudoArgToMatch = pseudoArg;
  4735. if (
  4736. pseudoArgToMatch.startsWith(SLASH) &&
  4737. REGEXP_WITH_FLAGS_REGEXP.test(pseudoArgToMatch)
  4738. ) {
  4739. // regexp arg
  4740. const flagsIndex = pseudoArgToMatch.lastIndexOf("/");
  4741. const flagsStr = pseudoArgToMatch.substring(flagsIndex + 1);
  4742. pseudoArgToMatch = pseudoArgToMatch
  4743. .substring(0, flagsIndex + 1)
  4744. .slice(1, -1)
  4745. .replace(/\\([\\"])/g, "$1");
  4746. let regex;
  4747. try {
  4748. regex = new RegExp(pseudoArgToMatch, flagsStr);
  4749. } catch (e) {
  4750. throw new Error(
  4751. `Invalid argument of :${pseudoName}() pseudo-class: ${pseudoArg}`
  4752. );
  4753. }
  4754. isTextContentMatched = regex.test(textContent);
  4755. } else {
  4756. // none-regexp arg
  4757. pseudoArgToMatch = pseudoArgToMatch.replace(/\\([\\()[\]"])/g, "$1");
  4758. isTextContentMatched = textContent.includes(pseudoArgToMatch);
  4759. }
  4760. return isTextContentMatched;
  4761. };
  4762. /**
  4763. * Validates number arg for :nth-ancestor() and :upward() pseudo-classes.
  4764. *
  4765. * @param rawArg Raw arg of pseudo-class.
  4766. * @param pseudoName Pseudo-class name.
  4767. *
  4768. * @returns Valid number arg for :nth-ancestor() and :upward().
  4769. * @throws An error on invalid `rawArg`.
  4770. */
  4771. const getValidNumberAncestorArg = (rawArg, pseudoName) => {
  4772. const deep = Number(rawArg);
  4773. if (Number.isNaN(deep) || deep < 1 || deep >= 256) {
  4774. throw new Error(
  4775. `Invalid argument of :${pseudoName} pseudo-class: '${rawArg}'`
  4776. );
  4777. }
  4778. return deep;
  4779. };
  4780. /**
  4781. * Returns nth ancestor by 'deep' number arg OR undefined if ancestor range limit exceeded.
  4782. *
  4783. * @param domElement DOM element to find ancestor for.
  4784. * @param nth Depth up to needed ancestor.
  4785. * @param pseudoName Pseudo-class name.
  4786. *
  4787. * @returns Ancestor element found in DOM, or null if not found.
  4788. * @throws An error on invalid `nth` arg.
  4789. */
  4790. const getNthAncestor = (domElement, nth, pseudoName) => {
  4791. let ancestor = null;
  4792. let i = 0;
  4793. while (i < nth) {
  4794. ancestor = domElement.parentElement;
  4795. if (!ancestor) {
  4796. throw new Error(
  4797. `Out of DOM: Argument of :${pseudoName}() pseudo-class is too big '${nth}'.`
  4798. );
  4799. }
  4800. domElement = ancestor;
  4801. i += 1;
  4802. }
  4803. return ancestor;
  4804. };
  4805. /**
  4806. * Validates standard CSS selector.
  4807. *
  4808. * @param selector Standard selector.
  4809. *
  4810. * @returns True if standard CSS selector is valid.
  4811. */
  4812. const validateStandardSelector = (selector) => {
  4813. let isValid;
  4814. try {
  4815. document.querySelectorAll(selector);
  4816. isValid = true;
  4817. } catch (e) {
  4818. isValid = false;
  4819. }
  4820. return isValid;
  4821. };
  4822. /**
  4823. * Wrapper to run matcher `callback` with `args`
  4824. * and throw error with `errorMessage` if `callback` run fails.
  4825. *
  4826. * @param callback Matcher callback.
  4827. * @param argsData Args needed for matcher callback.
  4828. * @param errorMessage Error message.
  4829. *
  4830. * @returns True if `callback` returns true.
  4831. * @throws An error if `callback` fails.
  4832. */
  4833. const matcherWrapper = (callback, argsData, errorMessage) => {
  4834. let isMatched;
  4835. try {
  4836. isMatched = callback(argsData);
  4837. } catch (e) {
  4838. logger.error(getErrorMessage(e));
  4839. throw new Error(errorMessage);
  4840. }
  4841. return isMatched;
  4842. };
  4843. /**
  4844. * Generates common error message to throw while matching element `propDesc`.
  4845. *
  4846. * @param propDesc Text to describe what element 'prop' pseudo-class is trying to match.
  4847. * @param pseudoName Pseudo-class name.
  4848. * @param pseudoArg Pseudo-class arg.
  4849. *
  4850. * @returns Generated error message string.
  4851. */
  4852. const getAbsolutePseudoError = (propDesc, pseudoName, pseudoArg) => {
  4853. // eslint-disable-next-line max-len
  4854. return `${MATCHING_ELEMENT_ERROR_PREFIX} ${propDesc}, may be invalid :${pseudoName}() pseudo-class arg: '${pseudoArg}'`;
  4855. };
  4856. /**
  4857. * Checks whether the domElement is matched by absolute extended pseudo-class argument.
  4858. *
  4859. * @param domElement Page element.
  4860. * @param pseudoName Pseudo-class name.
  4861. * @param pseudoArg Pseudo-class arg.
  4862. *
  4863. * @returns True if `domElement` is matched by absolute pseudo-class.
  4864. * @throws An error on unknown absolute pseudo-class.
  4865. */
  4866. const isMatchedByAbsolutePseudo = (domElement, pseudoName, pseudoArg) => {
  4867. let argsData;
  4868. let errorMessage;
  4869. let callback;
  4870. switch (pseudoName) {
  4871. case CONTAINS_PSEUDO:
  4872. case HAS_TEXT_PSEUDO:
  4873. case ABP_CONTAINS_PSEUDO:
  4874. callback = isTextMatched;
  4875. argsData = {
  4876. pseudoName,
  4877. pseudoArg,
  4878. domElement,
  4879. };
  4880. errorMessage = getAbsolutePseudoError(
  4881. "text content",
  4882. pseudoName,
  4883. pseudoArg
  4884. );
  4885. break;
  4886. case MATCHES_CSS_PSEUDO:
  4887. case MATCHES_CSS_AFTER_PSEUDO:
  4888. case MATCHES_CSS_BEFORE_PSEUDO:
  4889. callback = isStyleMatched;
  4890. argsData = {
  4891. pseudoName,
  4892. pseudoArg,
  4893. domElement,
  4894. };
  4895. errorMessage = getAbsolutePseudoError("style", pseudoName, pseudoArg);
  4896. break;
  4897. case MATCHES_ATTR_PSEUDO_CLASS_MARKER:
  4898. callback = isAttributeMatched;
  4899. argsData = {
  4900. domElement,
  4901. pseudoName,
  4902. pseudoArg,
  4903. };
  4904. errorMessage = getAbsolutePseudoError(
  4905. "attributes",
  4906. pseudoName,
  4907. pseudoArg
  4908. );
  4909. break;
  4910. case MATCHES_PROPERTY_PSEUDO_CLASS_MARKER:
  4911. callback = isPropertyMatched;
  4912. argsData = {
  4913. domElement,
  4914. pseudoName,
  4915. pseudoArg,
  4916. };
  4917. errorMessage = getAbsolutePseudoError(
  4918. "properties",
  4919. pseudoName,
  4920. pseudoArg
  4921. );
  4922. break;
  4923. default:
  4924. throw new Error(`Unknown absolute pseudo-class :${pseudoName}()`);
  4925. }
  4926. return matcherWrapper(callback, argsData, errorMessage);
  4927. };
  4928. const findByAbsolutePseudoPseudo = {
  4929. /**
  4930. * Returns list of nth ancestors relative to every dom node from domElements list.
  4931. *
  4932. * @param domElements DOM elements.
  4933. * @param rawPseudoArg Number arg of :nth-ancestor() or :upward() pseudo-class.
  4934. * @param pseudoName Pseudo-class name.
  4935. *
  4936. * @returns Array of ancestor DOM elements.
  4937. */
  4938. nthAncestor: (domElements, rawPseudoArg, pseudoName) => {
  4939. const deep = getValidNumberAncestorArg(rawPseudoArg, pseudoName);
  4940. const ancestors = domElements
  4941. .map((domElement) => {
  4942. let ancestor = null;
  4943. try {
  4944. ancestor = getNthAncestor(domElement, deep, pseudoName);
  4945. } catch (e) {
  4946. logger.error(getErrorMessage(e));
  4947. }
  4948. return ancestor;
  4949. })
  4950. .filter(isHtmlElement);
  4951. return ancestors;
  4952. },
  4953. /**
  4954. * Returns list of elements by xpath expression, evaluated on every dom node from domElements list.
  4955. *
  4956. * @param domElements DOM elements.
  4957. * @param rawPseudoArg Arg of :xpath() pseudo-class.
  4958. *
  4959. * @returns Array of DOM elements matched by xpath expression.
  4960. */
  4961. xpath: (domElements, rawPseudoArg) => {
  4962. const foundElements = domElements.map((domElement) => {
  4963. const result = [];
  4964. let xpathResult;
  4965. try {
  4966. xpathResult = document.evaluate(
  4967. rawPseudoArg,
  4968. domElement,
  4969. null,
  4970. window.XPathResult.UNORDERED_NODE_ITERATOR_TYPE,
  4971. null
  4972. );
  4973. } catch (e) {
  4974. logger.error(getErrorMessage(e));
  4975. throw new Error(
  4976. `Invalid argument of :xpath() pseudo-class: '${rawPseudoArg}'`
  4977. );
  4978. }
  4979. let node = xpathResult.iterateNext();
  4980. while (node) {
  4981. if (isHtmlElement(node)) {
  4982. result.push(node);
  4983. }
  4984. node = xpathResult.iterateNext();
  4985. }
  4986. return result;
  4987. });
  4988. return flatten(foundElements);
  4989. },
  4990. /**
  4991. * Returns list of closest ancestors relative to every dom node from domElements list.
  4992. *
  4993. * @param domElements DOM elements.
  4994. * @param rawPseudoArg Standard selector arg of :upward() pseudo-class.
  4995. *
  4996. * @returns Array of closest ancestor DOM elements.
  4997. * @throws An error if `rawPseudoArg` is not a valid standard selector.
  4998. */
  4999. upward: (domElements, rawPseudoArg) => {
  5000. if (!validateStandardSelector(rawPseudoArg)) {
  5001. throw new Error(
  5002. `Invalid argument of :upward pseudo-class: '${rawPseudoArg}'`
  5003. );
  5004. }
  5005. const closestAncestors = domElements
  5006. .map((domElement) => {
  5007. // closest to parent element should be found
  5008. // otherwise `.base:upward(.base)` will return itself too, not only ancestor
  5009. const parent = domElement.parentElement;
  5010. if (!parent) {
  5011. return null;
  5012. }
  5013. return parent.closest(rawPseudoArg);
  5014. })
  5015. .filter(isHtmlElement);
  5016. return closestAncestors;
  5017. },
  5018. };
  5019. /**
  5020. * Calculated selector text which is needed to :has(), :is() and :not() pseudo-classes.
  5021. * Contains calculated part (depends on the processed element)
  5022. * and value of RegularSelector which is next to selector by.
  5023. *
  5024. * Native Document.querySelectorAll() does not select exact descendant elements
  5025. * but match all page elements satisfying the selector,
  5026. * so extra specification is needed for proper descendants selection
  5027. * e.g. 'div:has(> img)'.
  5028. *
  5029. * Its calculation depends on extended selector.
  5030. */
  5031. /**
  5032. * Combined `:scope` pseudo-class and **child** combinator — `:scope>`.
  5033. */
  5034. const scopeDirectChildren = `${SCOPE_CSS_PSEUDO_CLASS}${CHILD_COMBINATOR}`;
  5035. /**
  5036. * Combined `:scope` pseudo-class and **descendant** combinator — `:scope `.
  5037. */
  5038. const scopeAnyChildren = `${SCOPE_CSS_PSEUDO_CLASS}${DESCENDANT_COMBINATOR}`;
  5039. /**
  5040. * Type for relative pseudo-class helpers args.
  5041. */
  5042. /**
  5043. * Returns the first of RegularSelector child node for `selectorNode`.
  5044. *
  5045. * @param selectorNode Ast Selector node.
  5046. * @param pseudoName Name of relative pseudo-class.
  5047. *
  5048. * @returns Ast RegularSelector node.
  5049. */
  5050. const getFirstInnerRegularChild = (selectorNode, pseudoName) => {
  5051. return getFirstRegularChild(
  5052. selectorNode.children,
  5053. `RegularSelector is missing for :${pseudoName}() pseudo-class`
  5054. );
  5055. }; // TODO: fix for <forgiving-relative-selector-list>
  5056. // https://github.com/AdguardTeam/ExtendedCss/issues/154
  5057. /**
  5058. * Checks whether the element has all relative elements specified by pseudo-class arg.
  5059. * Used for :has() pseudo-class.
  5060. *
  5061. * @param argsData Relative pseudo-class helpers args data.
  5062. *
  5063. * @returns True if **all selectors** from argsData.relativeSelectorList is **matched** for argsData.element.
  5064. */
  5065. const hasRelativesBySelectorList = (argsData) => {
  5066. const { element, relativeSelectorList, pseudoName } = argsData;
  5067. return relativeSelectorList.children // Array.every() is used here as each Selector node from SelectorList should exist on page
  5068. .every((selectorNode) => {
  5069. // selectorList.children always starts with regular selector as any selector generally
  5070. const relativeRegularSelector = getFirstInnerRegularChild(
  5071. selectorNode,
  5072. pseudoName
  5073. );
  5074. let specifiedSelector = "";
  5075. let rootElement = null;
  5076. const regularSelector = getNodeValue(relativeRegularSelector);
  5077. if (
  5078. regularSelector.startsWith(NEXT_SIBLING_COMBINATOR) ||
  5079. regularSelector.startsWith(SUBSEQUENT_SIBLING_COMBINATOR)
  5080. ) {
  5081. /**
  5082. * For matching the element by "element:has(+ next-sibling)" and "element:has(~ sibling)"
  5083. * we check whether the element's parentElement has specific direct child combination,
  5084. * e.g. 'h1:has(+ .share)' -> `h1Node.parentElement.querySelectorAll(':scope > h1 + .share')`.
  5085. *
  5086. * @see {@link https://www.w3.org/TR/selectors-4/#relational}
  5087. */
  5088. rootElement = element.parentElement;
  5089. const elementSelectorText = getElementSelectorDesc(element);
  5090. specifiedSelector = `${scopeDirectChildren}${elementSelectorText}${regularSelector}`;
  5091. } else if (regularSelector === ASTERISK) {
  5092. /**
  5093. * :scope specification is needed for proper descendants selection
  5094. * as native element.querySelectorAll() does not select exact element descendants
  5095. * e.g. 'a:has(> img)' -> `aNode.querySelectorAll(':scope > img')`.
  5096. *
  5097. * For 'any selector' as arg of relative simplicity should be set for all inner elements
  5098. * e.g. 'div:has(*)' -> `divNode.querySelectorAll(':scope *')`
  5099. * which means empty div with no child element.
  5100. */
  5101. rootElement = element;
  5102. specifiedSelector = `${scopeAnyChildren}${ASTERISK}`;
  5103. } else {
  5104. /**
  5105. * As it described above, inner elements should be found using `:scope` pseudo-class
  5106. * e.g. 'a:has(> img)' -> `aNode.querySelectorAll(':scope > img')`
  5107. * OR '.block(div > span)' -> `blockClassNode.querySelectorAll(':scope div > span')`.
  5108. */
  5109. specifiedSelector = `${scopeAnyChildren}${regularSelector}`;
  5110. rootElement = element;
  5111. }
  5112. if (!rootElement) {
  5113. throw new Error(
  5114. `Selection by :${pseudoName}() pseudo-class is not possible`
  5115. );
  5116. }
  5117. let relativeElements;
  5118. try {
  5119. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  5120. relativeElements = getElementsForSelectorNode(
  5121. selectorNode,
  5122. rootElement,
  5123. specifiedSelector
  5124. );
  5125. } catch (e) {
  5126. logger.error(getErrorMessage(e)); // fail for invalid selector
  5127. throw new Error(
  5128. `Invalid selector for :${pseudoName}() pseudo-class: '${regularSelector}'`
  5129. );
  5130. }
  5131. return relativeElements.length > 0;
  5132. });
  5133. };
  5134. /**
  5135. * Checks whether the element is an any element specified by pseudo-class arg.
  5136. * Used for :is() pseudo-class.
  5137. *
  5138. * @param argsData Relative pseudo-class helpers args data.
  5139. *
  5140. * @returns True if **any selector** from argsData.relativeSelectorList is **matched** for argsData.element.
  5141. */
  5142. const isAnyElementBySelectorList = (argsData) => {
  5143. const { element, relativeSelectorList, pseudoName } = argsData;
  5144. return relativeSelectorList.children // Array.some() is used here as any selector from selector list should exist on page
  5145. .some((selectorNode) => {
  5146. // selectorList.children always starts with regular selector
  5147. const relativeRegularSelector = getFirstInnerRegularChild(
  5148. selectorNode,
  5149. pseudoName
  5150. );
  5151. /**
  5152. * For checking the element by 'div:is(.banner)'
  5153. * we check whether the element's parentElement has any specific direct child.
  5154. */
  5155. const rootElement = getParent(
  5156. element,
  5157. `Selection by :${pseudoName}() pseudo-class is not possible`
  5158. );
  5159. /**
  5160. * So we calculate the element "description" by it's tagname and attributes for targeting
  5161. * and use it to specify the selection
  5162. * e.g. `div:is(.banner)` --> `divNode.parentElement.querySelectorAll(':scope > .banner')`.
  5163. */
  5164. const specifiedSelector = `${scopeDirectChildren}${getNodeValue(
  5165. relativeRegularSelector
  5166. )}`;
  5167. let anyElements;
  5168. try {
  5169. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  5170. anyElements = getElementsForSelectorNode(
  5171. selectorNode,
  5172. rootElement,
  5173. specifiedSelector
  5174. );
  5175. } catch (e) {
  5176. // do not fail on invalid selectors for :is()
  5177. return false;
  5178. } // TODO: figure out how to handle complex selectors with extended pseudo-classes
  5179. // (check readme - extended-css-is-limitations)
  5180. // because `element` and `anyElements` may be from different DOM levels
  5181. return anyElements.includes(element);
  5182. });
  5183. };
  5184. /**
  5185. * Checks whether the element is not an element specified by pseudo-class arg.
  5186. * Used for :not() pseudo-class.
  5187. *
  5188. * @param argsData Relative pseudo-class helpers args data.
  5189. *
  5190. * @returns True if **any selector** from argsData.relativeSelectorList is **not matched** for argsData.element.
  5191. */
  5192. const notElementBySelectorList = (argsData) => {
  5193. const { element, relativeSelectorList, pseudoName } = argsData;
  5194. return relativeSelectorList.children // Array.every() is used here as element should not be selected by any selector from selector list
  5195. .every((selectorNode) => {
  5196. // selectorList.children always starts with regular selector
  5197. const relativeRegularSelector = getFirstInnerRegularChild(
  5198. selectorNode,
  5199. pseudoName
  5200. );
  5201. /**
  5202. * For checking the element by 'div:not([data="content"])
  5203. * we check whether the element's parentElement has any specific direct child.
  5204. */
  5205. const rootElement = getParent(
  5206. element,
  5207. `Selection by :${pseudoName}() pseudo-class is not possible`
  5208. );
  5209. /**
  5210. * So we calculate the element "description" by it's tagname and attributes for targeting
  5211. * and use it to specify the selection
  5212. * e.g. `div:not(.banner)` --> `divNode.parentElement.querySelectorAll(':scope > .banner')`.
  5213. */
  5214. const specifiedSelector = `${scopeDirectChildren}${getNodeValue(
  5215. relativeRegularSelector
  5216. )}`;
  5217. let anyElements;
  5218. try {
  5219. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  5220. anyElements = getElementsForSelectorNode(
  5221. selectorNode,
  5222. rootElement,
  5223. specifiedSelector
  5224. );
  5225. } catch (e) {
  5226. // fail on invalid selectors for :not()
  5227. logger.error(getErrorMessage(e)); // eslint-disable-next-line max-len
  5228. throw new Error(
  5229. `Invalid selector for :${pseudoName}() pseudo-class: '${getNodeValue(
  5230. relativeRegularSelector
  5231. )}'`
  5232. );
  5233. } // TODO: figure out how to handle up-looking pseudo-classes inside :not()
  5234. // (check readme - extended-css-not-limitations)
  5235. // because `element` and `anyElements` may be from different DOM levels
  5236. return !anyElements.includes(element);
  5237. });
  5238. };
  5239. /**
  5240. * Selects dom elements by value of RegularSelector.
  5241. *
  5242. * @param regularSelectorNode RegularSelector node.
  5243. * @param root Root DOM element.
  5244. * @param specifiedSelector @see {@link SpecifiedSelector}.
  5245. *
  5246. * @returns Array of DOM elements.
  5247. * @throws An error if RegularSelector node value is an invalid selector.
  5248. */
  5249. const getByRegularSelector = (
  5250. regularSelectorNode,
  5251. root,
  5252. specifiedSelector
  5253. ) => {
  5254. const selectorText = specifiedSelector
  5255. ? specifiedSelector
  5256. : getNodeValue(regularSelectorNode);
  5257. let selectedElements = [];
  5258. try {
  5259. selectedElements = Array.from(root.querySelectorAll(selectorText));
  5260. } catch (e) {
  5261. throw new Error(
  5262. `Error: unable to select by '${selectorText}' ${getErrorMessage(e)}`
  5263. );
  5264. }
  5265. return selectedElements;
  5266. };
  5267. /**
  5268. * Returns list of dom elements filtered or selected by ExtendedSelector node.
  5269. *
  5270. * @param domElements Array of DOM elements.
  5271. * @param extendedSelectorNode ExtendedSelector node.
  5272. *
  5273. * @returns Array of DOM elements.
  5274. * @throws An error on unknown pseudo-class,
  5275. * absent or invalid arg of extended pseudo-class, etc.
  5276. */
  5277. const getByExtendedSelector = (domElements, extendedSelectorNode) => {
  5278. let foundElements = [];
  5279. const extendedPseudoClassNode = getPseudoClassNode(extendedSelectorNode);
  5280. const pseudoName = getNodeName(extendedPseudoClassNode);
  5281. if (isAbsolutePseudoClass(pseudoName)) {
  5282. // absolute extended pseudo-classes should have an argument
  5283. const absolutePseudoArg = getNodeValue(
  5284. extendedPseudoClassNode,
  5285. `Missing arg for :${pseudoName}() pseudo-class`
  5286. );
  5287. if (pseudoName === NTH_ANCESTOR_PSEUDO_CLASS_MARKER) {
  5288. // :nth-ancestor()
  5289. foundElements = findByAbsolutePseudoPseudo.nthAncestor(
  5290. domElements,
  5291. absolutePseudoArg,
  5292. pseudoName
  5293. );
  5294. } else if (pseudoName === XPATH_PSEUDO_CLASS_MARKER) {
  5295. // :xpath()
  5296. try {
  5297. document.createExpression(absolutePseudoArg, null);
  5298. } catch (e) {
  5299. throw new Error(
  5300. `Invalid argument of :${pseudoName}() pseudo-class: '${absolutePseudoArg}'`
  5301. );
  5302. }
  5303. foundElements = findByAbsolutePseudoPseudo.xpath(
  5304. domElements,
  5305. absolutePseudoArg
  5306. );
  5307. } else if (pseudoName === UPWARD_PSEUDO_CLASS_MARKER) {
  5308. // :upward()
  5309. if (Number.isNaN(Number(absolutePseudoArg))) {
  5310. // so arg is selector, not a number
  5311. foundElements = findByAbsolutePseudoPseudo.upward(
  5312. domElements,
  5313. absolutePseudoArg
  5314. );
  5315. } else {
  5316. foundElements = findByAbsolutePseudoPseudo.nthAncestor(
  5317. domElements,
  5318. absolutePseudoArg,
  5319. pseudoName
  5320. );
  5321. }
  5322. } else {
  5323. // all other absolute extended pseudo-classes
  5324. // e.g. contains, matches-attr, etc.
  5325. foundElements = domElements.filter((element) => {
  5326. return isMatchedByAbsolutePseudo(
  5327. element,
  5328. pseudoName,
  5329. absolutePseudoArg
  5330. );
  5331. });
  5332. }
  5333. } else if (isRelativePseudoClass(pseudoName)) {
  5334. const relativeSelectorList = getRelativeSelectorListNode(
  5335. extendedPseudoClassNode
  5336. );
  5337. let relativePredicate;
  5338. switch (pseudoName) {
  5339. case HAS_PSEUDO_CLASS_MARKER:
  5340. case ABP_HAS_PSEUDO_CLASS_MARKER:
  5341. relativePredicate = (element) =>
  5342. hasRelativesBySelectorList({
  5343. element,
  5344. relativeSelectorList,
  5345. pseudoName,
  5346. });
  5347. break;
  5348. case IS_PSEUDO_CLASS_MARKER:
  5349. relativePredicate = (element) =>
  5350. isAnyElementBySelectorList({
  5351. element,
  5352. relativeSelectorList,
  5353. pseudoName,
  5354. });
  5355. break;
  5356. case NOT_PSEUDO_CLASS_MARKER:
  5357. relativePredicate = (element) =>
  5358. notElementBySelectorList({
  5359. element,
  5360. relativeSelectorList,
  5361. pseudoName,
  5362. });
  5363. break;
  5364. default:
  5365. throw new Error(`Unknown relative pseudo-class: '${pseudoName}'`);
  5366. }
  5367. foundElements = domElements.filter(relativePredicate);
  5368. } else {
  5369. // extra check is parser missed something
  5370. throw new Error(`Unknown extended pseudo-class: '${pseudoName}'`);
  5371. }
  5372. return foundElements;
  5373. };
  5374. /**
  5375. * Returns list of dom elements which is selected by RegularSelector value.
  5376. *
  5377. * @param domElements Array of DOM elements.
  5378. * @param regularSelectorNode RegularSelector node.
  5379. *
  5380. * @returns Array of DOM elements.
  5381. * @throws An error if RegularSelector has not value.
  5382. */
  5383. const getByFollowingRegularSelector = (
  5384. domElements,
  5385. regularSelectorNode
  5386. ) => {
  5387. // array of arrays because of Array.map() later
  5388. let foundElements = [];
  5389. const value = getNodeValue(regularSelectorNode);
  5390. if (value.startsWith(CHILD_COMBINATOR)) {
  5391. // e.g. div:has(> img) > .banner
  5392. foundElements = domElements.map((root) => {
  5393. const specifiedSelector = `${SCOPE_CSS_PSEUDO_CLASS}${value}`;
  5394. return getByRegularSelector(
  5395. regularSelectorNode,
  5396. root,
  5397. specifiedSelector
  5398. );
  5399. });
  5400. } else if (
  5401. value.startsWith(NEXT_SIBLING_COMBINATOR) ||
  5402. value.startsWith(SUBSEQUENT_SIBLING_COMBINATOR)
  5403. ) {
  5404. // e.g. div:has(> img) + .banner
  5405. // or div:has(> img) ~ .banner
  5406. foundElements = domElements.map((element) => {
  5407. const rootElement = element.parentElement;
  5408. if (!rootElement) {
  5409. // do not throw error if there in no parent for element
  5410. // e.g. '*:contains(text)' selects `html` which has no parentElement
  5411. return [];
  5412. }
  5413. const elementSelectorText = getElementSelectorDesc(element);
  5414. const specifiedSelector = `${scopeDirectChildren}${elementSelectorText}${value}`;
  5415. const selected = getByRegularSelector(
  5416. regularSelectorNode,
  5417. rootElement,
  5418. specifiedSelector
  5419. );
  5420. return selected;
  5421. });
  5422. } else {
  5423. // space-separated regular selector after extended one
  5424. // e.g. div:has(> img) .banner
  5425. foundElements = domElements.map((root) => {
  5426. const specifiedSelector = `${scopeAnyChildren}${getNodeValue(
  5427. regularSelectorNode
  5428. )}`;
  5429. return getByRegularSelector(
  5430. regularSelectorNode,
  5431. root,
  5432. specifiedSelector
  5433. );
  5434. });
  5435. } // foundElements should be flattened
  5436. // as getByRegularSelector() returns elements array, and Array.map() collects them to array
  5437. return flatten(foundElements);
  5438. };
  5439. /**
  5440. * Returns elements nodes for Selector node.
  5441. * As far as any selector always starts with regular part,
  5442. * it selects by RegularSelector first and checks found elements later.
  5443. *
  5444. * Relative pseudo-classes has it's own subtree so getElementsForSelectorNode is called recursively.
  5445. *
  5446. * 'specifiedSelector' is needed for :has(), :is(), and :not() pseudo-classes
  5447. * as native querySelectorAll() does not select exact element descendants even if it is called on 'div'
  5448. * e.g. ':scope' specification is needed for proper descendants selection for 'div:has(> img)'.
  5449. * So we check `divNode.querySelectorAll(':scope > img').length > 0`.
  5450. *
  5451. * @param selectorNode Selector node.
  5452. * @param root Root DOM element.
  5453. * @param specifiedSelector Needed element specification.
  5454. *
  5455. * @returns Array of DOM elements.
  5456. * @throws An error if there is no selectorNodeChild.
  5457. */
  5458. const getElementsForSelectorNode = (
  5459. selectorNode,
  5460. root,
  5461. specifiedSelector
  5462. ) => {
  5463. let selectedElements = [];
  5464. let i = 0;
  5465. while (i < selectorNode.children.length) {
  5466. const selectorNodeChild = getItemByIndex(
  5467. selectorNode.children,
  5468. i,
  5469. "selectorNodeChild should be specified"
  5470. );
  5471. if (i === 0) {
  5472. // any selector always starts with regular selector
  5473. selectedElements = getByRegularSelector(
  5474. selectorNodeChild,
  5475. root,
  5476. specifiedSelector
  5477. );
  5478. } else if (isExtendedSelectorNode(selectorNodeChild)) {
  5479. // filter previously selected elements by next selector nodes
  5480. selectedElements = getByExtendedSelector(
  5481. selectedElements,
  5482. selectorNodeChild
  5483. );
  5484. } else if (isRegularSelectorNode(selectorNodeChild)) {
  5485. selectedElements = getByFollowingRegularSelector(
  5486. selectedElements,
  5487. selectorNodeChild
  5488. );
  5489. }
  5490. i += 1;
  5491. }
  5492. return selectedElements;
  5493. };
  5494. /**
  5495. * Selects elements by ast.
  5496. *
  5497. * @param ast Ast of parsed selector.
  5498. * @param doc Document.
  5499. *
  5500. * @returns Array of DOM elements.
  5501. */
  5502. const selectElementsByAst = function (ast) {
  5503. let doc =
  5504. arguments.length > 1 && arguments[1] !== undefined
  5505. ? arguments[1]
  5506. : document;
  5507. const selectedElements = []; // ast root is SelectorList node;
  5508. // it has Selector nodes as children which should be processed separately
  5509. ast.children.forEach((selectorNode) => {
  5510. selectedElements.push(...getElementsForSelectorNode(selectorNode, doc));
  5511. }); // selectedElements should be flattened as it is array of arrays with elements
  5512. const uniqueElements = [...new Set(flatten(selectedElements))];
  5513. return uniqueElements;
  5514. };
  5515. /**
  5516. * Class of ExtCssDocument is needed for caching.
  5517. * For making cache related to each new instance of class, not global.
  5518. */
  5519. class ExtCssDocument {
  5520. /**
  5521. * Cache with selectors and their AST parsing results.
  5522. */
  5523. /**
  5524. * Creates new ExtCssDocument and inits new `astCache`.
  5525. */
  5526. constructor() {
  5527. this.astCache = new Map();
  5528. }
  5529. /**
  5530. * Saves selector and it's ast to cache.
  5531. *
  5532. * @param selector Standard or extended selector.
  5533. * @param ast Selector ast.
  5534. */
  5535. saveAstToCache(selector, ast) {
  5536. this.astCache.set(selector, ast);
  5537. }
  5538. /**
  5539. * Returns ast from cache for given selector.
  5540. *
  5541. * @param selector Standard or extended selector.
  5542. *
  5543. * @returns Previously parsed ast found in cache, or null if not found.
  5544. */
  5545. getAstFromCache(selector) {
  5546. const cachedAst = this.astCache.get(selector) || null;
  5547. return cachedAst;
  5548. }
  5549. /**
  5550. * Returns selector ast:
  5551. * - if cached ast exists — returns it;
  5552. * - if no cached ast — saves newly parsed ast to cache and returns it.
  5553. *
  5554. * @param selector Standard or extended selector.
  5555. *
  5556. * @returns Ast for `selector`.
  5557. */
  5558. getSelectorAst(selector) {
  5559. let ast = this.getAstFromCache(selector);
  5560. if (!ast) {
  5561. ast = parse(selector);
  5562. }
  5563. this.saveAstToCache(selector, ast);
  5564. return ast;
  5565. }
  5566. /**
  5567. * Selects elements by selector.
  5568. *
  5569. * @param selector Standard or extended selector.
  5570. *
  5571. * @returns Array of DOM elements.
  5572. */
  5573. querySelectorAll(selector) {
  5574. const ast = this.getSelectorAst(selector);
  5575. return selectElementsByAst(ast);
  5576. }
  5577. }
  5578. const extCssDocument = new ExtCssDocument();
  5579. /**
  5580. * Converts array of `entries` to object.
  5581. * Object.fromEntries() polyfill because it is not supported by old browsers, e.g. Chrome 55.
  5582. * Only first two elements of `entries` array matter, other will be skipped silently.
  5583. *
  5584. * @see {@link https://caniuse.com/?search=Object.fromEntries}
  5585. *
  5586. * @param entries Array of pairs.
  5587. *
  5588. * @returns Object converted from `entries`.
  5589. */
  5590. const getObjectFromEntries = (entries) => {
  5591. const object = {};
  5592. entries.forEach((el) => {
  5593. const [key, value] = el;
  5594. object[key] = value;
  5595. });
  5596. return object;
  5597. };
  5598. const DEBUG_PSEUDO_PROPERTY_KEY = "debug";
  5599. /**
  5600. * Checks the presence of :remove() pseudo-class and validates it while parsing the selector part of css rule.
  5601. *
  5602. * @param rawSelector Selector which may contain :remove() pseudo-class.
  5603. *
  5604. * @returns Parsed selector data with selector and styles.
  5605. * @throws An error on invalid :remove() position.
  5606. */
  5607. const parseRemoveSelector = (rawSelector) => {
  5608. /**
  5609. * No error will be thrown on invalid selector as it will be validated later
  5610. * so it's better to explicitly specify 'any' selector for :remove() pseudo-class by '*',
  5611. * e.g. '.banner > *:remove()' instead of '.banner > :remove()'.
  5612. */
  5613. // ':remove()'
  5614. // eslint-disable-next-line max-len
  5615. const VALID_REMOVE_MARKER = `${COLON}${REMOVE_PSEUDO_MARKER}${BRACKET.PARENTHESES.LEFT}${BRACKET.PARENTHESES.RIGHT}`; // ':remove(' - needed for validation rules like 'div:remove(2)'
  5616. const INVALID_REMOVE_MARKER = `${COLON}${REMOVE_PSEUDO_MARKER}${BRACKET.PARENTHESES.LEFT}`;
  5617. let selector;
  5618. let shouldRemove = false;
  5619. const firstIndex = rawSelector.indexOf(VALID_REMOVE_MARKER);
  5620. if (firstIndex === 0) {
  5621. // e.g. ':remove()'
  5622. throw new Error(
  5623. `${REMOVE_ERROR_PREFIX.NO_TARGET_SELECTOR}: '${rawSelector}'`
  5624. );
  5625. } else if (firstIndex > 0) {
  5626. if (firstIndex !== rawSelector.lastIndexOf(VALID_REMOVE_MARKER)) {
  5627. // rule with more than one :remove() pseudo-class is invalid
  5628. // e.g. '.block:remove() > .banner:remove()'
  5629. throw new Error(
  5630. `${REMOVE_ERROR_PREFIX.MULTIPLE_USAGE}: '${rawSelector}'`
  5631. );
  5632. } else if (
  5633. firstIndex + VALID_REMOVE_MARKER.length <
  5634. rawSelector.length
  5635. ) {
  5636. // remove pseudo-class should be last in the rule
  5637. // e.g. '.block:remove():upward(2)'
  5638. throw new Error(
  5639. `${REMOVE_ERROR_PREFIX.INVALID_POSITION}: '${rawSelector}'`
  5640. );
  5641. } else {
  5642. // valid :remove() pseudo-class position
  5643. selector = rawSelector.substring(0, firstIndex);
  5644. shouldRemove = true;
  5645. }
  5646. } else if (rawSelector.includes(INVALID_REMOVE_MARKER)) {
  5647. // it is not valid if ':remove()' is absent in rule but just ':remove(' is present
  5648. // e.g. 'div:remove(0)'
  5649. throw new Error(
  5650. `${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${rawSelector}'`
  5651. );
  5652. } else {
  5653. // there is no :remove() pseudo-class in rule
  5654. selector = rawSelector;
  5655. }
  5656. const stylesOfSelector = shouldRemove
  5657. ? [
  5658. {
  5659. property: REMOVE_PSEUDO_MARKER,
  5660. value: PSEUDO_PROPERTY_POSITIVE_VALUE,
  5661. },
  5662. ]
  5663. : [];
  5664. return {
  5665. selector,
  5666. stylesOfSelector,
  5667. };
  5668. };
  5669. /**
  5670. * Parses cropped selector part found before `{`.
  5671. *
  5672. * @param selectorBuffer Buffered selector to parse.
  5673. * @param extCssDoc Needed for caching of selector ast.
  5674. *
  5675. * @returns Parsed validation data for cropped part of stylesheet which may be a selector.
  5676. * @throws An error on unsupported CSS features, e.g. at-rules.
  5677. */
  5678. const parseSelectorRulePart = (selectorBuffer, extCssDoc) => {
  5679. let selector = selectorBuffer.trim();
  5680. if (selector.startsWith(AT_RULE_MARKER)) {
  5681. throw new Error(`${NO_AT_RULE_ERROR_PREFIX}: '${selector}'.`);
  5682. }
  5683. let removeSelectorData;
  5684. try {
  5685. removeSelectorData = parseRemoveSelector(selector);
  5686. } catch (e) {
  5687. logger.error(getErrorMessage(e));
  5688. throw new Error(`${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`);
  5689. }
  5690. let stylesOfSelector = [];
  5691. let success = false;
  5692. let ast;
  5693. try {
  5694. selector = removeSelectorData.selector;
  5695. stylesOfSelector = removeSelectorData.stylesOfSelector; // validate found selector by parsing it to ast
  5696. // so if it is invalid error will be thrown
  5697. ast = extCssDoc.getSelectorAst(selector);
  5698. success = true;
  5699. } catch (e) {
  5700. success = false;
  5701. }
  5702. return {
  5703. success,
  5704. selector,
  5705. ast,
  5706. stylesOfSelector,
  5707. };
  5708. };
  5709. /**
  5710. * Creates a map for storing raw results of css rules parsing.
  5711. * Used for merging styles for same selector.
  5712. *
  5713. * @returns Map where **key** is `selector`
  5714. * and **value** is object with `ast` and `styles`.
  5715. */
  5716. const createRawResultsMap = () => {
  5717. return new Map();
  5718. };
  5719. /**
  5720. * Saves rules data for unique selectors.
  5721. *
  5722. * @param rawResults Previously collected results of parsing.
  5723. * @param rawRuleData Parsed rule data.
  5724. *
  5725. * @throws An error if there is no rawRuleData.styles or rawRuleData.ast.
  5726. */
  5727. const saveToRawResults = (rawResults, rawRuleData) => {
  5728. const { selector, ast, rawStyles } = rawRuleData;
  5729. if (!rawStyles) {
  5730. throw new Error(`No style declaration for selector: '${selector}'`);
  5731. }
  5732. if (!ast) {
  5733. throw new Error(`No ast parsed for selector: '${selector}'`);
  5734. }
  5735. const storedRuleData = rawResults.get(selector);
  5736. if (!storedRuleData) {
  5737. rawResults.set(selector, {
  5738. ast,
  5739. styles: rawStyles,
  5740. });
  5741. } else {
  5742. storedRuleData.styles.push(...rawStyles);
  5743. }
  5744. };
  5745. /**
  5746. * Checks whether the 'remove' property positively set in styles
  5747. * with only one positive value - 'true'.
  5748. *
  5749. * @param styles Array of styles.
  5750. *
  5751. * @returns True if there is 'remove' property with 'true' value in `styles`.
  5752. */
  5753. const isRemoveSetInStyles = (styles) => {
  5754. return styles.some((s) => {
  5755. return (
  5756. s.property === REMOVE_PSEUDO_MARKER &&
  5757. s.value === PSEUDO_PROPERTY_POSITIVE_VALUE
  5758. );
  5759. });
  5760. };
  5761. /**
  5762. * Returns 'debug' property value which is set in styles.
  5763. *
  5764. * @param styles Array of styles.
  5765. *
  5766. * @returns Value of 'debug' property if it is set in `styles`,
  5767. * or `undefined` if the property is not found.
  5768. */
  5769. const getDebugStyleValue = (styles) => {
  5770. const debugStyle = styles.find((s) => {
  5771. return s.property === DEBUG_PSEUDO_PROPERTY_KEY;
  5772. });
  5773. return debugStyle === null || debugStyle === void 0
  5774. ? void 0
  5775. : debugStyle.value;
  5776. };
  5777. /**
  5778. * Prepares final RuleData.
  5779. * Handles `debug` and `remove` in raw rule data styles.
  5780. *
  5781. * @param rawRuleData Raw data of selector css rule parsing.
  5782. *
  5783. * @returns Parsed ExtendedCss rule data.
  5784. * @throws An error if rawRuleData.ast or rawRuleData.rawStyles not defined.
  5785. */
  5786. const prepareRuleData = (rawRuleData) => {
  5787. const { selector, ast, rawStyles } = rawRuleData;
  5788. if (!ast) {
  5789. throw new Error(`AST should be parsed for selector: '${selector}'`);
  5790. }
  5791. if (!rawStyles) {
  5792. throw new Error(`Styles should be parsed for selector: '${selector}'`);
  5793. }
  5794. const ruleData = {
  5795. selector,
  5796. ast,
  5797. };
  5798. const debugValue = getDebugStyleValue(rawStyles);
  5799. const shouldRemove = isRemoveSetInStyles(rawStyles);
  5800. let styles = rawStyles;
  5801. if (debugValue) {
  5802. // get rid of 'debug' from styles
  5803. styles = rawStyles.filter(
  5804. (s) => s.property !== DEBUG_PSEUDO_PROPERTY_KEY
  5805. ); // and set it as separate property only if its value is valid
  5806. // which is 'true' or 'global'
  5807. if (
  5808. debugValue === PSEUDO_PROPERTY_POSITIVE_VALUE ||
  5809. debugValue === DEBUG_PSEUDO_PROPERTY_GLOBAL_VALUE
  5810. ) {
  5811. ruleData.debug = debugValue;
  5812. }
  5813. }
  5814. if (shouldRemove) {
  5815. // no other styles are needed to apply if 'remove' is set
  5816. ruleData.style = {
  5817. [REMOVE_PSEUDO_MARKER]: PSEUDO_PROPERTY_POSITIVE_VALUE,
  5818. };
  5819. /**
  5820. * 'content' property is needed for ExtCssConfiguration.beforeStyleApplied().
  5821. *
  5822. * @see {@link BeforeStyleAppliedCallback}
  5823. */
  5824. const contentStyle = styles.find(
  5825. (s) => s.property === CONTENT_CSS_PROPERTY
  5826. );
  5827. if (contentStyle) {
  5828. ruleData.style[CONTENT_CSS_PROPERTY] = contentStyle.value;
  5829. }
  5830. } else {
  5831. // otherwise all styles should be applied.
  5832. // every style property will be unique because of their converting into object
  5833. if (styles.length > 0) {
  5834. const stylesAsEntries = styles.map((style) => {
  5835. const { property, value } = style;
  5836. return [property, value];
  5837. });
  5838. const preparedStyleData = getObjectFromEntries(stylesAsEntries);
  5839. ruleData.style = preparedStyleData;
  5840. }
  5841. }
  5842. return ruleData;
  5843. };
  5844. /**
  5845. * Combines previously parsed css rules data objects
  5846. * into rules which are ready to apply.
  5847. *
  5848. * @param rawResults Previously parsed css rules data objects.
  5849. *
  5850. * @returns Parsed ExtendedCss rule data.
  5851. */
  5852. const combineRulesData = (rawResults) => {
  5853. const results = [];
  5854. rawResults.forEach((value, key) => {
  5855. const selector = key;
  5856. const { ast, styles: rawStyles } = value;
  5857. results.push(
  5858. prepareRuleData({
  5859. selector,
  5860. ast,
  5861. rawStyles,
  5862. })
  5863. );
  5864. });
  5865. return results;
  5866. };
  5867. /**
  5868. * Trims `rawStyle` and splits it into tokens.
  5869. *
  5870. * @param rawStyle Style declaration block content inside curly bracket — `{` and `}` —
  5871. * can be a single style declaration or a list of declarations.
  5872. *
  5873. * @returns Array of tokens supported for style declaration block.
  5874. */
  5875. const tokenizeStyleBlock = (rawStyle) => {
  5876. const styleDeclaration = rawStyle.trim();
  5877. return tokenize(styleDeclaration, SUPPORTED_STYLE_DECLARATION_MARKS);
  5878. };
  5879. /**
  5880. * Describes possible style declaration parts.
  5881. *
  5882. * IMPORTANT: it is used as 'const' instead of 'enum' to avoid side effects
  5883. * during ExtendedCss import into other libraries.
  5884. */
  5885. const DECLARATION_PART = {
  5886. PROPERTY: "property",
  5887. VALUE: "value",
  5888. };
  5889. /**
  5890. * Checks whether the quotes has been opened for style value.
  5891. *
  5892. * @param context Style block parser context.
  5893. *
  5894. * @returns True if style value has already opened quotes.
  5895. */
  5896. const isValueQuotesOpen = (context) => {
  5897. return context.bufferValue !== "" && context.valueQuoteMark !== null;
  5898. };
  5899. /**
  5900. * Saves parsed property and value to collection of parsed styles.
  5901. * Prunes context buffers for property and value.
  5902. *
  5903. * @param context Style block parser context.
  5904. */
  5905. const collectStyle = (context) => {
  5906. context.styles.push({
  5907. property: context.bufferProperty.trim(),
  5908. value: context.bufferValue.trim(),
  5909. }); // reset buffers
  5910. context.bufferProperty = "";
  5911. context.bufferValue = "";
  5912. };
  5913. /**
  5914. * Handles token which is supposed to be a part of style **property**.
  5915. *
  5916. * @param context Style block parser context.
  5917. * @param styleBlock Whole style block which is being parsed.
  5918. * @param token Current token.
  5919. *
  5920. * @throws An error on invalid token.
  5921. */
  5922. const processPropertyToken = (context, styleBlock, token) => {
  5923. const { value: tokenValue } = token;
  5924. switch (token.type) {
  5925. case TOKEN_TYPE.WORD:
  5926. if (context.bufferProperty.length > 0) {
  5927. // e.g. 'padding top: 0;' - current tokenValue is 'top' which is not valid
  5928. throw new Error(
  5929. `Invalid style property in style block: '${styleBlock}'`
  5930. );
  5931. }
  5932. context.bufferProperty += tokenValue;
  5933. break;
  5934. case TOKEN_TYPE.MARK:
  5935. // only colon and whitespaces are allowed while style property parsing
  5936. if (tokenValue === COLON) {
  5937. if (context.bufferProperty.trim().length === 0) {
  5938. // e.g. such style block: '{ : none; }'
  5939. throw new Error(
  5940. `Missing style property before ':' in style block: '${styleBlock}'`
  5941. );
  5942. } // the property successfully collected
  5943. context.bufferProperty = context.bufferProperty.trim(); // prepare for value collecting
  5944. context.processing = DECLARATION_PART.VALUE; // the property buffer shall be reset after the value is successfully collected
  5945. } else if (WHITE_SPACE_CHARACTERS.includes(tokenValue));
  5946. else {
  5947. // if after the property there is anything other than ':' except whitespace, this is a parse error
  5948. // https://www.w3.org/TR/css-syntax-3/#consume-declaration
  5949. throw new Error(
  5950. `Invalid style declaration in style block: '${styleBlock}'`
  5951. );
  5952. }
  5953. break;
  5954. default:
  5955. throw new Error(
  5956. `Unsupported style property character: '${tokenValue}' in style block: '${styleBlock}'`
  5957. );
  5958. }
  5959. };
  5960. /**
  5961. * Handles token which is supposed to be a part of style **value**.
  5962. *
  5963. * @param context Style block parser context.
  5964. * @param styleBlock Whole style block which is being parsed.
  5965. * @param token Current token.
  5966. *
  5967. * @throws An error on invalid token.
  5968. */
  5969. const processValueToken = (context, styleBlock, token) => {
  5970. const { value: tokenValue } = token;
  5971. if (token.type === TOKEN_TYPE.WORD) {
  5972. // simply collect to buffer
  5973. context.bufferValue += tokenValue;
  5974. } else {
  5975. // otherwise check the mark
  5976. switch (tokenValue) {
  5977. case COLON:
  5978. // the ':' character inside of the value should be inside of quotes
  5979. // otherwise the value is not valid
  5980. // e.g. 'content: display: none'
  5981. // parser is here ↑
  5982. if (!isValueQuotesOpen(context)) {
  5983. // eslint-disable-next-line max-len
  5984. throw new Error(
  5985. `Invalid style value for property '${context.bufferProperty}' in style block: '${styleBlock}'`
  5986. );
  5987. } // collect the colon inside quotes
  5988. // e.g. 'content: "test:123"'
  5989. // parser is here ↑
  5990. context.bufferValue += tokenValue;
  5991. break;
  5992. case SEMICOLON:
  5993. if (isValueQuotesOpen(context)) {
  5994. // ';' inside quotes is part of style value
  5995. // e.g. 'content: "test;"'
  5996. context.bufferValue += tokenValue;
  5997. } else {
  5998. // otherwise the value is successfully collected
  5999. // save parsed style
  6000. collectStyle(context); // prepare for value collecting
  6001. context.processing = DECLARATION_PART.PROPERTY;
  6002. }
  6003. break;
  6004. case SINGLE_QUOTE:
  6005. case DOUBLE_QUOTE:
  6006. // if quotes are not open
  6007. if (context.valueQuoteMark === null) {
  6008. // save the opening quote mark for later comparison
  6009. context.valueQuoteMark = tokenValue;
  6010. } else if (
  6011. !context.bufferValue.endsWith(BACKSLASH) && // otherwise a quote appeared in the value earlier,
  6012. // and non-escaped quote should be checked whether it is a closing quote
  6013. context.valueQuoteMark === tokenValue
  6014. ) {
  6015. context.valueQuoteMark = null;
  6016. } // always save the quote to the buffer
  6017. // but after the context.bufferValue is checked for BACKSLASH above
  6018. // e.g. 'content: "test:123"'
  6019. // 'content: "\""'
  6020. context.bufferValue += tokenValue;
  6021. break;
  6022. case BACKSLASH:
  6023. if (!isValueQuotesOpen(context)) {
  6024. // eslint-disable-next-line max-len
  6025. throw new Error(
  6026. `Invalid style value for property '${context.bufferProperty}' in style block: '${styleBlock}'`
  6027. );
  6028. } // collect the backslash inside quotes
  6029. // e.g. ' content: "\"" '
  6030. // parser is here ↑
  6031. context.bufferValue += tokenValue;
  6032. break;
  6033. case SPACE:
  6034. case TAB:
  6035. case CARRIAGE_RETURN:
  6036. case LINE_FEED:
  6037. case FORM_FEED:
  6038. // whitespace should be collected only if the value collecting started
  6039. // which means inside of the value
  6040. // e.g. 'width: 100% !important'
  6041. // parser is here ↑
  6042. if (context.bufferValue.length > 0) {
  6043. context.bufferValue += tokenValue;
  6044. } // otherwise it can be omitted
  6045. // e.g. 'width: 100% !important'
  6046. // here ↑
  6047. break;
  6048. default:
  6049. throw new Error(`Unknown style declaration token: '${tokenValue}'`);
  6050. }
  6051. }
  6052. };
  6053. /**
  6054. * Parses css rule style block.
  6055. *
  6056. * @param rawStyleBlock Style block to parse.
  6057. *
  6058. * @returns Array of style declarations.
  6059. * @throws An error on invalid style block.
  6060. */
  6061. const parseStyleBlock = (rawStyleBlock) => {
  6062. const styleBlock = rawStyleBlock.trim();
  6063. const tokens = tokenizeStyleBlock(styleBlock);
  6064. const context = {
  6065. // style declaration parsing always starts with 'property'
  6066. processing: DECLARATION_PART.PROPERTY,
  6067. styles: [],
  6068. bufferProperty: "",
  6069. bufferValue: "",
  6070. valueQuoteMark: null,
  6071. };
  6072. let i = 0;
  6073. while (i < tokens.length) {
  6074. const token = tokens[i];
  6075. if (!token) {
  6076. break;
  6077. }
  6078. if (context.processing === DECLARATION_PART.PROPERTY) {
  6079. processPropertyToken(context, styleBlock, token);
  6080. } else if (context.processing === DECLARATION_PART.VALUE) {
  6081. processValueToken(context, styleBlock, token);
  6082. } else {
  6083. throw new Error("Style declaration parsing failed");
  6084. }
  6085. i += 1;
  6086. } // unbalanced value quotes
  6087. // e.g. 'content: "test} '
  6088. if (isValueQuotesOpen(context)) {
  6089. throw new Error(
  6090. `Unbalanced style declaration quotes in style block: '${styleBlock}'`
  6091. );
  6092. } // collected property and value have not been saved to styles;
  6093. // it is possible for style block with no semicolon at the end
  6094. // e.g. such style block: '{ display: none }'
  6095. if (context.bufferProperty.length > 0) {
  6096. if (context.bufferValue.length === 0) {
  6097. // e.g. such style blocks:
  6098. // '{ display: }'
  6099. // '{ remove }'
  6100. // eslint-disable-next-line max-len
  6101. throw new Error(
  6102. `Missing style value for property '${context.bufferProperty}' in style block '${styleBlock}'`
  6103. );
  6104. }
  6105. collectStyle(context);
  6106. } // rule with empty style block
  6107. // e.g. 'div { }'
  6108. if (context.styles.length === 0) {
  6109. throw new Error(STYLE_ERROR_PREFIX.NO_STYLE);
  6110. }
  6111. return context.styles;
  6112. };
  6113. /**
  6114. * Returns array of positions of `{` in `cssRule`.
  6115. *
  6116. * @param cssRule CSS rule.
  6117. *
  6118. * @returns Array of left curly bracket indexes.
  6119. */
  6120. const getLeftCurlyBracketIndexes = (cssRule) => {
  6121. const indexes = [];
  6122. for (let i = 0; i < cssRule.length; i += 1) {
  6123. if (cssRule[i] === BRACKET.CURLY.LEFT) {
  6124. indexes.push(i);
  6125. }
  6126. }
  6127. return indexes;
  6128. }; // TODO: use `extCssDoc` for caching of style block parser results
  6129. /**
  6130. * Parses CSS rule into rules data object:
  6131. * 1. Find the last `{` mark in the rule
  6132. * which supposed to be a divider between selector and style block.
  6133. * 2. Validates found string part before the `{` via selector parser; and if:
  6134. * - parsing failed – get the previous `{` in the rule,
  6135. * and validates a new rule part again [2];
  6136. * - parsing successful — saves a found rule part as selector and parses the style block.
  6137. *
  6138. * @param rawCssRule Single CSS rule to parse.
  6139. * @param extCssDoc ExtCssDocument which is used for selector ast caching.
  6140. *
  6141. * @returns Array of rules data which contains:
  6142. * - selector as string;
  6143. * - ast to query elements by;
  6144. * - map of styles to apply.
  6145. * @throws An error on invalid css rule syntax:
  6146. * - unsupported CSS features – comments and at-rules
  6147. * - invalid selector or style block.
  6148. */
  6149. const parseRule = (rawCssRule, extCssDoc) => {
  6150. var _rawRuleData$selector;
  6151. const cssRule = rawCssRule.trim();
  6152. if (
  6153. cssRule.includes(`${SLASH}${ASTERISK}`) &&
  6154. cssRule.includes(`${ASTERISK}${SLASH}`)
  6155. ) {
  6156. throw new Error(STYLE_ERROR_PREFIX.NO_COMMENT);
  6157. }
  6158. const leftCurlyBracketIndexes = getLeftCurlyBracketIndexes(cssRule); // rule with style block but no selector
  6159. // e.g. '{ display: none; }'
  6160. if (getFirst(leftCurlyBracketIndexes) === 0) {
  6161. throw new Error(NO_SELECTOR_ERROR_PREFIX);
  6162. }
  6163. let selectorData; // if rule has `{` but there is no `}`
  6164. if (
  6165. leftCurlyBracketIndexes.length > 0 &&
  6166. !cssRule.includes(BRACKET.CURLY.RIGHT)
  6167. ) {
  6168. throw new Error(
  6169. `${STYLE_ERROR_PREFIX.NO_STYLE} OR ${STYLE_ERROR_PREFIX.UNCLOSED_STYLE}`
  6170. );
  6171. }
  6172. if (
  6173. // if rule has no `{`
  6174. leftCurlyBracketIndexes.length === 0 || // or `}`
  6175. !cssRule.includes(BRACKET.CURLY.RIGHT)
  6176. ) {
  6177. try {
  6178. // the whole css rule considered as "selector part"
  6179. // which may contain :remove() pseudo-class
  6180. selectorData = parseSelectorRulePart(cssRule, extCssDoc);
  6181. if (selectorData.success) {
  6182. var _selectorData$stylesO;
  6183. // rule with no style block has valid :remove() pseudo-class
  6184. // which is parsed into "styles"
  6185. // e.g. 'div:remove()'
  6186. // but also it can be just selector with no styles
  6187. // e.g. 'div'
  6188. // which should not be considered as valid css rule
  6189. if (
  6190. ((_selectorData$stylesO = selectorData.stylesOfSelector) ===
  6191. null || _selectorData$stylesO === void 0
  6192. ? void 0
  6193. : _selectorData$stylesO.length) === 0
  6194. ) {
  6195. throw new Error(STYLE_ERROR_PREFIX.NO_STYLE_OR_REMOVE);
  6196. }
  6197. return {
  6198. selector: selectorData.selector.trim(),
  6199. ast: selectorData.ast,
  6200. rawStyles: selectorData.stylesOfSelector,
  6201. };
  6202. } else {
  6203. // not valid selector
  6204. throw new Error("Invalid selector");
  6205. }
  6206. } catch (e) {
  6207. throw new Error(getErrorMessage(e));
  6208. }
  6209. }
  6210. let selectorBuffer;
  6211. let styleBlockBuffer;
  6212. const rawRuleData = {
  6213. selector: "",
  6214. }; // css rule should be parsed from its end
  6215. for (let i = leftCurlyBracketIndexes.length - 1; i > -1; i -= 1) {
  6216. const index = leftCurlyBracketIndexes[i];
  6217. if (!index) {
  6218. throw new Error(
  6219. `Impossible to continue, no '{' to process for rule: '${cssRule}'`
  6220. );
  6221. } // selector is before `{`, style block is after it
  6222. selectorBuffer = cssRule.slice(0, index); // skip curly brackets
  6223. styleBlockBuffer = cssRule.slice(index + 1, cssRule.length - 1);
  6224. selectorData = parseSelectorRulePart(selectorBuffer, extCssDoc);
  6225. if (selectorData.success) {
  6226. var _rawRuleData$rawStyle;
  6227. // selector successfully parsed
  6228. rawRuleData.selector = selectorData.selector.trim();
  6229. rawRuleData.ast = selectorData.ast;
  6230. rawRuleData.rawStyles = selectorData.stylesOfSelector; // style block should be parsed
  6231. // TODO: add cache for style block parsing
  6232. const parsedStyles = parseStyleBlock(styleBlockBuffer);
  6233. (_rawRuleData$rawStyle = rawRuleData.rawStyles) === null ||
  6234. _rawRuleData$rawStyle === void 0
  6235. ? void 0
  6236. : _rawRuleData$rawStyle.push(...parsedStyles); // stop rule parsing
  6237. break;
  6238. } else {
  6239. // if selector was not parsed successfully
  6240. // continue with next index of `{`
  6241. continue;
  6242. }
  6243. }
  6244. if (
  6245. ((_rawRuleData$selector = rawRuleData.selector) === null ||
  6246. _rawRuleData$selector === void 0
  6247. ? void 0
  6248. : _rawRuleData$selector.length) === 0
  6249. ) {
  6250. // skip the rule as selector
  6251. throw new Error("Selector in not valid");
  6252. }
  6253. return rawRuleData;
  6254. };
  6255. /**
  6256. * Parses array of CSS rules into array of rules data objects.
  6257. * Invalid rules are skipped and not applied,
  6258. * and the errors are logged.
  6259. *
  6260. * @param rawCssRules Array of rules to parse.
  6261. * @param extCssDoc Needed for selector ast caching.
  6262. *
  6263. * @returns Array of parsed valid rules data.
  6264. */
  6265. const parseRules$1 = (rawCssRules, extCssDoc) => {
  6266. const rawResults = createRawResultsMap();
  6267. const warnings = []; // trim all rules and find unique ones
  6268. const uniqueRules = [...new Set(rawCssRules.map((r) => r.trim()))];
  6269. uniqueRules.forEach((rule) => {
  6270. try {
  6271. saveToRawResults(rawResults, parseRule(rule, extCssDoc));
  6272. } catch (e) {
  6273. // skip the invalid rule
  6274. const errorMessage = getErrorMessage(e);
  6275. warnings.push(`'${rule}' - error: '${errorMessage}'`);
  6276. }
  6277. }); // log info about skipped invalid rules
  6278. if (warnings.length > 0) {
  6279. logger.info(`Invalid rules:\n ${warnings.join("\n ")}`);
  6280. }
  6281. return combineRulesData(rawResults);
  6282. };
  6283. const REGEXP_DECLARATION_END = /[;}]/g;
  6284. const REGEXP_DECLARATION_DIVIDER = /[;:}]/g;
  6285. const REGEXP_NON_WHITESPACE = /\S/g;
  6286. /**
  6287. * Interface for stylesheet parser context.
  6288. */
  6289. /**
  6290. * Resets rule data buffer to init value after rule successfully collected.
  6291. *
  6292. * @param context Stylesheet parser context.
  6293. */
  6294. const restoreRuleAcc = (context) => {
  6295. context.rawRuleData = {
  6296. selector: "",
  6297. };
  6298. };
  6299. /**
  6300. * Parses cropped selector part found before `{` previously.
  6301. *
  6302. * @param context Stylesheet parser context.
  6303. * @param extCssDoc Needed for caching of selector ast.
  6304. *
  6305. * @returns Parsed validation data for cropped part of stylesheet which may be a selector.
  6306. * @throws An error on unsupported CSS features, e.g. at-rules.
  6307. */
  6308. const parseSelectorPart = (context, extCssDoc) => {
  6309. let selector = context.selectorBuffer.trim();
  6310. if (selector.startsWith(AT_RULE_MARKER)) {
  6311. throw new Error(`${NO_AT_RULE_ERROR_PREFIX}: '${selector}'.`);
  6312. }
  6313. let removeSelectorData;
  6314. try {
  6315. removeSelectorData = parseRemoveSelector(selector);
  6316. } catch (e) {
  6317. logger.error(getErrorMessage(e));
  6318. throw new Error(`${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`);
  6319. }
  6320. if (context.nextIndex === -1) {
  6321. if (selector === removeSelectorData.selector) {
  6322. // rule should have style or pseudo-class :remove()
  6323. throw new Error(
  6324. `${STYLE_ERROR_PREFIX.NO_STYLE_OR_REMOVE}: '${context.cssToParse}'`
  6325. );
  6326. } // stop parsing as there is no style declaration and selector parsed fine
  6327. context.cssToParse = "";
  6328. }
  6329. let stylesOfSelector = [];
  6330. let success = false;
  6331. let ast;
  6332. try {
  6333. selector = removeSelectorData.selector;
  6334. stylesOfSelector = removeSelectorData.stylesOfSelector; // validate found selector by parsing it to ast
  6335. // so if it is invalid error will be thrown
  6336. ast = extCssDoc.getSelectorAst(selector);
  6337. success = true;
  6338. } catch (e) {
  6339. success = false;
  6340. }
  6341. if (context.nextIndex > 0) {
  6342. // slice found valid selector part off
  6343. // and parse rest of stylesheet later
  6344. context.cssToParse = context.cssToParse.slice(context.nextIndex);
  6345. }
  6346. return {
  6347. success,
  6348. selector,
  6349. ast,
  6350. stylesOfSelector,
  6351. };
  6352. };
  6353. /**
  6354. * Recursively parses style declaration string into `Style`s.
  6355. *
  6356. * @param context Stylesheet parser context.
  6357. * @param styles Array of styles.
  6358. *
  6359. * @throws An error on invalid style declaration.
  6360. * @returns A number index of the next `}` in `this.cssToParse`.
  6361. */
  6362. const parseUntilClosingBracket = (context, styles) => {
  6363. // Expects ":", ";", and "}".
  6364. REGEXP_DECLARATION_DIVIDER.lastIndex = context.nextIndex;
  6365. let match = REGEXP_DECLARATION_DIVIDER.exec(context.cssToParse);
  6366. if (match === null) {
  6367. throw new Error(
  6368. `${STYLE_ERROR_PREFIX.INVALID_STYLE}: '${context.cssToParse}'`
  6369. );
  6370. }
  6371. let matchPos = match.index;
  6372. let matched = match[0];
  6373. if (matched === BRACKET.CURLY.RIGHT) {
  6374. const declarationChunk = context.cssToParse.slice(
  6375. context.nextIndex,
  6376. matchPos
  6377. );
  6378. if (declarationChunk.trim().length === 0) {
  6379. // empty style declaration
  6380. // e.g. 'div { }'
  6381. if (styles.length === 0) {
  6382. throw new Error(
  6383. `${STYLE_ERROR_PREFIX.NO_STYLE}: '${context.cssToParse}'`
  6384. );
  6385. } // else valid style parsed before it
  6386. // e.g. '{ display: none; }' -- position is after ';'
  6387. } else {
  6388. // closing curly bracket '}' is matched before colon ':'
  6389. // trimmed declarationChunk is not a space, between ';' and '}',
  6390. // e.g. 'visible }' in style '{ display: none; visible }' after part before ';' is parsed
  6391. throw new Error(
  6392. `${STYLE_ERROR_PREFIX.INVALID_STYLE}: '${context.cssToParse}'`
  6393. );
  6394. }
  6395. return matchPos;
  6396. }
  6397. if (matched === COLON) {
  6398. const colonIndex = matchPos; // Expects ";" and "}".
  6399. REGEXP_DECLARATION_END.lastIndex = colonIndex;
  6400. match = REGEXP_DECLARATION_END.exec(context.cssToParse);
  6401. if (match === null) {
  6402. throw new Error(
  6403. `${STYLE_ERROR_PREFIX.UNCLOSED_STYLE}: '${context.cssToParse}'`
  6404. );
  6405. }
  6406. matchPos = match.index;
  6407. matched = match[0]; // Populates the `styleMap` key-value map.
  6408. const property = context.cssToParse
  6409. .slice(context.nextIndex, colonIndex)
  6410. .trim();
  6411. if (property.length === 0) {
  6412. throw new Error(
  6413. `${STYLE_ERROR_PREFIX.NO_PROPERTY}: '${context.cssToParse}'`
  6414. );
  6415. }
  6416. const value = context.cssToParse.slice(colonIndex + 1, matchPos).trim();
  6417. if (value.length === 0) {
  6418. throw new Error(
  6419. `${STYLE_ERROR_PREFIX.NO_VALUE}: '${context.cssToParse}'`
  6420. );
  6421. }
  6422. styles.push({
  6423. property,
  6424. value,
  6425. }); // finish style parsing if '}' is found
  6426. // e.g. '{ display: none }' -- no ';' at the end of declaration
  6427. if (matched === BRACKET.CURLY.RIGHT) {
  6428. return matchPos;
  6429. }
  6430. } // matchPos is the position of the next ';'
  6431. // crop 'cssToParse' and re-run the loop
  6432. context.cssToParse = context.cssToParse.slice(matchPos + 1);
  6433. context.nextIndex = 0;
  6434. return parseUntilClosingBracket(context, styles); // Should be a subject of tail-call optimization.
  6435. };
  6436. /**
  6437. * Parses next style declaration part in stylesheet.
  6438. *
  6439. * @param context Stylesheet parser context.
  6440. *
  6441. * @returns Array of style data objects.
  6442. */
  6443. const parseNextStyle = (context) => {
  6444. const styles = [];
  6445. const styleEndPos = parseUntilClosingBracket(context, styles); // find next rule after the style declaration
  6446. REGEXP_NON_WHITESPACE.lastIndex = styleEndPos + 1;
  6447. const match = REGEXP_NON_WHITESPACE.exec(context.cssToParse);
  6448. if (match === null) {
  6449. context.cssToParse = "";
  6450. return styles;
  6451. }
  6452. const matchPos = match.index; // cut out matched style declaration for previous selector
  6453. context.cssToParse = context.cssToParse.slice(matchPos);
  6454. return styles;
  6455. };
  6456. /**
  6457. * Parses stylesheet of rules into rules data objects (non-recursively):
  6458. * 1. Iterates through stylesheet string.
  6459. * 2. Finds first `{` which can be style declaration start or part of selector.
  6460. * 3. Validates found string part via selector parser; and if:
  6461. * - it throws error — saves string part to buffer as part of selector,
  6462. * slice next stylesheet part to `{` [2] and validates again [3];
  6463. * - no error — saves found string part as selector and starts to parse styles (recursively).
  6464. *
  6465. * @param rawStylesheet Raw stylesheet as string.
  6466. * @param extCssDoc ExtCssDocument which uses cache while selectors parsing.
  6467. * @throws An error on unsupported CSS features, e.g. comments or invalid stylesheet syntax.
  6468. * @returns Array of rules data which contains:
  6469. * - selector as string;
  6470. * - ast to query elements by;
  6471. * - map of styles to apply.
  6472. */
  6473. const parseStylesheet = (rawStylesheet, extCssDoc) => {
  6474. const stylesheet = rawStylesheet.trim();
  6475. if (
  6476. stylesheet.includes(`${SLASH}${ASTERISK}`) &&
  6477. stylesheet.includes(`${ASTERISK}${SLASH}`)
  6478. ) {
  6479. throw new Error(
  6480. `${STYLE_ERROR_PREFIX.NO_COMMENT} in stylesheet: '${stylesheet}'`
  6481. );
  6482. }
  6483. const context = {
  6484. // any stylesheet should start with selector
  6485. isSelector: true,
  6486. // init value of parser position
  6487. nextIndex: 0,
  6488. // init value of cssToParse
  6489. cssToParse: stylesheet,
  6490. // buffer for collecting selector part
  6491. selectorBuffer: "",
  6492. // accumulator for rules
  6493. rawRuleData: {
  6494. selector: "",
  6495. },
  6496. };
  6497. const rawResults = createRawResultsMap();
  6498. let selectorData; // context.cssToParse is going to be cropped while its parsing
  6499. while (context.cssToParse) {
  6500. if (context.isSelector) {
  6501. // find index of first opening curly bracket
  6502. // which may mean start of style part and end of selector one
  6503. context.nextIndex = context.cssToParse.indexOf(BRACKET.CURLY.LEFT); // rule should not start with style, selector is required
  6504. // e.g. '{ display: none; }'
  6505. if (context.selectorBuffer.length === 0 && context.nextIndex === 0) {
  6506. throw new Error(
  6507. `${STYLE_ERROR_PREFIX.NO_SELECTOR}: '${context.cssToParse}'`
  6508. );
  6509. }
  6510. if (context.nextIndex === -1) {
  6511. // no style declaration in rule
  6512. // but rule still may contain :remove() pseudo-class
  6513. context.selectorBuffer = context.cssToParse;
  6514. } else {
  6515. // collect string parts before opening curly bracket
  6516. // until valid selector collected
  6517. context.selectorBuffer += context.cssToParse.slice(
  6518. 0,
  6519. context.nextIndex
  6520. );
  6521. }
  6522. selectorData = parseSelectorPart(context, extCssDoc);
  6523. if (selectorData.success) {
  6524. // selector successfully parsed
  6525. context.rawRuleData.selector = selectorData.selector.trim();
  6526. context.rawRuleData.ast = selectorData.ast;
  6527. context.rawRuleData.rawStyles = selectorData.stylesOfSelector;
  6528. context.isSelector = false; // save rule data if there is no style declaration
  6529. if (context.nextIndex === -1) {
  6530. saveToRawResults(rawResults, context.rawRuleData); // clean up ruleContext
  6531. restoreRuleAcc(context);
  6532. } else {
  6533. // skip the opening curly bracket at the start of style declaration part
  6534. context.nextIndex = 1;
  6535. context.selectorBuffer = "";
  6536. }
  6537. } else {
  6538. // if selector was not successfully parsed parseSelectorPart(), continue stylesheet parsing:
  6539. // save the found bracket to buffer and proceed to next loop iteration
  6540. context.selectorBuffer += BRACKET.CURLY.LEFT; // delete `{` from cssToParse
  6541. context.cssToParse = context.cssToParse.slice(1);
  6542. }
  6543. } else {
  6544. var _context$rawRuleData$;
  6545. // style declaration should be parsed
  6546. const parsedStyles = parseNextStyle(context); // styles can be parsed from selector part if it has :remove() pseudo-class
  6547. // e.g. '.banner:remove() { debug: true; }'
  6548. (_context$rawRuleData$ = context.rawRuleData.rawStyles) === null ||
  6549. _context$rawRuleData$ === void 0
  6550. ? void 0
  6551. : _context$rawRuleData$.push(...parsedStyles); // save rule data to results
  6552. saveToRawResults(rawResults, context.rawRuleData);
  6553. context.nextIndex = 0; // clean up ruleContext
  6554. restoreRuleAcc(context); // parse next rule selector after style successfully parsed
  6555. context.isSelector = true;
  6556. }
  6557. }
  6558. return combineRulesData(rawResults);
  6559. };
  6560. /**
  6561. * Checks whether passed `arg` is number type.
  6562. *
  6563. * @param arg Value to check.
  6564. *
  6565. * @returns True if `arg` is number and not NaN.
  6566. */
  6567. const isNumber = (arg) => {
  6568. return typeof arg === "number" && !Number.isNaN(arg);
  6569. };
  6570. /**
  6571. * The purpose of ThrottleWrapper is to throttle calls of the function
  6572. * that applies ExtendedCss rules. The reasoning here is that the function calls
  6573. * are triggered by MutationObserver and there may be many mutations in a short period of time.
  6574. * We do not want to apply rules on every mutation so we use this helper to make sure
  6575. * that there is only one call in the given amount of time.
  6576. */
  6577. class ThrottleWrapper {
  6578. /**
  6579. * Creates new ThrottleWrapper.
  6580. * The {@link callback} should be executed not more often than {@link ThrottleWrapper.THROTTLE_DELAY_MS}.
  6581. *
  6582. * @param callback The callback.
  6583. */
  6584. constructor(callback) {
  6585. this.callback = callback;
  6586. this.executeCallback = this.executeCallback.bind(this);
  6587. }
  6588. /**
  6589. * Calls the {@link callback} function and update bounded throttle wrapper properties.
  6590. */
  6591. executeCallback() {
  6592. this.lastRunTime = performance.now();
  6593. if (isNumber(this.timerId)) {
  6594. clearTimeout(this.timerId);
  6595. delete this.timerId;
  6596. }
  6597. this.callback();
  6598. }
  6599. /**
  6600. * Schedules the {@link executeCallback} function execution via setTimeout.
  6601. * It may triggered by MutationObserver job which may occur too ofter, so we limit the function execution:
  6602. *
  6603. * 1. If {@link timerId} is set, ignore the call, because the function is already scheduled to be executed;
  6604. *
  6605. * 2. If {@link lastRunTime} is set, we need to check the time elapsed time since the last call. If it is
  6606. * less than {@link ThrottleWrapper.THROTTLE_DELAY_MS}, we schedule the function execution after the remaining time.
  6607. *
  6608. * Otherwise, we execute the function asynchronously to ensure that it is executed
  6609. * in the correct order with respect to DOM events, by deferring its execution until after
  6610. * those tasks have completed.
  6611. */
  6612. run() {
  6613. if (isNumber(this.timerId)) {
  6614. // there is a pending execution scheduled
  6615. return;
  6616. }
  6617. if (isNumber(this.lastRunTime)) {
  6618. const elapsedTime = performance.now() - this.lastRunTime;
  6619. if (elapsedTime < ThrottleWrapper.THROTTLE_DELAY_MS) {
  6620. this.timerId = window.setTimeout(
  6621. this.executeCallback,
  6622. ThrottleWrapper.THROTTLE_DELAY_MS - elapsedTime
  6623. );
  6624. return;
  6625. }
  6626. }
  6627. /**
  6628. * We use `setTimeout` instead `requestAnimationFrame`
  6629. * here because requestAnimationFrame can be delayed for a long time
  6630. * when the browser saves battery or the engine is heavily loaded.
  6631. */
  6632. this.timerId = window.setTimeout(this.executeCallback);
  6633. }
  6634. }
  6635. _defineProperty(ThrottleWrapper, "THROTTLE_DELAY_MS", 150);
  6636. const LAST_EVENT_TIMEOUT_MS = 10;
  6637. const IGNORED_EVENTS = [
  6638. "mouseover",
  6639. "mouseleave",
  6640. "mouseenter",
  6641. "mouseout",
  6642. ];
  6643. const SUPPORTED_EVENTS = [
  6644. // keyboard events
  6645. "keydown",
  6646. "keypress",
  6647. "keyup",
  6648. // mouse events
  6649. "auxclick",
  6650. "click",
  6651. "contextmenu",
  6652. "dblclick",
  6653. "mousedown",
  6654. "mouseenter",
  6655. "mouseleave",
  6656. "mousemove",
  6657. "mouseover",
  6658. "mouseout",
  6659. "mouseup",
  6660. "pointerlockchange",
  6661. "pointerlockerror",
  6662. "select",
  6663. "wheel",
  6664. ]; // 'wheel' event makes scrolling in Safari twitchy
  6665. // https://github.com/AdguardTeam/ExtendedCss/issues/120
  6666. const SAFARI_PROBLEMATIC_EVENTS = ["wheel"];
  6667. /**
  6668. * We use EventTracker to track the event that is likely to cause the mutation.
  6669. * The problem is that we cannot use `window.event` directly from the mutation observer call
  6670. * as we're not in the event handler context anymore.
  6671. */
  6672. class EventTracker {
  6673. /**
  6674. * Creates new EventTracker.
  6675. */
  6676. constructor() {
  6677. _defineProperty(this, "getLastEventType", () => this.lastEventType);
  6678. _defineProperty(this, "getTimeSinceLastEvent", () => {
  6679. if (!this.lastEventTime) {
  6680. return null;
  6681. }
  6682. return Date.now() - this.lastEventTime;
  6683. });
  6684. this.trackedEvents = isSafariBrowser
  6685. ? SUPPORTED_EVENTS.filter(
  6686. (event) => !SAFARI_PROBLEMATIC_EVENTS.includes(event)
  6687. )
  6688. : SUPPORTED_EVENTS;
  6689. this.trackedEvents.forEach((eventName) => {
  6690. document.documentElement.addEventListener(
  6691. eventName,
  6692. this.trackEvent,
  6693. true
  6694. );
  6695. });
  6696. }
  6697. /**
  6698. * Callback for event listener for events tracking.
  6699. *
  6700. * @param event Any event.
  6701. */
  6702. trackEvent(event) {
  6703. this.lastEventType = event.type;
  6704. this.lastEventTime = Date.now();
  6705. }
  6706. /**
  6707. * Checks whether the last caught event should be ignored.
  6708. *
  6709. * @returns True if event should be ignored.
  6710. */
  6711. isIgnoredEventType() {
  6712. const lastEventType = this.getLastEventType();
  6713. const sinceLastEventTime = this.getTimeSinceLastEvent();
  6714. return (
  6715. !!lastEventType &&
  6716. IGNORED_EVENTS.includes(lastEventType) &&
  6717. !!sinceLastEventTime &&
  6718. sinceLastEventTime < LAST_EVENT_TIMEOUT_MS
  6719. );
  6720. }
  6721. /**
  6722. * Stops event tracking by removing event listener.
  6723. */
  6724. stopTracking() {
  6725. this.trackedEvents.forEach((eventName) => {
  6726. document.documentElement.removeEventListener(
  6727. eventName,
  6728. this.trackEvent,
  6729. true
  6730. );
  6731. });
  6732. }
  6733. }
  6734. /**
  6735. * We are trying to limit the number of callback calls by not calling it on all kind of "hover" events.
  6736. * The rationale behind this is that "hover" events often cause attributes modification,
  6737. * but re-applying extCSS rules will be useless as these attribute changes are usually transient.
  6738. *
  6739. * @param mutations DOM elements mutation records.
  6740. * @returns True if all mutations are about attributes changes, otherwise false.
  6741. */
  6742. function shouldIgnoreMutations(mutations) {
  6743. // ignore if all mutations are about attributes changes
  6744. return !mutations.some((m) => m.type !== "attributes");
  6745. }
  6746. /**
  6747. * Adds new {@link context.domMutationObserver} instance and connect it to document.
  6748. *
  6749. * @param context ExtendedCss context.
  6750. */
  6751. function observeDocument(context) {
  6752. if (context.isDomObserved) {
  6753. return;
  6754. } // enable dynamically added elements handling
  6755. context.isDomObserved = true;
  6756. context.domMutationObserver = new natives.MutationObserver(
  6757. (mutations) => {
  6758. if (!mutations || mutations.length === 0) {
  6759. return;
  6760. }
  6761. const eventTracker = new EventTracker();
  6762. if (
  6763. eventTracker.isIgnoredEventType() &&
  6764. shouldIgnoreMutations(mutations)
  6765. ) {
  6766. return;
  6767. } // save instance of EventTracker to context
  6768. // for removing its event listeners on disconnectDocument() while mainDisconnect()
  6769. context.eventTracker = eventTracker;
  6770. context.scheduler.run();
  6771. }
  6772. );
  6773. context.domMutationObserver.observe(document, {
  6774. childList: true,
  6775. subtree: true,
  6776. attributes: true,
  6777. attributeFilter: ["id", "class"],
  6778. });
  6779. }
  6780. /**
  6781. * Disconnect from {@link context.domMutationObserver}.
  6782. *
  6783. * @param context ExtendedCss context.
  6784. */
  6785. function disconnectDocument(context) {
  6786. if (!context.isDomObserved) {
  6787. return;
  6788. } // disable dynamically added elements handling
  6789. context.isDomObserved = false;
  6790. if (context.domMutationObserver) {
  6791. context.domMutationObserver.disconnect();
  6792. } // clean up event listeners
  6793. if (context.eventTracker) {
  6794. context.eventTracker.stopTracking();
  6795. }
  6796. }
  6797. const CONTENT_ATTR_PREFIX_REGEXP = /^("|')adguard.+?/;
  6798. /**
  6799. * Removes affectedElement.node from DOM.
  6800. *
  6801. * @param context ExtendedCss context.
  6802. * @param affectedElement Affected element.
  6803. */
  6804. const removeElement = (context, affectedElement) => {
  6805. const { node } = affectedElement;
  6806. affectedElement.removed = true;
  6807. const elementSelector = getElementSelectorPath(node); // check if the element has been already removed earlier
  6808. const elementRemovalsCounter =
  6809. context.removalsStatistic[elementSelector] || 0; // if removals attempts happened more than specified we do not try to remove node again
  6810. if (elementRemovalsCounter > MAX_STYLE_PROTECTION_COUNT) {
  6811. logger.error(
  6812. `ExtendedCss: infinite loop protection for selector: '${elementSelector}'`
  6813. );
  6814. return;
  6815. }
  6816. if (node.parentElement) {
  6817. node.parentElement.removeChild(node);
  6818. context.removalsStatistic[elementSelector] = elementRemovalsCounter + 1;
  6819. }
  6820. };
  6821. /**
  6822. * Sets style to the specified DOM node.
  6823. *
  6824. * @param node DOM element.
  6825. * @param style Style to set.
  6826. */
  6827. const setStyleToElement = (node, style) => {
  6828. if (!(node instanceof HTMLElement)) {
  6829. return;
  6830. }
  6831. Object.keys(style).forEach((prop) => {
  6832. // Apply this style only to existing properties
  6833. // We cannot use hasOwnProperty here (does not work in FF)
  6834. if (
  6835. typeof node.style.getPropertyValue(prop.toString()) !== "undefined"
  6836. ) {
  6837. let value = style[prop];
  6838. if (!value) {
  6839. return;
  6840. } // do not apply 'content' style given by tsurlfilter
  6841. // which is needed only for BeforeStyleAppliedCallback
  6842. if (
  6843. prop === CONTENT_CSS_PROPERTY &&
  6844. value.match(CONTENT_ATTR_PREFIX_REGEXP)
  6845. ) {
  6846. return;
  6847. } // First we should remove !important attribute (or it won't be applied')
  6848. value = removeSuffix(value.trim(), "!important").trim();
  6849. node.style.setProperty(prop, value, "important");
  6850. }
  6851. });
  6852. };
  6853. /**
  6854. * Checks the required properties of `affectedElement`
  6855. * **before** `beforeStyleApplied()` execution.
  6856. *
  6857. * @param affectedElement Affected element.
  6858. *
  6859. * @returns False if there is no `node` or `rules`
  6860. * or `rules` is not an array.
  6861. */
  6862. const isIAffectedElement = (affectedElement) => {
  6863. return (
  6864. "node" in affectedElement &&
  6865. "rules" in affectedElement &&
  6866. affectedElement.rules instanceof Array
  6867. );
  6868. };
  6869. /**
  6870. * Checks the required properties of `affectedElement`
  6871. * **after** `beforeStyleApplied()` execution.
  6872. * These properties are needed for proper internal usage.
  6873. *
  6874. * @param affectedElement Affected element.
  6875. *
  6876. * @returns False if there is no `node` or `rules`
  6877. * or `rules` is not an array.
  6878. */
  6879. const isAffectedElement = (affectedElement) => {
  6880. return (
  6881. "node" in affectedElement &&
  6882. "originalStyle" in affectedElement &&
  6883. "rules" in affectedElement &&
  6884. affectedElement.rules instanceof Array
  6885. );
  6886. };
  6887. /**
  6888. * Applies style to the specified DOM node.
  6889. *
  6890. * @param context ExtendedCss context.
  6891. * @param rawAffectedElement Object containing DOM node and rule to be applied.
  6892. *
  6893. * @throws An error if affectedElement has no style to apply.
  6894. */
  6895. const applyStyle = (context, rawAffectedElement) => {
  6896. if (rawAffectedElement.protectionObserver) {
  6897. // style is already applied and protected by the observer
  6898. return;
  6899. }
  6900. let affectedElement;
  6901. if (context.beforeStyleApplied) {
  6902. if (!isIAffectedElement(rawAffectedElement)) {
  6903. throw new Error(
  6904. "Returned IAffectedElement should have 'node' and 'rules' properties"
  6905. );
  6906. }
  6907. affectedElement = context.beforeStyleApplied(rawAffectedElement);
  6908. if (!affectedElement) {
  6909. throw new Error(
  6910. "Callback 'beforeStyleApplied' should return IAffectedElement"
  6911. );
  6912. }
  6913. } else {
  6914. affectedElement = rawAffectedElement;
  6915. }
  6916. if (!isAffectedElement(affectedElement)) {
  6917. throw new Error(
  6918. "Returned IAffectedElement should have 'node' and 'rules' properties"
  6919. );
  6920. }
  6921. const { node, rules } = affectedElement;
  6922. for (let i = 0; i < rules.length; i += 1) {
  6923. const rule = rules[i];
  6924. const selector =
  6925. rule === null || rule === void 0 ? void 0 : rule.selector;
  6926. const style = rule === null || rule === void 0 ? void 0 : rule.style;
  6927. const debug = rule === null || rule === void 0 ? void 0 : rule.debug; // rule may not have style to apply
  6928. // e.g. 'div:has(> a) { debug: true }' -> means no style to apply, and enable debug mode
  6929. if (style) {
  6930. if (style[REMOVE_PSEUDO_MARKER] === PSEUDO_PROPERTY_POSITIVE_VALUE) {
  6931. removeElement(context, affectedElement);
  6932. return;
  6933. }
  6934. setStyleToElement(node, style);
  6935. } else if (!debug) {
  6936. // but rule should not have both style and debug properties
  6937. throw new Error(
  6938. `No style declaration in rule for selector: '${selector}'`
  6939. );
  6940. }
  6941. }
  6942. };
  6943. /**
  6944. * Reverts style for the affected object.
  6945. *
  6946. * @param affectedElement Affected element.
  6947. */
  6948. const revertStyle = (affectedElement) => {
  6949. if (affectedElement.protectionObserver) {
  6950. affectedElement.protectionObserver.disconnect();
  6951. }
  6952. affectedElement.node.style.cssText = affectedElement.originalStyle;
  6953. };
  6954. /**
  6955. * ExtMutationObserver is a wrapper over regular MutationObserver with one additional function:
  6956. * it keeps track of the number of times we called the "ProtectionCallback".
  6957. *
  6958. * We use an instance of this to monitor styles added by ExtendedCss
  6959. * and to make sure these styles are recovered if the page script attempts to modify them.
  6960. *
  6961. * However, we want to avoid endless loops of modification if the page script repeatedly modifies the styles.
  6962. * So we keep track of the number of calls and observe() makes a decision
  6963. * whether to continue recovering the styles or not.
  6964. */
  6965. class ExtMutationObserver {
  6966. /**
  6967. * Extra property for keeping 'style fix counts'.
  6968. */
  6969. /**
  6970. * Creates new ExtMutationObserver.
  6971. *
  6972. * @param protectionCallback Callback which execution should be counted.
  6973. */
  6974. constructor(protectionCallback) {
  6975. this.styleProtectionCount = 0;
  6976. this.observer = new natives.MutationObserver((mutations) => {
  6977. if (!mutations.length) {
  6978. return;
  6979. }
  6980. this.styleProtectionCount += 1;
  6981. protectionCallback(mutations, this);
  6982. });
  6983. }
  6984. /**
  6985. * Starts to observe target element,
  6986. * prevents infinite loop of observing due to the limited number of times of callback runs.
  6987. *
  6988. * @param target Target to observe.
  6989. * @param options Mutation observer options.
  6990. */
  6991. observe(target, options) {
  6992. if (this.styleProtectionCount < MAX_STYLE_PROTECTION_COUNT) {
  6993. this.observer.observe(target, options);
  6994. } else {
  6995. logger.error("ExtendedCss: infinite loop protection for style");
  6996. }
  6997. }
  6998. /**
  6999. * Stops ExtMutationObserver from observing any mutations.
  7000. * Until the `observe()` is used again, `protectionCallback` will not be invoked.
  7001. */
  7002. disconnect() {
  7003. this.observer.disconnect();
  7004. }
  7005. }
  7006. const PROTECTION_OBSERVER_OPTIONS = {
  7007. attributes: true,
  7008. attributeOldValue: true,
  7009. attributeFilter: ["style"],
  7010. };
  7011. /**
  7012. * Creates MutationObserver protection callback.
  7013. *
  7014. * @param styles Styles data object.
  7015. *
  7016. * @returns Callback for styles protection.
  7017. */
  7018. const createProtectionCallback = (styles) => {
  7019. const protectionCallback = (mutations, extObserver) => {
  7020. if (!mutations[0]) {
  7021. return;
  7022. }
  7023. const { target } = mutations[0];
  7024. extObserver.disconnect();
  7025. styles.forEach((style) => {
  7026. setStyleToElement(target, style);
  7027. });
  7028. extObserver.observe(target, PROTECTION_OBSERVER_OPTIONS);
  7029. };
  7030. return protectionCallback;
  7031. };
  7032. /**
  7033. * Sets up a MutationObserver which protects style attributes from changes.
  7034. *
  7035. * @param node DOM node.
  7036. * @param rules Rule data objects.
  7037. * @returns Mutation observer used to protect attribute or null if there's nothing to protect.
  7038. */
  7039. const protectStyleAttribute = (node, rules) => {
  7040. if (!natives.MutationObserver) {
  7041. return null;
  7042. }
  7043. const styles = [];
  7044. rules.forEach((ruleData) => {
  7045. const { style } = ruleData; // some rules might have only debug property in style declaration
  7046. // e.g. 'div:has(> a) { debug: true }' -> parsed to boolean `ruleData.debug`
  7047. // so no style is fine, and here we should collect only valid styles to protect
  7048. if (style) {
  7049. styles.push(style);
  7050. }
  7051. });
  7052. const protectionObserver = new ExtMutationObserver(
  7053. createProtectionCallback(styles)
  7054. );
  7055. protectionObserver.observe(node, PROTECTION_OBSERVER_OPTIONS);
  7056. return protectionObserver;
  7057. };
  7058. const STATS_DECIMAL_DIGITS_COUNT = 4;
  7059. /**
  7060. * A helper class for applied rule stats.
  7061. */
  7062. class TimingStats {
  7063. /**
  7064. * Creates new TimingStats.
  7065. */
  7066. constructor() {
  7067. this.appliesTimings = [];
  7068. this.appliesCount = 0;
  7069. this.timingsSum = 0;
  7070. this.meanTiming = 0;
  7071. this.squaredSum = 0;
  7072. this.standardDeviation = 0;
  7073. }
  7074. /**
  7075. * Observe target element and mark observer as active.
  7076. *
  7077. * @param elapsedTimeMs Time in ms.
  7078. */
  7079. push(elapsedTimeMs) {
  7080. this.appliesTimings.push(elapsedTimeMs);
  7081. this.appliesCount += 1;
  7082. this.timingsSum += elapsedTimeMs;
  7083. this.meanTiming = this.timingsSum / this.appliesCount;
  7084. this.squaredSum += elapsedTimeMs * elapsedTimeMs;
  7085. this.standardDeviation = Math.sqrt(
  7086. this.squaredSum / this.appliesCount - Math.pow(this.meanTiming, 2)
  7087. );
  7088. }
  7089. }
  7090. /**
  7091. * Makes the timestamps more readable.
  7092. *
  7093. * @param timestamp Raw timestamp.
  7094. *
  7095. * @returns Fine-looking timestamps.
  7096. */
  7097. const beautifyTimingNumber = (timestamp) => {
  7098. return Number(timestamp.toFixed(STATS_DECIMAL_DIGITS_COUNT));
  7099. };
  7100. /**
  7101. * Improves timing stats readability.
  7102. *
  7103. * @param rawTimings Collected timings with raw timestamp.
  7104. *
  7105. * @returns Fine-looking timing stats.
  7106. */
  7107. const beautifyTimings = (rawTimings) => {
  7108. return {
  7109. appliesTimings: rawTimings.appliesTimings.map((t) =>
  7110. beautifyTimingNumber(t)
  7111. ),
  7112. appliesCount: beautifyTimingNumber(rawTimings.appliesCount),
  7113. timingsSum: beautifyTimingNumber(rawTimings.timingsSum),
  7114. meanTiming: beautifyTimingNumber(rawTimings.meanTiming),
  7115. standardDeviation: beautifyTimingNumber(rawTimings.standardDeviation),
  7116. };
  7117. };
  7118. /**
  7119. * Prints timing information if debugging mode is enabled.
  7120. *
  7121. * @param context ExtendedCss context.
  7122. */
  7123. const printTimingInfo = (context) => {
  7124. if (context.areTimingsPrinted) {
  7125. return;
  7126. }
  7127. context.areTimingsPrinted = true;
  7128. const timingsLogData = {};
  7129. context.parsedRules.forEach((ruleData) => {
  7130. if (ruleData.timingStats) {
  7131. const { selector, style, debug, matchedElements } = ruleData; // style declaration for some rules is parsed to debug property and no style to apply
  7132. // e.g. 'div:has(> a) { debug: true }'
  7133. if (!style && !debug) {
  7134. throw new Error(
  7135. `Rule should have style declaration for selector: '${selector}'`
  7136. );
  7137. }
  7138. const selectorData = {
  7139. selectorParsed: selector,
  7140. timings: beautifyTimings(ruleData.timingStats),
  7141. }; // `ruleData.style` may contain `remove` pseudo-property
  7142. // and make logs look better
  7143. if (
  7144. style &&
  7145. style[REMOVE_PSEUDO_MARKER] === PSEUDO_PROPERTY_POSITIVE_VALUE
  7146. ) {
  7147. selectorData.removed = true; // no matchedElements for such case as they are removed after ExtendedCss applied
  7148. } else {
  7149. selectorData.styleApplied = style || null;
  7150. selectorData.matchedElements = matchedElements;
  7151. }
  7152. timingsLogData[selector] = selectorData;
  7153. }
  7154. });
  7155. if (Object.keys(timingsLogData).length === 0) {
  7156. return;
  7157. } // add location.href to the message to distinguish frames
  7158. logger.info(
  7159. "[ExtendedCss] Timings in milliseconds for %o:\n%o",
  7160. window.location.href,
  7161. timingsLogData
  7162. );
  7163. };
  7164. /**
  7165. * Finds affectedElement object for the specified DOM node.
  7166. *
  7167. * @param affElements Array of affected elements — context.affectedElements.
  7168. * @param domNode DOM node.
  7169. * @returns Found affectedElement or undefined.
  7170. */
  7171. const findAffectedElement = (affElements, domNode) => {
  7172. return affElements.find((affEl) => affEl.node === domNode);
  7173. };
  7174. /**
  7175. * Applies specified rule and returns list of elements affected.
  7176. *
  7177. * @param context ExtendedCss context.
  7178. * @param ruleData Rule to apply.
  7179. * @returns List of elements affected by the rule.
  7180. */
  7181. const applyRule = (context, ruleData) => {
  7182. // debugging mode can be enabled in two ways:
  7183. // 1. for separate rules - by `{ debug: true; }`
  7184. // 2. for all rules simultaneously by:
  7185. // - `{ debug: global; }` in any rule
  7186. // - positive `debug` property in ExtCssConfiguration
  7187. const isDebuggingMode = !!ruleData.debug || context.debug;
  7188. let startTime;
  7189. if (isDebuggingMode) {
  7190. startTime = performance.now();
  7191. }
  7192. const { ast } = ruleData;
  7193. const nodes = []; // selector can be successfully parser into ast with no error
  7194. // but its applying by native Document.querySelectorAll() still may throw an error
  7195. // e.g. 'div[..banner]'
  7196. try {
  7197. nodes.push(...selectElementsByAst(ast));
  7198. } catch (e) {
  7199. // log the error only in debug mode
  7200. if (context.debug) {
  7201. logger.error(getErrorMessage(e));
  7202. }
  7203. }
  7204. nodes.forEach((node) => {
  7205. let affectedElement = findAffectedElement(
  7206. context.affectedElements,
  7207. node
  7208. );
  7209. if (affectedElement) {
  7210. affectedElement.rules.push(ruleData);
  7211. applyStyle(context, affectedElement);
  7212. } else {
  7213. // Applying style first time
  7214. const originalStyle = node.style.cssText;
  7215. affectedElement = {
  7216. node,
  7217. // affected DOM node
  7218. rules: [ruleData],
  7219. // rule to be applied
  7220. originalStyle,
  7221. // original node style
  7222. protectionObserver: null, // style attribute observer
  7223. };
  7224.  
  7225. applyStyle(context, affectedElement);
  7226. context.affectedElements.push(affectedElement);
  7227. }
  7228. });
  7229. if (isDebuggingMode && startTime) {
  7230. const elapsedTimeMs = performance.now() - startTime;
  7231. if (!ruleData.timingStats) {
  7232. ruleData.timingStats = new TimingStats();
  7233. }
  7234. ruleData.timingStats.push(elapsedTimeMs);
  7235. }
  7236. return nodes;
  7237. };
  7238. /**
  7239. * Applies filtering rules.
  7240. *
  7241. * @param context ExtendedCss context.
  7242. */
  7243. const applyRules = (context) => {
  7244. const newSelectedElements = []; // some rules could make call - selector.querySelectorAll() temporarily to change node id attribute
  7245. // this caused MutationObserver to call recursively
  7246. // https://github.com/AdguardTeam/ExtendedCss/issues/81
  7247. disconnectDocument(context);
  7248. context.parsedRules.forEach((ruleData) => {
  7249. const nodes = applyRule(context, ruleData);
  7250. Array.prototype.push.apply(newSelectedElements, nodes); // save matched elements to ruleData as linked to applied rule
  7251. // only for debugging purposes
  7252. if (ruleData.debug) {
  7253. ruleData.matchedElements = nodes;
  7254. }
  7255. }); // Now revert styles for elements which are no more affected
  7256. let affLength = context.affectedElements.length; // do nothing if there is no elements to process
  7257. while (affLength) {
  7258. const affectedElement = context.affectedElements[affLength - 1];
  7259. if (!affectedElement) {
  7260. break;
  7261. }
  7262. if (!newSelectedElements.includes(affectedElement.node)) {
  7263. // Time to revert style
  7264. revertStyle(affectedElement);
  7265. context.affectedElements.splice(affLength - 1, 1);
  7266. } else if (!affectedElement.removed) {
  7267. // Add style protection observer
  7268. // Protect "style" attribute from changes
  7269. if (!affectedElement.protectionObserver) {
  7270. affectedElement.protectionObserver = protectStyleAttribute(
  7271. affectedElement.node,
  7272. affectedElement.rules
  7273. );
  7274. }
  7275. }
  7276. affLength -= 1;
  7277. } // After styles are applied we can start observe again
  7278. observeDocument(context);
  7279. printTimingInfo(context);
  7280. };
  7281. /**
  7282. * Result of selector validation.
  7283. */
  7284. /**
  7285. * Main class of ExtendedCss lib.
  7286. *
  7287. * Parses css stylesheet with any selectors (passed to its argument as styleSheet),
  7288. * and guarantee its applying as mutation observer is used to prevent the restyling of needed elements by other scripts.
  7289. * This style protection is limited to 50 times to avoid infinite loop (MAX_STYLE_PROTECTION_COUNT).
  7290. * Our own ThrottleWrapper is used for styles applying to avoid too often lib reactions on page mutations.
  7291. *
  7292. * Constructor creates the instance of class which should be run be `apply()` method to apply the rules,
  7293. * and the applying can be stopped by `dispose()`.
  7294. *
  7295. * Can be used to select page elements by selector with `query()` method (similar to `Document.querySelectorAll()`),
  7296. * which does not require instance creating.
  7297. */
  7298. class ExtendedCss {
  7299. /**
  7300. * Creates new ExtendedCss.
  7301. *
  7302. * @param configuration ExtendedCss configuration.
  7303. */
  7304. constructor(configuration) {
  7305. if (!configuration) {
  7306. throw new Error("ExtendedCss configuration should be provided.");
  7307. }
  7308. this.applyRulesCallbackListener =
  7309. this.applyRulesCallbackListener.bind(this);
  7310. this.context = {
  7311. beforeStyleApplied: configuration.beforeStyleApplied,
  7312. debug: false,
  7313. affectedElements: [],
  7314. isDomObserved: false,
  7315. removalsStatistic: {},
  7316. parsedRules: [],
  7317. scheduler: new ThrottleWrapper(this.applyRulesCallbackListener),
  7318. }; // TODO: throw an error instead of logging and handle it in related products.
  7319. if (!isBrowserSupported()) {
  7320. logger.error("Browser is not supported by ExtendedCss");
  7321. return;
  7322. } // at least 'styleSheet' or 'cssRules' should be provided
  7323. if (!configuration.styleSheet && !configuration.cssRules) {
  7324. throw new Error(
  7325. "ExtendedCss configuration should have 'styleSheet' or 'cssRules' defined."
  7326. );
  7327. } // 'styleSheet' and 'cssRules' are optional
  7328. // and both can be provided at the same time
  7329. // so both should be parsed and applied in such case
  7330. if (configuration.styleSheet) {
  7331. // stylesheet parsing can fail on some invalid selectors
  7332. try {
  7333. this.context.parsedRules.push(
  7334. ...parseStylesheet(configuration.styleSheet, extCssDocument)
  7335. );
  7336. } catch (e) {
  7337. // eslint-disable-next-line max-len
  7338. throw new Error(
  7339. `Pass the rules as configuration.cssRules since configuration.styleSheet cannot be parsed because of: '${getErrorMessage(
  7340. e
  7341. )}'`
  7342. );
  7343. }
  7344. }
  7345. if (configuration.cssRules) {
  7346. this.context.parsedRules.push(
  7347. ...parseRules$1(configuration.cssRules, extCssDocument)
  7348. );
  7349. } // true if set in configuration
  7350. // or any rule in styleSheet has `debug: global`
  7351. this.context.debug =
  7352. configuration.debug ||
  7353. this.context.parsedRules.some((ruleData) => {
  7354. return ruleData.debug === DEBUG_PSEUDO_PROPERTY_GLOBAL_VALUE;
  7355. });
  7356. if (
  7357. this.context.beforeStyleApplied &&
  7358. typeof this.context.beforeStyleApplied !== "function"
  7359. ) {
  7360. // eslint-disable-next-line max-len
  7361. throw new Error(
  7362. `Invalid configuration. Type of 'beforeStyleApplied' should be a function, received: '${typeof this
  7363. .context.beforeStyleApplied}'`
  7364. );
  7365. }
  7366. }
  7367. /**
  7368. * Invokes {@link applyRules} function with current app context.
  7369. *
  7370. * This method is bound to the class instance in the constructor because it is called
  7371. * in {@link ThrottleWrapper} and on the DOMContentLoaded event.
  7372. */
  7373. applyRulesCallbackListener() {
  7374. applyRules(this.context);
  7375. }
  7376. /**
  7377. * Initializes ExtendedCss.
  7378. *
  7379. * Should be executed on page ASAP,
  7380. * otherwise the :contains() pseudo-class may work incorrectly.
  7381. */
  7382. init() {
  7383. /**
  7384. * Native Node textContent getter must be intercepted as soon as possible,
  7385. * and stored as it is needed for proper work of :contains() pseudo-class
  7386. * because DOM Node prototype 'textContent' property may be mocked.
  7387. *
  7388. * @see {@link https://github.com/AdguardTeam/ExtendedCss/issues/127}
  7389. */
  7390. nativeTextContent.setGetter();
  7391. }
  7392. /**
  7393. * Applies stylesheet rules on page.
  7394. */
  7395. apply() {
  7396. applyRules(this.context);
  7397. if (document.readyState !== "complete") {
  7398. document.addEventListener(
  7399. "DOMContentLoaded",
  7400. this.applyRulesCallbackListener,
  7401. false
  7402. );
  7403. }
  7404. }
  7405. /**
  7406. * Disposes ExtendedCss and removes our styles from matched elements.
  7407. */
  7408. dispose() {
  7409. disconnectDocument(this.context);
  7410. this.context.affectedElements.forEach((el) => {
  7411. revertStyle(el);
  7412. });
  7413. document.removeEventListener(
  7414. "DOMContentLoaded",
  7415. this.applyRulesCallbackListener,
  7416. false
  7417. );
  7418. }
  7419. /**
  7420. * Exposed for testing purposes only.
  7421. *
  7422. * @returns Array of AffectedElement data objects.
  7423. */
  7424. getAffectedElements() {
  7425. return this.context.affectedElements;
  7426. }
  7427. /**
  7428. * Returns a list of the document's elements that match the specified selector.
  7429. * Uses ExtCssDocument.querySelectorAll().
  7430. *
  7431. * @param selector Selector text.
  7432. * @param [noTiming=true] If true — do not print the timings to the console.
  7433. *
  7434. * @throws An error if selector is not valid.
  7435. * @returns A list of elements that match the selector.
  7436. */
  7437. static query(selector) {
  7438. let noTiming =
  7439. arguments.length > 1 && arguments[1] !== undefined
  7440. ? arguments[1]
  7441. : true;
  7442. if (typeof selector !== "string") {
  7443. throw new Error("Selector should be defined as a string.");
  7444. }
  7445. const start = performance.now();
  7446. try {
  7447. return extCssDocument.querySelectorAll(selector);
  7448. } finally {
  7449. const end = performance.now();
  7450. if (!noTiming) {
  7451. logger.info(
  7452. `[ExtendedCss] Elapsed: ${Math.round((end - start) * 1000)} μs.`
  7453. );
  7454. }
  7455. }
  7456. }
  7457. /**
  7458. * Validates selector.
  7459. *
  7460. * @param inputSelector Selector text to validate.
  7461. *
  7462. * @returns Result of selector validation.
  7463. */
  7464. static validate(inputSelector) {
  7465. try {
  7466. // ExtendedCss in general supports :remove() in selector
  7467. // but ExtendedCss.query() does not support it as it should be parsed by stylesheet parser.
  7468. // so for validation we have to handle selectors with `:remove()` in it
  7469. const { selector } = parseRemoveSelector(inputSelector);
  7470. ExtendedCss.query(selector);
  7471. return {
  7472. ok: true,
  7473. error: null,
  7474. };
  7475. } catch (e) {
  7476. // not valid input `selector` should be logged eventually
  7477. const error = `Error: Invalid selector: '${inputSelector}' -- ${getErrorMessage(
  7478. e
  7479. )}`;
  7480. return {
  7481. ok: false,
  7482. error,
  7483. };
  7484. }
  7485. }
  7486. }
  7487. function parseBRules() {
  7488. var _a;
  7489. return __awaiter(this, void 0, void 0, function* () {
  7490. data.appliedLevel = 0;
  7491. const brules =
  7492. (_a = yield values.brules()) !== null && _a !== void 0
  7493. ? _a
  7494. : defaultValues.brules;
  7495. brules.forEach((br) => {
  7496. const level = bRuleParser(br);
  7497. if (level > 0) data.bRules.push(br);
  7498. if (level > data.appliedLevel) data.appliedLevel = level;
  7499. });
  7500. });
  7501. }
  7502. function canApplyCss(type) {
  7503. return (data.appliedLevel & (type >= 2 ? 2 : 1)) == 0;
  7504. }
  7505. function cleanRules() {
  7506. if (
  7507. confirm(`是否清空存储规则 ?
  7508.  
  7509. 如果要卸载脚本,点击 确定 以后不要刷新,也不要打开任何新页面,
  7510. (如果可以)清空脚本存储(全选,删除,填 {},保存),然后删除脚本`)
  7511. ) {
  7512. values.rules(null);
  7513. values.time(null);
  7514. values.etags(null);
  7515. values.brules(null);
  7516. getSavedHosts().then((saves) =>
  7517. saves.forEach((host) => values.css(null, host))
  7518. );
  7519. data.isClean = true;
  7520. gmMenu("update");
  7521. gmMenu("export");
  7522. gmMenu("count", () => location.reload());
  7523. }
  7524. }
  7525. function reportRecord() {
  7526. let text = "";
  7527. function pushRecord(css) {
  7528. const match = cssToAbp(css);
  7529. if (match === null) return;
  7530. const [item, type, sel] = match,
  7531. count =
  7532. type % 2 === 1
  7533. ? ExtendedCss.query(sel).length
  7534. : document.querySelectorAll(sel).length;
  7535. if (count > 0) {
  7536. text += `
  7537. ! 匹配元素数量: ${count}
  7538. ${item}
  7539. `;
  7540. }
  7541. }
  7542. data.bRules.forEach((br) => {
  7543. if (br.level > 0) {
  7544. text += `
  7545. ! 禁用${["", "通用", "特定", "所有"][br.level]}元素隐藏
  7546. ${br.rule}
  7547. `;
  7548. }
  7549. });
  7550. styleBoxes.forEach((box, i) => {
  7551. if (canApplyCss(i)) {
  7552. data[box]
  7553. .split("\n")
  7554. .filter((css, i, csss) => csss.indexOf(css) === i)
  7555. .forEach((css) => pushRecord(css));
  7556. }
  7557. });
  7558. const blobUrl = URL.createObjectURL(
  7559. new Blob([
  7560. `[Adblock Plus 2.0]
  7561. ! 应用地址:
  7562. ! ${location.href}
  7563. ${text}`,
  7564. ])
  7565. );
  7566. if (text.length > 0) {
  7567. downUrl(blobUrl, `拦截报告_${location.hostname}.txt`);
  7568. } else {
  7569. alert("这个页面没有任何规则生效");
  7570. }
  7571. }
  7572. function switchDisabledStat() {
  7573. values.black().then((disaList) => {
  7574. const disas = disaList !== null && disaList !== void 0 ? disaList : [];
  7575. data.disabled = !disas.includes(location.hostname);
  7576. if (data.disabled) {
  7577. disas.push(location.hostname);
  7578. } else {
  7579. disas.splice(disas.indexOf(location.hostname), 1);
  7580. }
  7581. values.black(disas).finally(() => location.reload());
  7582. });
  7583. }
  7584. function getCustomHash(saveHash) {
  7585. var _a;
  7586. return __awaiter(this, void 0, void 0, function* () {
  7587. {
  7588. if (location.protocol === "https:") {
  7589. const hash = new Uint32Array(
  7590. yield window.crypto.subtle.digest(
  7591. "SHA-1",
  7592. yield new Blob([data.customRules]).arrayBuffer()
  7593. )
  7594. ).toString();
  7595. if (saveHash) yield values.hash(hash);
  7596. return hash;
  7597. } else {
  7598. return (_a = yield values.hash()) !== null && _a !== void 0
  7599. ? _a
  7600. : defaultValues.hash;
  7601. }
  7602. }
  7603. });
  7604. }
  7605. function initRules(apply) {
  7606. var _a;
  7607. return __awaiter(this, void 0, void 0, function* () {
  7608. let abpRules = {};
  7609. data.receivedRules = "";
  7610. abpRules =
  7611. (_a = yield values.rules()) !== null && _a !== void 0
  7612. ? _a
  7613. : defaultValues.rules;
  7614. {
  7615. yield Promise.all(
  7616. preset.onlineRules.map((rule) =>
  7617. __awaiter(this, void 0, void 0, function* () {
  7618. const resRule = yield getRuleFromResource(rule.标识);
  7619. if (resRule && !abpRules[rule.标识])
  7620. abpRules[rule.标识] = resRule;
  7621. })
  7622. )
  7623. );
  7624. }
  7625. Object.keys(abpRules).forEach((name) => {
  7626. data.receivedRules += "\n" + abpRules[name];
  7627. });
  7628. data.allRules = data.customRules + data.receivedRules;
  7629. if (apply) yield splitRules();
  7630. });
  7631. }
  7632. function styleApplyExec(type) {
  7633. const csss = data[styleBoxes[type]];
  7634. if (csss !== "") {
  7635. new ExtendedCss({
  7636. styleSheet: csss.replace(CMRE, "").replaceAll("\n", ""),
  7637. }).apply();
  7638. if (!(type % 2 == 1)) addStyle(csss);
  7639. }
  7640. }
  7641. function styleApply() {
  7642. return __awaiter(this, void 0, void 0, function* () {
  7643. {
  7644. yield parseBRules();
  7645. if (data.appliedLevel == 3) return;
  7646. }
  7647. for (let type = 0; type < 4; type++)
  7648. if (canApplyCss(type)) styleApplyExec(type);
  7649. gmMenu("export", reportRecord);
  7650. });
  7651. }
  7652. function parseRules() {
  7653. return __awaiter(this, void 0, void 0, function* () {
  7654. function addRule(rule, box) {
  7655. const [full, selector, isStyle] = ruleToCss(rule, data.preset, false);
  7656. const index = (box % 2) + (rule.generic ? 0 : 2);
  7657. const checkResult = ExtendedCss.validate(selector);
  7658. const typeError = isStyle && rule.type < 2;
  7659. if (checkResult.ok && !typeError) {
  7660. data[styleBoxes[index]] += full;
  7661. data.appliedCount++;
  7662. } else {
  7663. console.error(
  7664. "选择器检查错误:",
  7665. rule,
  7666. typeError || checkResult.error
  7667. );
  7668. }
  7669. }
  7670. styleBoxes.forEach((box) => {
  7671. data[box] = "";
  7672. });
  7673. data.appliedCount = 0;
  7674. [
  7675. data.styles,
  7676. data.extStyles,
  7677. data.selectors,
  7678. data.extSelectors,
  7679. ].forEach((r, t) => {
  7680. const sels = new Set();
  7681. r.white.forEach((obj) => !sels.has(obj.sel) && sels.add(obj.sel));
  7682. r.black
  7683. .filter((obj) => !sels.has(obj.sel) && sels.add(obj.sel))
  7684. .forEach((s) => addRule(s, t));
  7685. });
  7686. styleBoxes.forEach((box) => {
  7687. if (data[box] !== "")
  7688. data[box] +=
  7689. "html > head:valid " +
  7690. data.preset.replace(/^\s{2,}/g, " ").replaceAll("\n", "");
  7691. });
  7692. yield gmMenu("count", cleanRules);
  7693. saveCss();
  7694. if (!data.saved) styleApply();
  7695. });
  7696. }
  7697. function splitRules() {
  7698. const bRuleSet = new Set(),
  7699. bRuleBad = [],
  7700. sels = new Set();
  7701. dataBoxes.forEach((box) => {
  7702. data[box] = makeRuleBox();
  7703. });
  7704. data.allRules.split("\n").forEach((rule) => {
  7705. if (isBasicRule(rule)) {
  7706. const brule = bRuleSpliter(rule);
  7707. if (brule) {
  7708. if (brule[1]) {
  7709. bRuleBad.push(brule[0]);
  7710. } else {
  7711. bRuleSet.add(brule[0]);
  7712. }
  7713. }
  7714. } else {
  7715. const ruleObj = ruleLoader(rule);
  7716. if (typeof ruleObj !== "undefined") {
  7717. if (ruleObj.black === "black" && sels.has(ruleObj.sel)) return;
  7718. if (ruleObj.black === "white" && !sels.has(ruleObj.sel))
  7719. sels.add(ruleObj.sel);
  7720. data[dataBoxes[ruleObj.type]][ruleObj.black].push(ruleObj);
  7721. }
  7722. }
  7723. });
  7724. {
  7725. const bRules = [];
  7726. bRuleBad.forEach((brule) => bRuleSet.delete(brule));
  7727. bRuleSet.forEach((brule) => bRules.push(brule));
  7728. values.brules(bRules);
  7729. }
  7730. return parseRules();
  7731. }
  7732. function makeInitMenu() {
  7733. return __awaiter(this, void 0, void 0, function* () {
  7734. yield gmMenu("count", cleanRules);
  7735. {
  7736. yield gmMenu("update", () => {
  7737. performUpdate(true).then(() => {
  7738. location.reload();
  7739. });
  7740. });
  7741. }
  7742. });
  7743. }
  7744. function extrEtag(resp) {
  7745. var _a, _b, _c;
  7746. const etag = getEtag(
  7747. typeof (resp === null || resp === void 0 ? void 0 : resp.headers) ==
  7748. "object"
  7749. ? // 海阔世界
  7750. (_b =
  7751. (_a =
  7752. resp === null || resp === void 0 ? void 0 : resp.headers) ===
  7753. null || _a === void 0
  7754. ? void 0
  7755. : _a.etag) === null || _b === void 0
  7756. ? void 0
  7757. : _b[0]
  7758. : typeof (resp === null || resp === void 0
  7759. ? void 0
  7760. : resp.responseHeaders) == "string"
  7761. ? // Tampermonkey
  7762. resp === null || resp === void 0
  7763. ? void 0
  7764. : resp.responseHeaders
  7765. : // Appara
  7766. (_c =
  7767. resp === null || resp === void 0
  7768. ? void 0
  7769. : resp.getAllResponseHeaders) === null || _c === void 0
  7770. ? void 0
  7771. : _c.call(resp)
  7772. );
  7773. return etag;
  7774. }
  7775. function storeRule(rule, resp) {
  7776. var _a, _c;
  7777. return __awaiter(this, void 0, void 0, function* () {
  7778. let savedRules = {};
  7779. savedRules =
  7780. (_a = yield values.rules()) !== null && _a !== void 0
  7781. ? _a
  7782. : defaultValues.rules;
  7783. if (resp.responseText) {
  7784. let parsed = resp.responseText;
  7785. if (rule.筛选后存储) {
  7786. parsed = resp.responseText
  7787. .split("\n")
  7788. .filter((rule) => CRRE.test(rule) || isBasicRule(rule))
  7789. .join("\n");
  7790. }
  7791. savedRules[rule.标识] = parsed;
  7792. {
  7793. yield values.rules(savedRules);
  7794. if (savedRules[rule.标识].length !== 0) {
  7795. const etag = extrEtag(resp),
  7796. savedEtags =
  7797. (_c = yield values.etags()) !== null && _c !== void 0
  7798. ? _c
  7799. : defaultValues.etags;
  7800. if (etag) {
  7801. savedEtags[rule.标识] = etag;
  7802. yield values.etags(savedEtags);
  7803. }
  7804. }
  7805. }
  7806. data.receivedRules += "\n" + savedRules[rule.标识];
  7807. }
  7808. return;
  7809. });
  7810. }
  7811. function fetchRuleBody(rule) {
  7812. var _a;
  7813. return __awaiter(this, void 0, void 0, function* () {
  7814. const url = addTimeParam(rule.地址);
  7815. const getResp = yield promiseXhr({
  7816. method: "GET",
  7817. responseType: "text",
  7818. url,
  7819. }).catch((error) => {
  7820. console.error("规则: ", url, " 下载错误: ", error);
  7821. });
  7822. if (
  7823. (_a =
  7824. getResp === null || getResp === void 0
  7825. ? void 0
  7826. : getResp.responseText) === null || _a === void 0
  7827. ? void 0
  7828. : _a.length
  7829. ) {
  7830. yield storeRule(rule, getResp);
  7831. return true;
  7832. } else return false;
  7833. });
  7834. }
  7835. function fetchRuleGet(resp, rule) {
  7836. var _a;
  7837. return __awaiter(this, void 0, void 0, function* () {
  7838. const etag = extrEtag(resp),
  7839. savedEtags = yield values.etags();
  7840. if (
  7841. (_a =
  7842. resp === null || resp === void 0 ? void 0 : resp.responseText) ===
  7843. null || _a === void 0
  7844. ? void 0
  7845. : _a.length
  7846. ) {
  7847. yield storeRule(rule, resp);
  7848. if (
  7849. etag !==
  7850. (savedEtags === null || savedEtags === void 0
  7851. ? void 0
  7852. : savedEtags[rule.标识])
  7853. ) {
  7854. return;
  7855. } else {
  7856. return Promise.reject("ETag 一致");
  7857. }
  7858. } else {
  7859. if (
  7860. etag !==
  7861. (savedEtags === null || savedEtags === void 0
  7862. ? void 0
  7863. : savedEtags[rule.标识])
  7864. ) {
  7865. if (yield fetchRuleBody(rule)) {
  7866. return;
  7867. } else {
  7868. return Promise.reject("GET 失败");
  7869. }
  7870. } else return Promise.reject("ETag 一致");
  7871. }
  7872. });
  7873. }
  7874. function fetchRule(rule) {
  7875. var _a;
  7876. return __awaiter(this, void 0, void 0, function* () {
  7877. let headRespError = {};
  7878. const url = addTimeParam(rule.地址);
  7879. const headResp = yield promiseXhr({
  7880. method: "HEAD",
  7881. responseType: "text",
  7882. url,
  7883. }).catch((error) => {
  7884. headRespError = error;
  7885. console.error("规则: ", url, " HEAD 错误: ", error);
  7886. });
  7887. if (!headResp) {
  7888. // Via HEAD 会超时,但可以得到 ETag
  7889. if (
  7890. (_a =
  7891. headRespError === null || headRespError === void 0
  7892. ? void 0
  7893. : headRespError.resp) === null || _a === void 0
  7894. ? void 0
  7895. : _a.responseHeaders
  7896. ) {
  7897. return yield fetchRuleGet(headRespError.resp, rule);
  7898. } else {
  7899. return Promise.reject("HEAD 失败");
  7900. }
  7901. } else {
  7902. return yield fetchRuleGet(headResp, rule);
  7903. }
  7904. });
  7905. }
  7906. function fetchRules() {
  7907. return __awaiter(this, void 0, void 0, function* () {
  7908. let hasUpdate = preset.onlineRules.length;
  7909. data.updating = true;
  7910. yield gmMenu("update", () => void 0);
  7911. for (const rule of preset.onlineRules) {
  7912. if (rule.在线更新) {
  7913. yield fetchRule(rule).catch((error) => {
  7914. console.error("获取规则 ", rule, " 发生错误: ", error);
  7915. hasUpdate--;
  7916. });
  7917. } else {
  7918. hasUpdate--;
  7919. }
  7920. }
  7921. values.time(new Date().toLocaleString("zh-CN"));
  7922. data.updating = false;
  7923. yield makeInitMenu();
  7924. if (hasUpdate > 0) {
  7925. yield Promise.all(
  7926. (yield getSavedHosts()).map((host) =>
  7927. __awaiter(this, void 0, void 0, function* () {
  7928. if (host === location.hostname) {
  7929. initRules(true);
  7930. } else {
  7931. const save = yield values.css(void 0, host);
  7932. if (save) {
  7933. save.needUpdate = true;
  7934. yield values.css(save, host);
  7935. }
  7936. }
  7937. })
  7938. )
  7939. );
  7940. }
  7941. });
  7942. }
  7943. function performUpdate(force) {
  7944. var _b;
  7945. return __awaiter(this, void 0, void 0, function* () {
  7946. if (data.isFrame) return Promise.reject();
  7947. return force ||
  7948. new Date(
  7949. (_b = yield values.time()) !== null && _b !== void 0
  7950. ? _b
  7951. : defaultValues.time
  7952. ).getDate() !== new Date().getDate()
  7953. ? fetchRules()
  7954. : Promise.resolve();
  7955. });
  7956. }
  7957. function main() {
  7958. var _a, _b;
  7959. return __awaiter(this, void 0, void 0, function* () {
  7960. if (!location.protocol.startsWith("http")) return;
  7961. // 初始化 data
  7962. data.disabled =
  7963. (_b =
  7964. (_a = yield values.black()) === null || _a === void 0
  7965. ? void 0
  7966. : _a.includes(location.hostname)) !== null && _b !== void 0
  7967. ? _b
  7968. : false;
  7969. data.preset = yield getUserConfig("css");
  7970. data.timeout = yield getUserConfig("timeout");
  7971. data.tryCount = yield getUserConfig("tryCount");
  7972. data.tryTimeout = yield getUserConfig("tryTimeout");
  7973. data.headTimeout = yield getUserConfig("headTimeout");
  7974. let finish = false;
  7975. gmMenu("disable", switchDisabledStat);
  7976. if (data.disabled) {
  7977. gmMenu("count", cleanRules);
  7978. return;
  7979. }
  7980. if (yield getSavedHosts(location.hostname)) yield readCss();
  7981. const hash = yield getCustomHash(false);
  7982. saved: {
  7983. yield makeInitMenu();
  7984. if ((yield values.hash()) !== hash) {
  7985. yield getCustomHash(true);
  7986. yield initRules(true);
  7987. break saved;
  7988. }
  7989. if (data.saved) {
  7990. styleApply();
  7991. if (!data.update) break saved;
  7992. }
  7993. yield initRules(false);
  7994. if (data.receivedRules.length === 0) {
  7995. yield performUpdate(true);
  7996. yield gmMenu("count");
  7997. yield initRules(true);
  7998. finish = true;
  7999. } else yield splitRules();
  8000. }
  8001. if (!finish) {
  8002. try {
  8003. yield performUpdate(false);
  8004. } catch (_error) {
  8005. console.warn("iframe: ", location.href, " 取消更新");
  8006. }
  8007. }
  8008. });
  8009. }
  8010. {
  8011. runOnce(data.mutex, main);
  8012. }
  8013. })($presets, $polyfills);
  8014. })();