build-common.ts 6.3 KB

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