build-common.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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 { fdir as Fdir } from 'fdir';
  11. import { appendArrayInPlace } from './lib/append-array-in-place';
  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. // .exclude((dirName, dirPath) => {
  23. // if (dirName === 'domainset' || dirName === 'ip' || dirName === 'non_ip') {
  24. // return false;
  25. // }
  26. // console.error(picocolors.red(`[build-comman] Unknown dir: ${dirPath}`));
  27. // return true;
  28. // })
  29. .filter((filepath, isDirectory) => {
  30. if (isDirectory) return true;
  31. const extname = path.extname(filepath);
  32. if (extname === '.js' || extname === '.ts') {
  33. return false;
  34. }
  35. return true;
  36. })
  37. .crawl(sourceDir)
  38. .withPromise();
  39. for (let i = 0, len = paths.length; i < len; i++) {
  40. const relativePath = paths[i];
  41. const fullPath = sourceDir + path.sep + relativePath;
  42. if (relativePath.startsWith('domainset/')) {
  43. promises.push(transformDomainset(span, fullPath, relativePath));
  44. continue;
  45. }
  46. // if (
  47. // relativePath.startsWith('ip/')
  48. // || relativePath.startsWith('non_ip/')
  49. // ) {
  50. promises.push(transformRuleset(span, fullPath, relativePath));
  51. // continue;
  52. // }
  53. // console.error(picocolors.red(`[build-comman] Unknown file: ${relativePath}`));
  54. }
  55. return Promise.all(promises);
  56. });
  57. const processFile = (span: Span, sourcePath: string) => {
  58. // console.log('Processing', sourcePath);
  59. return span.traceChildAsync(`process file: ${sourcePath}`, async () => {
  60. const lines: string[] = [];
  61. let title = '';
  62. const descriptions: string[] = [];
  63. try {
  64. for await (const line of readFileByLine(sourcePath)) {
  65. if (line.startsWith(MAGIC_COMMAND_SKIP)) {
  66. return null;
  67. }
  68. if (line.startsWith(MAGIC_COMMAND_TITLE)) {
  69. title = line.slice(MAGIC_COMMAND_TITLE.length).trim();
  70. continue;
  71. }
  72. if (line.startsWith(MAGIC_COMMAND_DESCRIPTION)) {
  73. descriptions.push(line.slice(MAGIC_COMMAND_DESCRIPTION.length).trim());
  74. continue;
  75. }
  76. const l = processLine(line);
  77. if (l) {
  78. lines.push(l);
  79. }
  80. }
  81. } catch (e) {
  82. console.error('Error processing', sourcePath);
  83. console.trace(e);
  84. }
  85. return [title, descriptions, lines] as const;
  86. });
  87. };
  88. function transformDomainset(parentSpan: Span, sourcePath: string, relativePath: string) {
  89. return parentSpan
  90. .traceChildAsync(
  91. `transform domainset: ${path.basename(sourcePath, path.extname(sourcePath))}`,
  92. async (span) => {
  93. const res = await processFile(span, sourcePath);
  94. if (!res) return;
  95. const [title, descriptions, lines] = res;
  96. const deduped = domainDeduper(lines);
  97. let description: string[];
  98. if (descriptions.length) {
  99. description = SHARED_DESCRIPTION.slice();
  100. description.push('');
  101. appendArrayInPlace(description, descriptions);
  102. } else {
  103. description = SHARED_DESCRIPTION;
  104. }
  105. return createRuleset(
  106. span,
  107. title,
  108. description,
  109. new Date(),
  110. deduped,
  111. 'domainset',
  112. path.resolve(outputSurgeDir, relativePath),
  113. path.resolve(outputClashDir, `${relativePath.slice(0, -path.extname(relativePath).length)}.txt`)
  114. );
  115. }
  116. );
  117. }
  118. /**
  119. * Output Surge RULE-SET and Clash classical text format
  120. */
  121. async function transformRuleset(parentSpan: Span, sourcePath: string, relativePath: string) {
  122. return parentSpan
  123. .traceChild(`transform ruleset: ${path.basename(sourcePath, path.extname(sourcePath))}`)
  124. .traceAsyncFn(async (span) => {
  125. const res = await processFile(span, sourcePath);
  126. if (!res) return null;
  127. const [title, descriptions, lines] = res;
  128. let description: string[];
  129. if (descriptions.length) {
  130. description = SHARED_DESCRIPTION.slice();
  131. description.push('');
  132. appendArrayInPlace(description, descriptions);
  133. } else {
  134. description = SHARED_DESCRIPTION;
  135. }
  136. return createRuleset(
  137. span,
  138. title,
  139. description,
  140. new Date(),
  141. lines,
  142. 'ruleset',
  143. path.resolve(outputSurgeDir, relativePath),
  144. path.resolve(outputClashDir, `${relativePath.slice(0, -path.extname(relativePath).length)}.txt`)
  145. );
  146. });
  147. }