run-against-source-file.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. let l: string | null = '';
  12. for await (const line of readFileByLine(filePath)) {
  13. l = processLine(line);
  14. if (!l) {
  15. continue;
  16. }
  17. if (type == null) {
  18. if (l.includes(',')) {
  19. type = 'ruleset';
  20. } else {
  21. type = 'domainset';
  22. }
  23. }
  24. if (type === 'ruleset') {
  25. const [ruleType, domain] = l.split(',', 3);
  26. switch (ruleType) {
  27. case 'DOMAIN': {
  28. callback(domain, false);
  29. break;
  30. }
  31. case 'DOMAIN-SUFFIX': {
  32. callback(domain, true);
  33. break;
  34. }
  35. case 'DOMAIN-KEYWORD': {
  36. if (keywordSet) {
  37. keywordSet.add(domain);
  38. }
  39. break;
  40. }
  41. // no default
  42. }
  43. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- exhaus options
  44. } else if (type === 'domainset') {
  45. if (l[0] === '.') {
  46. callback(l.slice(1), true);
  47. } else {
  48. callback(l, false);
  49. }
  50. } else {
  51. never(type);
  52. }
  53. }
  54. }