build-common.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. import { OUTPUT_CLASH_DIR, OUTPUT_SINGBOX_DIR, OUTPUT_SURGE_DIR, SOURCE_DIR } from './constants/dir';
  14. const MAGIC_COMMAND_SKIP = '# $ custom_build_script';
  15. const MAGIC_COMMAND_RM = '# $ custom_no_output';
  16. const MAGIC_COMMAND_TITLE = '# $ meta_title ';
  17. const MAGIC_COMMAND_DESCRIPTION = '# $ meta_description ';
  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(SOURCE_DIR)
  39. .withPromise();
  40. for (let i = 0, len = paths.length; i < len; i++) {
  41. const relativePath = paths[i];
  42. const fullPath = SOURCE_DIR + 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 $skip = Symbol('skip');
  59. const $rm = Symbol('rm');
  60. const processFile = (span: Span, sourcePath: string) => {
  61. // console.log('Processing', sourcePath);
  62. return span.traceChildAsync(`process file: ${sourcePath}`, async () => {
  63. const lines: string[] = [];
  64. let title = '';
  65. const descriptions: string[] = [];
  66. try {
  67. for await (const line of readFileByLine(sourcePath)) {
  68. if (line.startsWith(MAGIC_COMMAND_RM)) {
  69. return $rm;
  70. }
  71. if (line.startsWith(MAGIC_COMMAND_SKIP)) {
  72. return $skip;
  73. }
  74. if (line.startsWith(MAGIC_COMMAND_TITLE)) {
  75. title = line.slice(MAGIC_COMMAND_TITLE.length).trim();
  76. continue;
  77. }
  78. if (line.startsWith(MAGIC_COMMAND_DESCRIPTION)) {
  79. descriptions.push(line.slice(MAGIC_COMMAND_DESCRIPTION.length).trim());
  80. continue;
  81. }
  82. const l = processLine(line);
  83. if (l) {
  84. lines.push(l);
  85. }
  86. }
  87. } catch (e) {
  88. console.error('Error processing', sourcePath);
  89. console.trace(e);
  90. }
  91. return [title, descriptions, lines] as const;
  92. });
  93. };
  94. function transformDomainset(parentSpan: Span, sourcePath: string, relativePath: string) {
  95. return parentSpan
  96. .traceChildAsync(
  97. `transform domainset: ${path.basename(sourcePath, path.extname(sourcePath))}`,
  98. async (span) => {
  99. const res = await processFile(span, sourcePath);
  100. if (res === $skip) return;
  101. const clashFileBasename = relativePath.slice(0, -path.extname(relativePath).length);
  102. if (res === $rm) {
  103. return removeFiles([
  104. path.resolve(OUTPUT_SURGE_DIR, relativePath),
  105. path.resolve(OUTPUT_CLASH_DIR, `${clashFileBasename}.txt`),
  106. path.resolve(OUTPUT_SINGBOX_DIR, `${clashFileBasename}.json`)
  107. ]);
  108. }
  109. const [title, descriptions, lines] = res;
  110. const deduped = domainDeduper(lines);
  111. let description: string[];
  112. if (descriptions.length) {
  113. description = SHARED_DESCRIPTION.slice();
  114. description.push('');
  115. appendArrayInPlace(description, descriptions);
  116. } else {
  117. description = SHARED_DESCRIPTION;
  118. }
  119. return createRuleset(
  120. span,
  121. title,
  122. description,
  123. new Date(),
  124. deduped,
  125. 'domainset',
  126. [
  127. path.resolve(OUTPUT_SURGE_DIR, relativePath),
  128. path.resolve(OUTPUT_CLASH_DIR, `${clashFileBasename}.txt`),
  129. path.resolve(OUTPUT_SINGBOX_DIR, `${clashFileBasename}.json`)
  130. ]
  131. );
  132. }
  133. );
  134. }
  135. /**
  136. * Output Surge RULE-SET and Clash classical text format
  137. */
  138. async function transformRuleset(parentSpan: Span, sourcePath: string, relativePath: string) {
  139. return parentSpan
  140. .traceChild(`transform ruleset: ${path.basename(sourcePath, path.extname(sourcePath))}`)
  141. .traceAsyncFn(async (span) => {
  142. const res = await processFile(span, sourcePath);
  143. if (res === $skip) return;
  144. const clashFileBasename = relativePath.slice(0, -path.extname(relativePath).length);
  145. if (res === $rm) {
  146. return removeFiles([
  147. path.resolve(OUTPUT_SURGE_DIR, relativePath),
  148. path.resolve(OUTPUT_CLASH_DIR, `${clashFileBasename}.txt`),
  149. path.resolve(OUTPUT_SINGBOX_DIR, `${clashFileBasename}.json`)
  150. ]);
  151. }
  152. const [title, descriptions, lines] = res;
  153. let description: string[];
  154. if (descriptions.length) {
  155. description = SHARED_DESCRIPTION.slice();
  156. description.push('');
  157. appendArrayInPlace(description, descriptions);
  158. } else {
  159. description = SHARED_DESCRIPTION;
  160. }
  161. return createRuleset(
  162. span,
  163. title,
  164. description,
  165. new Date(),
  166. lines,
  167. 'ruleset',
  168. [
  169. path.resolve(OUTPUT_SURGE_DIR, relativePath),
  170. path.resolve(OUTPUT_CLASH_DIR, `${clashFileBasename}.txt`),
  171. path.resolve(OUTPUT_SINGBOX_DIR, `${clashFileBasename}.json`)
  172. ]
  173. );
  174. });
  175. }