build-common.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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 domainsetSrcFolder = 'domainset' + path.sep;
  16. export const buildCommon = task(require.main === module, __filename)(async (span) => {
  17. const promises: Array<Promise<unknown>> = [];
  18. const paths = await new Fdir()
  19. .withRelativePaths()
  20. // .exclude((dirName, dirPath) => {
  21. // if (dirName === 'domainset' || dirName === 'ip' || dirName === 'non_ip') {
  22. // return false;
  23. // }
  24. // console.error(picocolors.red(`[build-comman] Unknown dir: ${dirPath}`));
  25. // return true;
  26. // })
  27. .filter((filepath, isDirectory) => {
  28. if (isDirectory) return true;
  29. const extname = path.extname(filepath);
  30. if (extname === '.js' || extname === '.ts') {
  31. return false;
  32. }
  33. return true;
  34. })
  35. .crawl(SOURCE_DIR)
  36. .withPromise();
  37. for (let i = 0, len = paths.length; i < len; i++) {
  38. const relativePath = paths[i];
  39. const fullPath = SOURCE_DIR + path.sep + relativePath;
  40. if (relativePath.startsWith(domainsetSrcFolder)) {
  41. promises.push(transformDomainset(span, fullPath, relativePath));
  42. continue;
  43. }
  44. // if (
  45. // relativePath.startsWith('ip/')
  46. // || relativePath.startsWith('non_ip/')
  47. // ) {
  48. promises.push(transformRuleset(span, fullPath, relativePath));
  49. // continue;
  50. // }
  51. // console.error(picocolors.red(`[build-comman] Unknown file: ${relativePath}`));
  52. }
  53. return Promise.all(promises);
  54. });
  55. const $skip = Symbol('skip');
  56. const processFile = (span: Span, sourcePath: string) => {
  57. // console.log('Processing', sourcePath);
  58. return span.traceChildAsync(`process file: ${sourcePath}`, async () => {
  59. const lines: string[] = [];
  60. let title = '';
  61. const descriptions: string[] = [];
  62. try {
  63. for await (const line of readFileByLine(sourcePath)) {
  64. if (line.startsWith(MAGIC_COMMAND_SKIP)) {
  65. return $skip;
  66. }
  67. if (line.startsWith(MAGIC_COMMAND_TITLE)) {
  68. title = line.slice(MAGIC_COMMAND_TITLE.length).trim();
  69. continue;
  70. }
  71. if (line.startsWith(MAGIC_COMMAND_DESCRIPTION)) {
  72. descriptions.push(line.slice(MAGIC_COMMAND_DESCRIPTION.length).trim());
  73. continue;
  74. }
  75. const l = processLine(line);
  76. if (l) {
  77. lines.push(l);
  78. }
  79. }
  80. } catch (e) {
  81. console.error('Error processing', sourcePath);
  82. console.trace(e);
  83. }
  84. return [title, descriptions, lines] as const;
  85. });
  86. };
  87. function transformDomainset(parentSpan: Span, sourcePath: string, relativePath: string) {
  88. return parentSpan
  89. .traceChildAsync(
  90. `transform domainset: ${path.basename(sourcePath, path.extname(sourcePath))}`,
  91. async (span) => {
  92. const res = await processFile(span, sourcePath);
  93. if (res === $skip) return;
  94. const id = path.basename(relativePath).slice(0, -path.extname(relativePath).length);
  95. const [title, descriptions, lines] = res;
  96. let description: string[];
  97. if (descriptions.length) {
  98. description = SHARED_DESCRIPTION.slice();
  99. description.push('');
  100. appendArrayInPlace(description, descriptions);
  101. } else {
  102. description = SHARED_DESCRIPTION;
  103. }
  104. return new DomainsetOutput(span, id)
  105. .withTitle(title)
  106. .withDescription(description)
  107. .addFromDomainset(lines)
  108. .write();
  109. }
  110. );
  111. }
  112. /**
  113. * Output Surge RULE-SET and Clash classical text format
  114. */
  115. async function transformRuleset(parentSpan: Span, sourcePath: string, relativePath: string) {
  116. return parentSpan
  117. .traceChild(`transform ruleset: ${path.basename(sourcePath, path.extname(sourcePath))}`)
  118. .traceAsyncFn(async (span) => {
  119. const res = await processFile(span, sourcePath);
  120. if (res === $skip) return;
  121. const [type, id] = relativePath.slice(0, -path.extname(relativePath).length).split(path.sep);
  122. if (type !== 'ip' && type !== 'non_ip') {
  123. throw new TypeError(`Invalid type: ${type}`);
  124. }
  125. const [title, descriptions, lines] = res;
  126. let description: string[];
  127. if (descriptions.length) {
  128. description = SHARED_DESCRIPTION.slice();
  129. description.push('');
  130. appendArrayInPlace(description, descriptions);
  131. } else {
  132. description = SHARED_DESCRIPTION;
  133. }
  134. return new RulesetOutput(span, id, type)
  135. .withTitle(title)
  136. .withDescription(description)
  137. .addFromRuleset(lines)
  138. .write();
  139. });
  140. }