run-against-source-file.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. const otherPoundSign = l.lastIndexOf('#');
  18. if (otherPoundSign > 0) {
  19. l = l.slice(0, otherPoundSign).trimEnd();
  20. }
  21. if (type == null) {
  22. if (l.includes(',')) {
  23. type = 'ruleset';
  24. } else {
  25. type = 'domainset';
  26. }
  27. }
  28. if (type === 'ruleset') {
  29. const [ruleType, domain] = l.split(',', 3);
  30. switch (ruleType) {
  31. case 'DOMAIN': {
  32. callback(domain, false);
  33. break;
  34. }
  35. case 'DOMAIN-SUFFIX': {
  36. callback(domain, true);
  37. break;
  38. }
  39. case 'DOMAIN-KEYWORD': {
  40. if (keywordSet) {
  41. keywordSet.add(domain);
  42. }
  43. break;
  44. }
  45. // no default
  46. }
  47. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- exhaus options
  48. } else if (type === 'domainset') {
  49. if (l[0] === '.') {
  50. callback(l.slice(1), true);
  51. } else {
  52. callback(l, false);
  53. }
  54. } else {
  55. never(type);
  56. }
  57. }
  58. }