build-common.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. 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. let sgmodulePathname: string | null = null;
  64. try {
  65. for await (const line of readFileByLine(sourcePath)) {
  66. if (line.startsWith(MAGIC_COMMAND_SKIP)) {
  67. return $skip;
  68. }
  69. if (line.startsWith(MAGIC_COMMAND_TITLE)) {
  70. title = line.slice(MAGIC_COMMAND_TITLE.length).trim();
  71. continue;
  72. }
  73. if (line.startsWith(MAGIC_COMMAND_DESCRIPTION)) {
  74. descriptions.push(line.slice(MAGIC_COMMAND_DESCRIPTION.length).trim());
  75. continue;
  76. }
  77. if (line.startsWith(MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES)) {
  78. sgmodulePathname = line.slice(MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES.length).trim();
  79. continue;
  80. }
  81. const l = processLine(line);
  82. if (l) {
  83. lines.push(l);
  84. }
  85. }
  86. } catch (e) {
  87. console.error('Error processing', sourcePath);
  88. console.trace(e);
  89. }
  90. return [title, descriptions, lines, sgmodulePathname] as const;
  91. });
  92. };
  93. function transformDomainset(parentSpan: Span, sourcePath: string, relativePath: string) {
  94. return parentSpan
  95. .traceChildAsync(
  96. `transform domainset: ${path.basename(sourcePath, path.extname(sourcePath))}`,
  97. async (span) => {
  98. const res = await processFile(span, sourcePath);
  99. if (res === $skip) return;
  100. const id = path.basename(relativePath).slice(0, -path.extname(relativePath).length);
  101. const [title, descriptions, lines] = res;
  102. let description: string[];
  103. if (descriptions.length) {
  104. description = SHARED_DESCRIPTION.slice();
  105. description.push('');
  106. appendArrayInPlace(description, descriptions);
  107. } else {
  108. description = SHARED_DESCRIPTION;
  109. }
  110. return new DomainsetOutput(span, id)
  111. .withTitle(title)
  112. .withDescription(description)
  113. .addFromDomainset(lines)
  114. .write();
  115. }
  116. );
  117. }
  118. /**
  119. * Output Surge RULE-SET and Clash classical text format
  120. */
  121. async function transformRuleset(parentSpan: Span, sourcePath: string, relativePath: string) {
  122. return parentSpan
  123. .traceChild(`transform ruleset: ${path.basename(sourcePath, path.extname(sourcePath))}`)
  124. .traceAsyncFn(async (span) => {
  125. const res = await processFile(span, sourcePath);
  126. if (res === $skip) return;
  127. const [type, id] = relativePath.slice(0, -path.extname(relativePath).length).split(path.sep);
  128. if (type !== 'ip' && type !== 'non_ip') {
  129. throw new TypeError(`Invalid type: ${type}`);
  130. }
  131. const [title, descriptions, lines, sgmodulePathname] = res;
  132. let description: string[];
  133. if (descriptions.length) {
  134. description = SHARED_DESCRIPTION.slice();
  135. description.push('');
  136. appendArrayInPlace(description, descriptions);
  137. } else {
  138. description = SHARED_DESCRIPTION;
  139. }
  140. return new RulesetOutput(span, id, type)
  141. .withTitle(title)
  142. .withDescription(description)
  143. .withMitmSgmodulePath(sgmodulePathname)
  144. .addFromRuleset(lines)
  145. .write();
  146. });
  147. }