套壳油猴的广告拦截脚本

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

当前为 2024-05-07 提交的版本,查看 最新版本

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