build-common.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. // @ts-check
  2. import * as path from 'path';
  3. import { readFileByLine } from './lib/fetch-text-by-line';
  4. import { processLine } from './lib/process-line';
  5. import { createRuleset } from './lib/create-file';
  6. import { domainDeduper } from './lib/domain-deduper';
  7. import type { Span } from './trace';
  8. import { task } from './trace';
  9. import { SHARED_DESCRIPTION } from './lib/constants';
  10. import picocolors from 'picocolors';
  11. import { fdir as Fdir } from 'fdir';
  12. const MAGIC_COMMAND_SKIP = '# $ custom_build_script';
  13. const MAGIC_COMMAND_TITLE = '# $ meta_title ';
  14. const MAGIC_COMMAND_DESCRIPTION = '# $ meta_description ';
  15. const sourceDir = path.resolve(import.meta.dir, '../Source');
  16. const outputSurgeDir = path.resolve(import.meta.dir, '../List');
  17. const outputClashDir = path.resolve(import.meta.dir, '../Clash');
  18. export const buildCommon = task(import.meta.main, import.meta.path)(async (span) => {
  19. const promises: Array<Promise<unknown>> = [];
  20. const paths = await new Fdir()
  21. .withRelativePaths()
  22. .crawl(sourceDir)
  23. .withPromise();
  24. for (let i = 0, len = paths.length; i < len; i++) {
  25. const relativePath = paths[i];
  26. const extname = path.extname(relativePath);
  27. if (extname === '.js' || extname === '.ts') {
  28. continue;
  29. }
  30. const fullPath = sourceDir + path.sep + relativePath;
  31. if (relativePath.startsWith('domainset/')) {
  32. promises.push(transformDomainset(span, fullPath, relativePath));
  33. continue;
  34. }
  35. if (
  36. relativePath.startsWith('ip/')
  37. || relativePath.startsWith('non_ip/')
  38. ) {
  39. promises.push(transformRuleset(span, fullPath, relativePath));
  40. continue;
  41. }
  42. console.error(picocolors.red(`[build-comman] Unknown file: ${relativePath}`));
  43. }
  44. return Promise.all(promises);
  45. });
  46. const processFile = (span: Span, sourcePath: string) => {
  47. // console.log('Processing', sourcePath);
  48. return span.traceChildAsync(`process file: ${sourcePath}`, async () => {
  49. const lines: string[] = [];
  50. let title = '';
  51. const descriptions: string[] = [];
  52. try {
  53. for await (const line of readFileByLine(sourcePath)) {
  54. if (line.startsWith(MAGIC_COMMAND_SKIP)) {
  55. return null;
  56. }
  57. if (line.startsWith(MAGIC_COMMAND_TITLE)) {
  58. title = line.slice(MAGIC_COMMAND_TITLE.length).trim();
  59. continue;
  60. }
  61. if (line.startsWith(MAGIC_COMMAND_DESCRIPTION)) {
  62. descriptions.push(line.slice(MAGIC_COMMAND_DESCRIPTION.length).trim());
  63. continue;
  64. }
  65. const l = processLine(line);
  66. if (l) {
  67. lines.push(l);
  68. }
  69. }
  70. } catch (e) {
  71. console.error('Error processing', sourcePath);
  72. console.trace(e);
  73. }
  74. return [title, descriptions, lines] as const;
  75. });
  76. };
  77. function transformDomainset(parentSpan: Span, sourcePath: string, relativePath: string) {
  78. return parentSpan
  79. .traceChildAsync(
  80. `transform domainset: ${path.basename(sourcePath, path.extname(sourcePath))}`,
  81. async (span) => {
  82. const res = await processFile(span, sourcePath);
  83. if (!res) return;
  84. const [title, descriptions, lines] = res;
  85. const deduped = domainDeduper(lines);
  86. const description = [
  87. ...SHARED_DESCRIPTION,
  88. ...(
  89. descriptions.length
  90. ? ['', ...descriptions]
  91. : []
  92. )
  93. ];
  94. return createRuleset(
  95. span,
  96. title,
  97. description,
  98. new Date(),
  99. deduped,
  100. 'domainset',
  101. path.resolve(outputSurgeDir, relativePath),
  102. path.resolve(outputClashDir, `${relativePath.slice(0, -path.extname(relativePath).length)}.txt`)
  103. );
  104. }
  105. );
  106. }
  107. /**
  108. * Output Surge RULE-SET and Clash classical text format
  109. */
  110. async function transformRuleset(parentSpan: Span, sourcePath: string, relativePath: string) {
  111. return parentSpan
  112. .traceChild(`transform ruleset: ${path.basename(sourcePath, path.extname(sourcePath))}`)
  113. .traceAsyncFn(async (span) => {
  114. const res = await processFile(span, sourcePath);
  115. if (!res) return null;
  116. const [title, descriptions, lines] = res;
  117. const description = [
  118. ...SHARED_DESCRIPTION,
  119. ...(
  120. descriptions.length
  121. ? ['', ...descriptions]
  122. : []
  123. )
  124. ];
  125. return createRuleset(
  126. span,
  127. title,
  128. description,
  129. new Date(),
  130. lines,
  131. 'ruleset',
  132. path.resolve(outputSurgeDir, relativePath),
  133. path.resolve(outputClashDir, `${relativePath.slice(0, -path.extname(relativePath).length)}.txt`)
  134. );
  135. });
  136. }