build-common.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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 type { Span } from './trace';
  6. import { task } from './trace';
  7. import { SHARED_DESCRIPTION } from './lib/constants';
  8. import { fdir as Fdir } from 'fdir';
  9. import { appendArrayInPlace } from './lib/append-array-in-place';
  10. import { SOURCE_DIR } from './constants/dir';
  11. import { DomainsetOutput, RulesetOutput } from './lib/create-file';
  12. const MAGIC_COMMAND_SKIP = '# $ custom_build_script';
  13. const MAGIC_COMMAND_TITLE = '# $ meta_title ';
  14. const MAGIC_COMMAND_DESCRIPTION = '# $ meta_description ';
  15. const MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES = '# $ sgmodule_mitm_hostnames ';
  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. return !(extname === '.js' || extname === '.ts');
  32. })
  33. .crawl(SOURCE_DIR)
  34. .withPromise();
  35. for (let i = 0, len = paths.length; i < len; i++) {
  36. const relativePath = paths[i];
  37. const fullPath = SOURCE_DIR + path.sep + relativePath;
  38. if (relativePath.startsWith(domainsetSrcFolder)) {
  39. promises.push(transformDomainset(span, fullPath, relativePath));
  40. continue;
  41. }
  42. // if (
  43. // relativePath.startsWith('ip/')
  44. // || relativePath.startsWith('non_ip/')
  45. // ) {
  46. promises.push(transformRuleset(span, fullPath, relativePath));
  47. // continue;
  48. // }
  49. // console.error(picocolors.red(`[build-comman] Unknown file: ${relativePath}`));
  50. }
  51. return Promise.all(promises);
  52. });
  53. const $skip = Symbol('skip');
  54. function processFile(span: Span, sourcePath: string) {
  55. return span.traceChildAsync(`process file: ${sourcePath}`, async () => {
  56. const lines: string[] = [];
  57. let title = '';
  58. const descriptions: string[] = [];
  59. let sgmodulePathname: string | null = null;
  60. try {
  61. for await (const line of readFileByLine(sourcePath)) {
  62. if (line.startsWith(MAGIC_COMMAND_SKIP)) {
  63. return $skip;
  64. }
  65. if (line.startsWith(MAGIC_COMMAND_TITLE)) {
  66. title = line.slice(MAGIC_COMMAND_TITLE.length).trim();
  67. continue;
  68. }
  69. if (line.startsWith(MAGIC_COMMAND_DESCRIPTION)) {
  70. descriptions.push(line.slice(MAGIC_COMMAND_DESCRIPTION.length).trim());
  71. continue;
  72. }
  73. if (line.startsWith(MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES)) {
  74. sgmodulePathname = line.slice(MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES.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, sgmodulePathname] 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 === $skip) return;
  96. const id = path.basename(relativePath).slice(0, -path.extname(relativePath).length);
  97. const [title, descriptions, lines] = res;
  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 new DomainsetOutput(span, id)
  107. .withTitle(title)
  108. .withDescription(description)
  109. .addFromDomainset(lines)
  110. .write();
  111. }
  112. );
  113. }
  114. /**
  115. * Output Surge RULE-SET and Clash classical text format
  116. */
  117. async function transformRuleset(parentSpan: Span, sourcePath: string, relativePath: string) {
  118. return parentSpan
  119. .traceChild(`transform ruleset: ${path.basename(sourcePath, path.extname(sourcePath))}`)
  120. .traceAsyncFn(async (span) => {
  121. const res = await processFile(span, sourcePath);
  122. if (res === $skip) return;
  123. const [type, id] = relativePath.slice(0, -path.extname(relativePath).length).split(path.sep);
  124. if (type !== 'ip' && type !== 'non_ip') {
  125. throw new TypeError(`Invalid type: ${type}`);
  126. }
  127. const [title, descriptions, lines, sgmodulePathname] = res;
  128. let description: string[];
  129. if (descriptions.length) {
  130. description = SHARED_DESCRIPTION.slice();
  131. description.push('');
  132. appendArrayInPlace(description, descriptions);
  133. } else {
  134. description = SHARED_DESCRIPTION;
  135. }
  136. return new RulesetOutput(span, id, type)
  137. .withTitle(title)
  138. .withDescription(description)
  139. .withMitmSgmodulePath(sgmodulePathname)
  140. .addFromRuleset(lines)
  141. .write();
  142. });
  143. }