build-common.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 { OUTPUT_CLASH_DIR, OUTPUT_SINGBOX_DIR, OUTPUT_SURGE_DIR, SOURCE_DIR } from './constants/dir';
  13. const MAGIC_COMMAND_SKIP = '# $ custom_build_script';
  14. const MAGIC_COMMAND_TITLE = '# $ meta_title ';
  15. const MAGIC_COMMAND_DESCRIPTION = '# $ meta_description ';
  16. const domainsetSrcFolder = 'domainset' + path.sep;
  17. export const buildCommon = task(require.main === module, __filename)(async (span) => {
  18. const promises: Array<Promise<unknown>> = [];
  19. const paths = await new Fdir()
  20. .withRelativePaths()
  21. // .exclude((dirName, dirPath) => {
  22. // if (dirName === 'domainset' || dirName === 'ip' || dirName === 'non_ip') {
  23. // return false;
  24. // }
  25. // console.error(picocolors.red(`[build-comman] Unknown dir: ${dirPath}`));
  26. // return true;
  27. // })
  28. .filter((filepath, isDirectory) => {
  29. if (isDirectory) return true;
  30. const extname = path.extname(filepath);
  31. if (extname === '.js' || extname === '.ts') {
  32. return false;
  33. }
  34. return true;
  35. })
  36. .crawl(SOURCE_DIR)
  37. .withPromise();
  38. for (let i = 0, len = paths.length; i < len; i++) {
  39. const relativePath = paths[i];
  40. const fullPath = SOURCE_DIR + path.sep + relativePath;
  41. if (relativePath.startsWith(domainsetSrcFolder)) {
  42. promises.push(transformDomainset(span, fullPath, relativePath));
  43. continue;
  44. }
  45. // if (
  46. // relativePath.startsWith('ip/')
  47. // || relativePath.startsWith('non_ip/')
  48. // ) {
  49. promises.push(transformRuleset(span, fullPath, relativePath));
  50. // continue;
  51. // }
  52. // console.error(picocolors.red(`[build-comman] Unknown file: ${relativePath}`));
  53. }
  54. return Promise.all(promises);
  55. });
  56. const $skip = Symbol('skip');
  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 $skip;
  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 === $skip) return;
  95. const clashFileBasename = relativePath.slice(0, -path.extname(relativePath).length);
  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. return createRuleset(
  107. span,
  108. title,
  109. description,
  110. new Date(),
  111. deduped,
  112. 'domainset',
  113. [
  114. path.resolve(OUTPUT_SURGE_DIR, relativePath),
  115. path.resolve(OUTPUT_CLASH_DIR, `${clashFileBasename}.txt`),
  116. path.resolve(OUTPUT_SINGBOX_DIR, `${clashFileBasename}.json`)
  117. ]
  118. );
  119. }
  120. );
  121. }
  122. /**
  123. * Output Surge RULE-SET and Clash classical text format
  124. */
  125. async function transformRuleset(parentSpan: Span, sourcePath: string, relativePath: string) {
  126. return parentSpan
  127. .traceChild(`transform ruleset: ${path.basename(sourcePath, path.extname(sourcePath))}`)
  128. .traceAsyncFn(async (span) => {
  129. const res = await processFile(span, sourcePath);
  130. if (res === $skip) return;
  131. const clashFileBasename = relativePath.slice(0, -path.extname(relativePath).length);
  132. const [title, descriptions, lines] = res;
  133. let description: string[];
  134. if (descriptions.length) {
  135. description = SHARED_DESCRIPTION.slice();
  136. description.push('');
  137. appendArrayInPlace(description, descriptions);
  138. } else {
  139. description = SHARED_DESCRIPTION;
  140. }
  141. return createRuleset(
  142. span,
  143. title,
  144. description,
  145. new Date(),
  146. lines,
  147. 'ruleset',
  148. [
  149. path.resolve(OUTPUT_SURGE_DIR, relativePath),
  150. path.resolve(OUTPUT_CLASH_DIR, `${clashFileBasename}.txt`),
  151. path.resolve(OUTPUT_SINGBOX_DIR, `${clashFileBasename}.json`)
  152. ]
  153. );
  154. });
  155. }