parse-filter.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. // @ts-check
  2. import { fetchRemoteTextByLine } from './fetch-text-by-line';
  3. import { NetworkFilter } from '@cliqz/adblocker';
  4. import { processLine } from './process-line';
  5. import { getGorhillPublicSuffixPromise } from './get-gorhill-publicsuffix';
  6. import type { PublicSuffixList } from '@gorhill/publicsuffixlist';
  7. import picocolors from 'picocolors';
  8. import { normalizeDomain } from './normalize-domain';
  9. import { fetchAssets } from './fetch-assets';
  10. import { deserializeSet, fsFetchCache, serializeSet } from './cache-filesystem';
  11. import type { Span } from '../trace';
  12. const DEBUG_DOMAIN_TO_FIND: string | null = null; // example.com | null
  13. let foundDebugDomain = false;
  14. export function processDomainLists(span: Span, domainListsUrl: string, includeAllSubDomain = false, ttl: number | null = null) {
  15. return span.traceChild(`process domainlist: ${domainListsUrl}`).traceAsyncFn(() => fsFetchCache.apply(
  16. domainListsUrl,
  17. async () => {
  18. const domainSets = new Set<string>();
  19. for await (const line of await fetchRemoteTextByLine(domainListsUrl)) {
  20. let domainToAdd = processLine(line);
  21. if (!domainToAdd) continue;
  22. domainToAdd = normalizeDomain(domainToAdd);
  23. if (!domainToAdd) continue;
  24. if (DEBUG_DOMAIN_TO_FIND && domainToAdd.includes(DEBUG_DOMAIN_TO_FIND)) {
  25. console.warn(picocolors.red(domainListsUrl), '(black)', domainToAdd.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND)));
  26. foundDebugDomain = true;
  27. }
  28. domainSets.add(includeAllSubDomain ? `.${domainToAdd}` : domainToAdd);
  29. }
  30. return domainSets;
  31. },
  32. {
  33. ttl,
  34. temporaryBypass: DEBUG_DOMAIN_TO_FIND !== null,
  35. serializer: serializeSet,
  36. deserializer: deserializeSet
  37. }
  38. ));
  39. }
  40. export function processHosts(span: Span, hostsUrl: string, mirrors: string[] | null, includeAllSubDomain = false, ttl: number | null = null) {
  41. return span.traceChild(`processhosts: ${hostsUrl}`).traceAsyncFn((childSpan) => fsFetchCache.apply(
  42. hostsUrl,
  43. async () => {
  44. const domainSets = new Set<string>();
  45. const lineCb = (l: string) => {
  46. const line = processLine(l);
  47. if (!line) {
  48. return;
  49. }
  50. const _domain = line.split(/\s/)[1]?.trim();
  51. if (!_domain) {
  52. return;
  53. }
  54. const domain = normalizeDomain(_domain);
  55. if (!domain) {
  56. return;
  57. }
  58. if (DEBUG_DOMAIN_TO_FIND && domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  59. console.warn(picocolors.red(hostsUrl), '(black)', domain.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND)));
  60. foundDebugDomain = true;
  61. }
  62. domainSets.add(includeAllSubDomain ? `.${domain}` : domain);
  63. };
  64. if (mirrors == null || mirrors.length === 0) {
  65. for await (const l of await fetchRemoteTextByLine(hostsUrl)) {
  66. lineCb(l);
  67. }
  68. } else {
  69. // Avoid event loop starvation, so we wait for a macrotask before we start fetching.
  70. await Promise.resolve();
  71. const filterRules = await childSpan
  72. .traceChild('download hosts')
  73. .traceAsyncFn(() => fetchAssets(hostsUrl, mirrors).then(text => text.split('\n')));
  74. childSpan.traceChild('parse hosts').traceSyncFn(() => {
  75. for (let i = 0, len = filterRules.length; i < len; i++) {
  76. lineCb(filterRules[i]);
  77. }
  78. });
  79. }
  80. console.log(picocolors.gray('[process hosts]'), picocolors.gray(hostsUrl), picocolors.gray(domainSets.size));
  81. return domainSets;
  82. },
  83. {
  84. ttl,
  85. temporaryBypass: DEBUG_DOMAIN_TO_FIND !== null,
  86. serializer: serializeSet,
  87. deserializer: deserializeSet
  88. }
  89. ));
  90. }
  91. // eslint-disable-next-line sukka-ts/no-const-enum -- bun bundler is smart, maybe?
  92. const enum ParseType {
  93. WhiteIncludeSubdomain = 0,
  94. WhiteAbsolute = -1,
  95. BlackAbsolute = 1,
  96. BlackIncludeSubdomain = 2,
  97. ErrorMessage = 10
  98. }
  99. export async function processFilterRules(
  100. parentSpan: Span,
  101. filterRulesUrl: string,
  102. fallbackUrls?: readonly string[] | undefined | null,
  103. ttl: number | null = null
  104. ): Promise<{ white: string[], black: string[], foundDebugDomain: boolean }> {
  105. const [white, black, warningMessages] = await parentSpan.traceChild(`process filter rules: ${filterRulesUrl}`).traceAsyncFn((span) => fsFetchCache.apply<Readonly<[
  106. white: string[],
  107. black: string[],
  108. warningMessages: string[]
  109. ]>>(
  110. filterRulesUrl,
  111. async () => {
  112. const whitelistDomainSets = new Set<string>();
  113. const blacklistDomainSets = new Set<string>();
  114. const warningMessages: string[] = [];
  115. const gorhill = await getGorhillPublicSuffixPromise();
  116. /**
  117. * @param {string} line
  118. */
  119. const lineCb = (line: string) => {
  120. const result = parse(line, gorhill);
  121. if (!result) {
  122. return;
  123. }
  124. const flag = result[1];
  125. const hostname = result[0];
  126. if (DEBUG_DOMAIN_TO_FIND) {
  127. if (hostname.includes(DEBUG_DOMAIN_TO_FIND)) {
  128. console.warn(
  129. picocolors.red(filterRulesUrl),
  130. flag === ParseType.WhiteIncludeSubdomain || flag === ParseType.WhiteAbsolute
  131. ? '(white)'
  132. : '(black)',
  133. hostname.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND))
  134. );
  135. foundDebugDomain = true;
  136. }
  137. }
  138. switch (flag) {
  139. case ParseType.WhiteIncludeSubdomain:
  140. if (hostname[0] !== '.') {
  141. whitelistDomainSets.add(`.${hostname}`);
  142. } else {
  143. whitelistDomainSets.add(hostname);
  144. }
  145. break;
  146. case ParseType.WhiteAbsolute:
  147. whitelistDomainSets.add(hostname);
  148. break;
  149. case ParseType.BlackAbsolute:
  150. blacklistDomainSets.add(hostname);
  151. break;
  152. case ParseType.BlackIncludeSubdomain:
  153. if (hostname[0] !== '.') {
  154. blacklistDomainSets.add(`.${hostname}`);
  155. } else {
  156. blacklistDomainSets.add(hostname);
  157. }
  158. break;
  159. case ParseType.ErrorMessage:
  160. warningMessages.push(hostname);
  161. break;
  162. default:
  163. break;
  164. }
  165. };
  166. if (!fallbackUrls || fallbackUrls.length === 0) {
  167. for await (const line of await fetchRemoteTextByLine(filterRulesUrl)) {
  168. // don't trim here
  169. lineCb(line);
  170. }
  171. } else {
  172. // Avoid event loop starvation, so we wait for a macrotask before we start fetching.
  173. await Promise.resolve();
  174. const filterRules = await span.traceChild('download adguard filter').traceAsyncFn(() => {
  175. return fetchAssets(filterRulesUrl, fallbackUrls).then(text => text.split('\n'));
  176. });
  177. span.traceChild('parse adguard filter').traceSyncFn(() => {
  178. for (let i = 0, len = filterRules.length; i < len; i++) {
  179. lineCb(filterRules[i]);
  180. }
  181. });
  182. }
  183. return [
  184. Array.from(whitelistDomainSets),
  185. Array.from(blacklistDomainSets),
  186. warningMessages
  187. ] as const;
  188. },
  189. {
  190. ttl,
  191. temporaryBypass: DEBUG_DOMAIN_TO_FIND !== null,
  192. serializer: JSON.stringify,
  193. deserializer: JSON.parse
  194. }
  195. ));
  196. for (let i = 0, len = warningMessages.length; i < len; i++) {
  197. console.warn(
  198. picocolors.yellow(warningMessages[i]),
  199. picocolors.gray(picocolors.underline(filterRulesUrl))
  200. );
  201. }
  202. console.log(
  203. picocolors.gray('[process filter]'),
  204. picocolors.gray(filterRulesUrl),
  205. picocolors.gray(`white: ${white.length}`),
  206. picocolors.gray(`black: ${black.length}`)
  207. );
  208. return {
  209. white,
  210. black,
  211. foundDebugDomain
  212. };
  213. }
  214. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN = /[#%&=~]/;
  215. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2 = /(\$popup|\$removeparam|\$popunder|\$cname)/;
  216. // cname exceptional filter can not be parsed by NetworkFilter
  217. // Surge / Clash can't handle CNAME either, so we just ignore them
  218. function parse($line: string, gorhill: PublicSuffixList): null | [hostname: string, flag: ParseType] {
  219. if (
  220. // doesn't include
  221. !$line.includes('.') // rule with out dot can not be a domain
  222. // includes
  223. || $line.includes('!')
  224. || $line.includes('?')
  225. || $line.includes('*')
  226. || $line.includes('[')
  227. || $line.includes('(')
  228. || $line.includes(']')
  229. || $line.includes(')')
  230. || $line.includes(',')
  231. || R_KNOWN_NOT_NETWORK_FILTER_PATTERN.test($line)
  232. ) {
  233. return null;
  234. }
  235. const line = $line.trim();
  236. /** @example line.length */
  237. const len = line.length;
  238. if (len === 0) {
  239. return null;
  240. }
  241. const firstCharCode = line[0].charCodeAt(0);
  242. const lastCharCode = line[len - 1].charCodeAt(0);
  243. if (
  244. firstCharCode === 47 // 47 `/`
  245. // ends with
  246. || lastCharCode === 46 // 46 `.`, line.endsWith('.')
  247. || lastCharCode === 45 // 45 `-`, line.endsWith('-')
  248. || lastCharCode === 95 // 95 `_`, line.endsWith('_')
  249. // special modifier
  250. || R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2.test(line)
  251. // || line.includes('$popup')
  252. // || line.includes('$removeparam')
  253. // || line.includes('$popunder')
  254. ) {
  255. return null;
  256. }
  257. if ((line.includes('/') || line.includes(':')) && !line.includes('://')) {
  258. return null;
  259. }
  260. const filter = NetworkFilter.parse(line);
  261. if (filter) {
  262. if (
  263. // filter.isCosmeticFilter() // always false
  264. // filter.isNetworkFilter() // always true
  265. filter.isElemHide()
  266. || filter.isGenericHide()
  267. || filter.isSpecificHide()
  268. || filter.isRedirect()
  269. || filter.isRedirectRule()
  270. || filter.hasDomains()
  271. || filter.isCSP() // must not be csp rule
  272. || (!filter.fromAny() && !filter.fromDocument())
  273. ) {
  274. // not supported type
  275. return null;
  276. }
  277. if (
  278. filter.hostname // filter.hasHostname() // must have
  279. && filter.isPlain() // isPlain() === !isRegex()
  280. && (!filter.isFullRegex())
  281. ) {
  282. const hostname = normalizeDomain(filter.hostname);
  283. if (!hostname) {
  284. return null;
  285. }
  286. // |: filter.isHostnameAnchor(),
  287. // |: filter.isLeftAnchor(),
  288. // |https://: !filter.isHostnameAnchor() && (filter.fromHttps() || filter.fromHttp())
  289. const isIncludeAllSubDomain = filter.isHostnameAnchor();
  290. if (filter.isException() || filter.isBadFilter()) {
  291. return [hostname, isIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute];
  292. }
  293. const _1p = filter.firstParty();
  294. const _3p = filter.thirdParty();
  295. if (_1p) {
  296. if (_1p === _3p) {
  297. return [hostname, isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute];
  298. }
  299. return null;
  300. }
  301. if (_3p) {
  302. return null;
  303. }
  304. }
  305. }
  306. // After NetworkFilter.parse, it means the line can not be parsed by cliqz NetworkFilter
  307. // We now need to "salvage" the line as much as possible
  308. /*
  309. * From now on, we are mostly facing non-standard domain rules (some are regex like)
  310. * We first skip third-party and frame rules, as Surge / Clash can't handle them
  311. *
  312. * `.sharecounter.$third-party`
  313. * `.bbelements.com^$third-party`
  314. * `://o0e.ru^$third-party`
  315. * `.1.1.1.l80.js^$third-party`
  316. */
  317. if (line.includes('$third-party') || line.includes('$frame')) {
  318. return null;
  319. }
  320. /** @example line.endsWith('^') */
  321. const lineEndsWithCaret = lastCharCode === 94; // lastChar === '^';
  322. /** @example line.endsWith('^|') */
  323. const lineEndsWithCaretVerticalBar = (lastCharCode === 124 /** lastChar === '|' */) && line[len - 2] === '^';
  324. /** @example line.endsWith('^') || line.endsWith('^|') */
  325. const lineEndsWithCaretOrCaretVerticalBar = lineEndsWithCaret || lineEndsWithCaretVerticalBar;
  326. // whitelist (exception)
  327. if (
  328. firstCharCode === 64 // 64 `@`
  329. && line[1] === '@'
  330. ) {
  331. let whiteIncludeAllSubDomain = true;
  332. /**
  333. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  334. * "$genericblock`" is also not supported by NetworkFilter, see:
  335. * https://github.com/ghostery/adblocker/blob/62caf7786ba10ef03beffecd8cd4eec111bcd5ec/packages/adblocker/test/parsing.test.ts#L950
  336. *
  337. * `@@||cmechina.net^$genericblock`
  338. * `@@|ftp.bmp.ovh^|`
  339. * `@@|adsterra.com^|`
  340. * `@@.atlassian.net$document`
  341. * `@@||ad.alimama.com^$genericblock`
  342. */
  343. let sliceStart = 0;
  344. let sliceEnd: number | undefined;
  345. if (line[2] === '|') { // line.startsWith('@@|')
  346. sliceStart = 3;
  347. whiteIncludeAllSubDomain = false;
  348. if (line[3] === '|') { // line.startsWith('@@||')
  349. sliceStart = 4;
  350. whiteIncludeAllSubDomain = true;
  351. }
  352. } else if (line[2] === '.') { // line.startsWith('@@.')
  353. sliceStart = 3;
  354. whiteIncludeAllSubDomain = true;
  355. } else if (
  356. /**
  357. * line.startsWith('@@://')
  358. *
  359. * `@@://googleadservices.com^|`
  360. * `@@://www.googleadservices.com^|`
  361. */
  362. line[2] === ':' && line[3] === '/' && line[4] === '/'
  363. ) {
  364. whiteIncludeAllSubDomain = false;
  365. sliceStart = 5;
  366. }
  367. if (lineEndsWithCaretOrCaretVerticalBar) {
  368. sliceEnd = -2;
  369. } else if (line.endsWith('$genericblock')) {
  370. sliceEnd = -13;
  371. if (line[len - 14] === '^') { // line.endsWith('^$genericblock')
  372. sliceEnd = -14;
  373. }
  374. } else if (line.endsWith('$document')) {
  375. sliceEnd = -9;
  376. if (line[len - 10] === '^') { // line.endsWith('^$document')
  377. sliceEnd = -10;
  378. }
  379. }
  380. if (sliceStart !== 0 || sliceEnd !== undefined) {
  381. const sliced = line.slice(sliceStart, sliceEnd);
  382. const domain = normalizeDomain(sliced);
  383. if (domain) {
  384. return [domain, whiteIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute];
  385. }
  386. return [
  387. `[parse-filter E0001] (white) invalid domain: ${JSON.stringify({
  388. line, sliced, sliceStart, sliceEnd
  389. })}`,
  390. ParseType.ErrorMessage
  391. ];
  392. }
  393. return [
  394. `[parse-filter E0006] (white) failed to parse: ${JSON.stringify({
  395. line, sliceStart, sliceEnd
  396. })}`,
  397. ParseType.ErrorMessage
  398. ];
  399. }
  400. if (
  401. // 124 `|`
  402. // line.startsWith('|')
  403. firstCharCode === 124
  404. && lineEndsWithCaretOrCaretVerticalBar
  405. ) {
  406. /**
  407. * Some malformed filters can not be parsed by NetworkFilter:
  408. *
  409. * `||smetrics.teambeachbody.com^.com^`
  410. * `||solutions.|pages.indigovision.com^`
  411. * `||vystar..0rg@client.iebetanialaargentina.edu.co^`
  412. * `app-uat.latrobehealth.com.au^predirect.snapdeal.com`
  413. */
  414. const includeAllSubDomain = line[1] === '|';
  415. const sliceStart = includeAllSubDomain ? 2 : 1;
  416. const sliceEnd = lineEndsWithCaret
  417. ? -1
  418. : (lineEndsWithCaretVerticalBar ? -2 : undefined);
  419. const sliced = line.slice(sliceStart, sliceEnd); // we already make sure line startsWith "|"
  420. const domain = normalizeDomain(sliced);
  421. if (domain) {
  422. return [domain, includeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute];
  423. }
  424. return [
  425. `[parse-filter E0002] (black) invalid domain: ${sliced}`,
  426. ParseType.ErrorMessage
  427. ];
  428. }
  429. const lineStartsWithSingleDot = firstCharCode === 46; // 46 `.`
  430. if (
  431. lineStartsWithSingleDot
  432. && lineEndsWithCaretOrCaretVerticalBar
  433. ) {
  434. /**
  435. * `.ay.delivery^`
  436. * `.m.bookben.com^`
  437. * `.wap.x4399.com^`
  438. */
  439. const sliced = line.slice(
  440. 1, // remove prefix dot
  441. lineEndsWithCaret // replaceAll('^', '')
  442. ? -1
  443. : (lineEndsWithCaretVerticalBar ? -2 : undefined) // replace('^|', '')
  444. );
  445. const suffix = gorhill.getPublicSuffix(sliced);
  446. if (!gorhill.suffixInPSL(suffix)) {
  447. // This exclude domain-like resource like `1.1.4.514.js`
  448. return null;
  449. }
  450. const domain = normalizeDomain(sliced);
  451. if (domain) {
  452. return [domain, ParseType.BlackIncludeSubdomain];
  453. }
  454. return [
  455. `[paparse-filter E0003] (black) invalid domain: ${sliced}`,
  456. ParseType.ErrorMessage
  457. ];
  458. }
  459. /**
  460. * `|http://x.o2.pl^`
  461. * `://mine.torrent.pw^`
  462. * `://say.ac^`
  463. */
  464. if (lineEndsWithCaretOrCaretVerticalBar) {
  465. let sliceStart = 0;
  466. let sliceEnd;
  467. if (lineEndsWithCaret) { // line.endsWith('^')
  468. sliceEnd = -1;
  469. } else if (lineEndsWithCaretVerticalBar) { // line.endsWith('^|')
  470. sliceEnd = -2;
  471. }
  472. if (line.startsWith('://')) {
  473. sliceStart = 3;
  474. } else if (line.startsWith('http://')) {
  475. sliceStart = 7;
  476. } else if (line.startsWith('https://')) {
  477. sliceStart = 8;
  478. } else if (line.startsWith('|http://')) {
  479. sliceStart = 8;
  480. } else if (line.startsWith('|https://')) {
  481. sliceStart = 9;
  482. }
  483. if (sliceStart !== 0 || sliceEnd !== undefined) {
  484. const sliced = line.slice(sliceStart, sliceEnd);
  485. const domain = normalizeDomain(sliced);
  486. if (domain) {
  487. return [domain, ParseType.BlackIncludeSubdomain];
  488. }
  489. return [
  490. `[parse-filter E0004] (black) invalid domain: ${JSON.stringify({
  491. line, sliced, sliceStart, sliceEnd
  492. })}`,
  493. ParseType.ErrorMessage
  494. ];
  495. }
  496. }
  497. /**
  498. * `_vmind.qqvideo.tc.qq.com^`
  499. * `arketing.indianadunes.com^`
  500. * `charlestownwyllie.oaklawnnonantum.com^`
  501. * `-telemetry.officeapps.live.com^`
  502. * `-tracker.biliapi.net`
  503. * `-logging.nextmedia.com`
  504. * `_social_tracking.js^`
  505. */
  506. if (
  507. firstCharCode !== 124 // 124 `|`
  508. && lastCharCode === 94 // 94 `^`
  509. ) {
  510. const _domain = line.slice(0, -1);
  511. const suffix = gorhill.getPublicSuffix(_domain);
  512. if (!suffix || !gorhill.suffixInPSL(suffix)) {
  513. // This exclude domain-like resource like `_social_tracking.js^`
  514. return null;
  515. }
  516. const domain = normalizeDomain(_domain);
  517. if (domain) {
  518. return [domain, ParseType.BlackAbsolute];
  519. }
  520. return [
  521. `[parse-filter E0005] (black) invalid domain: ${_domain}`,
  522. ParseType.ErrorMessage
  523. ];
  524. }
  525. // Possibly that entire rule is domain
  526. /**
  527. * lineStartsWithSingleDot:
  528. *
  529. * `.cookielaw.js`
  530. * `.content_tracking.js`
  531. * `.ads.css`
  532. *
  533. * else:
  534. *
  535. * `_prebid.js`
  536. * `t.yesware.com`
  537. * `ubmcmm.baidustatic.com`
  538. * `://www.smfg-card.$document`
  539. * `portal.librus.pl$$advertisement-module`
  540. * `@@-ds.metric.gstatic.com^|`
  541. * `://gom.ge/cookie.js`
  542. * `://accout-update-smba.jp.$document`
  543. * `_200x250.png`
  544. * `@@://www.liquidweb.com/kb/wp-content/themes/lw-kb-theme/images/ads/vps-sidebar.jpg`
  545. */
  546. let sliceStart = 0;
  547. let sliceEnd: number | undefined;
  548. if (lineStartsWithSingleDot) {
  549. sliceStart = 1;
  550. }
  551. if (line.endsWith('^$all')) { // This salvage line `thepiratebay3.com^$all`
  552. sliceEnd = -5;
  553. } else if (
  554. // Try to salvage line like `://account.smba.$document`
  555. // For this specific line, it will fail anyway though.
  556. line.endsWith('$document')
  557. ) {
  558. sliceEnd = -9;
  559. }
  560. const sliced = (sliceStart !== 0 || sliceEnd !== undefined) ? line.slice(sliceStart, sliceEnd) : line;
  561. const suffix = gorhill.getPublicSuffix(sliced);
  562. /**
  563. * Fast exclude definitely not domain-like resource
  564. *
  565. * `.gatracking.js`, suffix is `js`,
  566. * `.ads.css`, suffix is `css`,
  567. * `-cpm-ads.$badfilter`, suffix is `$badfilter`,
  568. * `portal.librus.pl$$advertisement-module`, suffix is `pl$$advertisement-module`
  569. */
  570. if (!suffix || !gorhill.suffixInPSL(suffix)) {
  571. // This exclude domain-like resource like `.gatracking.js`, `.beacon.min.js` and `.cookielaw.js`
  572. return null;
  573. }
  574. const tryNormalizeDomain = normalizeDomain(sliced);
  575. if (tryNormalizeDomain === sliced) {
  576. // the entire rule is domain
  577. return [sliced, ParseType.BlackIncludeSubdomain];
  578. }
  579. return [
  580. `[parse-filter E0010] can not parse: ${line}`,
  581. ParseType.ErrorMessage
  582. ];
  583. }