build-internal-rules.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // @ts-check
  2. const fs = require('fs');
  3. const fse = require('fs-extra');
  4. const path = require('path');
  5. const readline = require('readline');
  6. const { isDomainLoose } = require('./lib/is-domain-loose');
  7. const tldts = require('tldts');
  8. (async () => {
  9. const set = new Set();
  10. /**
  11. * @param {string} input
  12. */
  13. const addApexDomain = (input) => {
  14. const d = tldts.getDomain(input, { allowPrivateDomains: true });
  15. if (d) {
  16. set.add(d);
  17. }
  18. };
  19. /**
  20. * @param {string} domainSetPath
  21. */
  22. const processLocalDomainSet = async (domainSetPath) => {
  23. for await (
  24. const line of readline.createInterface({
  25. input: fs.createReadStream(domainSetPath),
  26. crlfDelay: Infinity
  27. })
  28. ) {
  29. if (line[0] === '.') {
  30. addApexDomain(line.slice(1));
  31. } else if (isDomainLoose(line)) {
  32. addApexDomain(line);
  33. } else if (!line.startsWith('#') && line.trim() !== '') {
  34. console.warn('[drop line from domainset]', line);
  35. }
  36. }
  37. };
  38. /**
  39. * @param {string} ruleSetPath
  40. */
  41. const processLocalRuleSet = async (ruleSetPath) => {
  42. for await (
  43. const line of readline.createInterface({
  44. input: fs.createReadStream(ruleSetPath),
  45. crlfDelay: Infinity
  46. })
  47. ) {
  48. if (line.startsWith('DOMAIN-SUFFIX,')) {
  49. addApexDomain(line.replace('DOMAIN-SUFFIX,', ''));
  50. } else if (line.startsWith('DOMAIN,')) {
  51. addApexDomain(line.replace('DOMAIN,', ''));
  52. } else if (!line.startsWith('#') && line.trim() !== '') {
  53. console.warn('[drop line from ruleset]', line);
  54. }
  55. }
  56. };
  57. await processLocalRuleSet(path.resolve(__dirname, '../List/non_ip/cdn.conf'));
  58. await processLocalRuleSet(path.resolve(__dirname, '../List/non_ip/global.conf'));
  59. await processLocalRuleSet(path.resolve(__dirname, '../List/non_ip/global_plus.conf'));
  60. await processLocalRuleSet(path.resolve(__dirname, '../List/non_ip/my_proxy.conf'));
  61. await processLocalRuleSet(path.resolve(__dirname, '../List/non_ip/stream.conf'));
  62. await processLocalRuleSet(path.resolve(__dirname, '../List/non_ip/telegram.conf'));
  63. await processLocalDomainSet(path.resolve(__dirname, '../List/domainset/cdn.conf'));
  64. await processLocalDomainSet(path.resolve(__dirname, '../List/domainset/download.conf'));
  65. await fse.ensureDir(path.resolve(__dirname, '../List/internal'));
  66. await fs.promises.writeFile(
  67. path.resolve(__dirname, '../List/internal/cdn.txt'),
  68. `${Array.from(set).map(i => `SUFFIX,${i}`).join('\n')}\n`
  69. );
  70. })();