build-common.ts 5.2 KB

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