build-common.ts 5.6 KB

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