run-against-source-file.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { never } from 'foxts/guard';
  2. import { readFileByLine } from './fetch-text-by-line';
  3. import { processLine } from './process-line';
  4. export default async function runAgainstSourceFile(
  5. filePath: string,
  6. callback: (domain: string, includeAllSubDomain: boolean) => void,
  7. type?: 'ruleset' | 'domainset',
  8. /** Secret keyword collection, only use for special purpose */
  9. keywordSet?: Set<string> | null
  10. ) {
  11. for await (const line of readFileByLine(filePath)) {
  12. const l = processLine(line);
  13. if (!l) {
  14. continue;
  15. }
  16. if (type == null) {
  17. if (l.includes(',')) {
  18. type = 'ruleset';
  19. } else {
  20. type = 'domainset';
  21. }
  22. }
  23. if (type === 'ruleset') {
  24. const [ruleType, domain] = l.split(',', 3);
  25. switch (ruleType) {
  26. case 'DOMAIN': {
  27. callback(domain, false);
  28. break;
  29. }
  30. case 'DOMAIN-SUFFIX': {
  31. callback(domain, true);
  32. break;
  33. }
  34. case 'DOMAIN-KEYWORD': {
  35. if (keywordSet) {
  36. keywordSet.add(domain);
  37. }
  38. break;
  39. }
  40. // no default
  41. }
  42. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- exhaus options
  43. } else if (type === 'domainset') {
  44. if (l[0] === '.') {
  45. callback(l.slice(1), true);
  46. } else {
  47. callback(l, false);
  48. }
  49. } else {
  50. never(type);
  51. }
  52. }
  53. }