create-file.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. // @ts-check
  2. import { surgeDomainsetToClashDomainset, surgeRulesetToClashClassicalTextRuleset } from './clash';
  3. import picocolors from 'picocolors';
  4. import type { Span } from '../trace';
  5. import path from 'node:path';
  6. import fs from 'node:fs';
  7. import { fastStringArrayJoin, writeFile } from './misc';
  8. import { readFileByLine } from './fetch-text-by-line';
  9. import stringify from 'json-stringify-pretty-compact';
  10. import { ipCidrListToSingbox, surgeDomainsetToSingbox, surgeRulesetToSingbox } from './singbox';
  11. import { createTrie } from './trie';
  12. import { pack, unpackFirst, unpackSecond } from './bitwise';
  13. import { asyncWriteToStream } from './async-write-to-stream';
  14. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  15. let isEqual = true;
  16. const linesALen = linesA.length;
  17. if (!fs.existsSync(filePath)) {
  18. console.log(`${filePath} does not exists, writing...`);
  19. isEqual = false;
  20. } else if (linesALen === 0) {
  21. console.log(`Nothing to write to ${filePath}...`);
  22. isEqual = false;
  23. } else {
  24. isEqual = await span.traceChildAsync(`comparing ${filePath}`, async () => {
  25. let index = 0;
  26. for await (const lineB of readFileByLine(filePath)) {
  27. const lineA = linesA[index] as string | undefined;
  28. index++;
  29. if (lineA == null) {
  30. // The file becomes smaller
  31. return false;
  32. }
  33. if (lineA[0] === '#' && lineB[0] === '#') {
  34. continue;
  35. }
  36. if (
  37. lineA[0] === '/'
  38. && lineA[1] === '/'
  39. && lineB[0] === '/'
  40. && lineB[1] === '/'
  41. && lineA[3] === '#'
  42. && lineB[3] === '#'
  43. ) {
  44. continue;
  45. }
  46. if (lineA !== lineB) {
  47. return false;
  48. }
  49. }
  50. if (index !== linesALen) {
  51. // The file becomes larger
  52. return false;
  53. }
  54. return true;
  55. });
  56. }
  57. if (isEqual) {
  58. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  59. return;
  60. }
  61. await span.traceChildAsync(`writing ${filePath}`, async () => {
  62. // The default highwater mark is normally 16384,
  63. // So we make sure direct write to file if the content is
  64. // most likely less than 500 lines
  65. if (linesALen < 500) {
  66. return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
  67. }
  68. const writeStream = fs.createWriteStream(filePath);
  69. for (let i = 0; i < linesALen; i++) {
  70. let p = asyncWriteToStream(writeStream, linesA[i]);
  71. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  72. if (p) await p;
  73. p = asyncWriteToStream(writeStream, '\n');
  74. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  75. if (p) await p;
  76. }
  77. await asyncWriteToStream(writeStream, '\n');
  78. writeStream.end();
  79. });
  80. }
  81. const withBannerArray = (title: string, description: string[] | readonly string[], date: Date, content: string[]) => {
  82. return [
  83. '#########################################',
  84. `# ${title}`,
  85. `# Last Updated: ${date.toISOString()}`,
  86. `# Size: ${content.length}`,
  87. ...description.map(line => (line ? `# ${line}` : '#')),
  88. '#########################################',
  89. ...content,
  90. '################## EOF ##################'
  91. ];
  92. };
  93. const defaultSortTypeOrder = Symbol('defaultSortTypeOrder');
  94. const sortTypeOrder: Record<string | typeof defaultSortTypeOrder, number> = {
  95. DOMAIN: 1,
  96. 'DOMAIN-SUFFIX': 2,
  97. 'DOMAIN-KEYWORD': 10,
  98. // experimental domain wildcard support
  99. 'DOMAIN-WILDCARD': 20,
  100. 'DOMAIN-REGEX': 21,
  101. 'USER-AGENT': 30,
  102. 'PROCESS-NAME': 40,
  103. [defaultSortTypeOrder]: 50, // default sort order for unknown type
  104. 'URL-REGEX': 100,
  105. AND: 300,
  106. OR: 300,
  107. 'IP-CIDR': 400,
  108. 'IP-CIDR6': 400
  109. };
  110. const flagDomain = 1 << 2;
  111. const flagDomainSuffix = 1 << 3;
  112. // dedupe and sort based on rule type
  113. const processRuleSet = (ruleSet: string[]) => {
  114. const trie = createTrie<number>(null, true);
  115. /** Packed Array<[valueIndex: number, weight: number]> */
  116. const sortMap: number[] = [];
  117. for (let i = 0, len = ruleSet.length; i < len; i++) {
  118. const line = ruleSet[i];
  119. const [type, value] = line.split(',');
  120. let extraWeight = 0;
  121. switch (type) {
  122. case 'DOMAIN':
  123. trie.add(value, pack(i, flagDomain));
  124. break;
  125. case 'DOMAIN-SUFFIX':
  126. trie.add('.' + value, pack(i, flagDomainSuffix));
  127. break;
  128. case 'URL-REGEX':
  129. if (value.includes('.+') || value.includes('.*')) {
  130. extraWeight += 10;
  131. }
  132. if (value.includes('|')) {
  133. extraWeight += 1;
  134. }
  135. sortMap.push(pack(i, sortTypeOrder[type] + extraWeight));
  136. break;
  137. case null:
  138. sortMap.push(pack(i, 10));
  139. break;
  140. default:
  141. if (type in sortTypeOrder) {
  142. sortMap.push(pack(i, sortTypeOrder[type]));
  143. } else {
  144. sortMap.push(pack(i, sortTypeOrder[defaultSortTypeOrder]));
  145. }
  146. }
  147. }
  148. const dumped = trie.dumpWithMeta();
  149. for (let i = 0, len = dumped.length; i < len; i++) {
  150. const originalIndex = unpackFirst(dumped[i][1]);
  151. const flag = unpackSecond(dumped[i][1]);
  152. const type = flag === flagDomain ? 'DOMAIN' : 'DOMAIN-SUFFIX';
  153. sortMap.push(pack(originalIndex, sortTypeOrder[type]));
  154. }
  155. return sortMap
  156. .sort((a, b) => unpackSecond(a) - unpackSecond(b))
  157. .map(c => ruleSet[unpackFirst(c)]);
  158. };
  159. const MARK = 'this_ruleset_is_made_by_sukkaw.ruleset.skk.moe';
  160. export const createRuleset = (
  161. parentSpan: Span,
  162. title: string, description: string[] | readonly string[], date: Date, content: string[],
  163. type: 'ruleset' | 'domainset' | 'ipcidr' | 'ipcidr6',
  164. [surgePath, clashPath, singBoxPath, _clashMrsPath]: readonly [
  165. surgePath: string,
  166. clashPath: string,
  167. singBoxPath: string,
  168. _clashMrsPath?: string
  169. ]
  170. ) => parentSpan.traceChild(`create ruleset: ${path.basename(surgePath, path.extname(surgePath))}`).traceAsyncFn(async (childSpan) => {
  171. content = processRuleSet(content);
  172. const surgeContent = childSpan.traceChildSync('process surge ruleset', () => {
  173. let _surgeContent;
  174. switch (type) {
  175. case 'domainset':
  176. _surgeContent = [MARK, ...content];
  177. break;
  178. case 'ruleset':
  179. _surgeContent = [`DOMAIN,${MARK}`, ...content];
  180. break;
  181. case 'ipcidr':
  182. _surgeContent = [`DOMAIN,${MARK}`, ...content.map(i => `IP-CIDR,${i}`)];
  183. break;
  184. case 'ipcidr6':
  185. _surgeContent = [`DOMAIN,${MARK}`, ...content.map(i => `IP-CIDR6,${i}`)];
  186. break;
  187. default:
  188. throw new TypeError(`Unknown type: ${type}`);
  189. }
  190. return withBannerArray(title, description, date, _surgeContent);
  191. });
  192. const clashContent = childSpan.traceChildSync('convert incoming ruleset to clash', () => {
  193. let _clashContent;
  194. switch (type) {
  195. case 'domainset':
  196. _clashContent = [MARK, ...surgeDomainsetToClashDomainset(content)];
  197. break;
  198. case 'ruleset':
  199. _clashContent = [`DOMAIN,${MARK}`, ...surgeRulesetToClashClassicalTextRuleset(content)];
  200. break;
  201. case 'ipcidr':
  202. case 'ipcidr6':
  203. _clashContent = content;
  204. break;
  205. default:
  206. throw new TypeError(`Unknown type: ${type}`);
  207. }
  208. return withBannerArray(title, description, date, _clashContent);
  209. });
  210. const singboxContent = childSpan.traceChildSync('convert incoming ruleset to singbox', () => {
  211. let _singBoxContent;
  212. switch (type) {
  213. case 'domainset':
  214. _singBoxContent = surgeDomainsetToSingbox([MARK, ...content]);
  215. break;
  216. case 'ruleset':
  217. _singBoxContent = surgeRulesetToSingbox([`DOMAIN,${MARK}`, ...content]);
  218. break;
  219. case 'ipcidr':
  220. case 'ipcidr6':
  221. _singBoxContent = ipCidrListToSingbox(content);
  222. break;
  223. default:
  224. throw new TypeError(`Unknown type: ${type}`);
  225. }
  226. return stringify(_singBoxContent).split('\n');
  227. });
  228. await Promise.all([
  229. compareAndWriteFile(childSpan, surgeContent, surgePath),
  230. compareAndWriteFile(childSpan, clashContent, clashPath),
  231. compareAndWriteFile(childSpan, singboxContent, singBoxPath)
  232. ]);
  233. // if (clashMrsPath) {
  234. // if (type === 'domainset') {
  235. // await childSpan.traceChildAsync('clash meta mrs domain ' + clashMrsPath, async () => {
  236. // await fs.promises.mkdir(path.dirname(clashMrsPath), { recursive: true });
  237. // await convertClashMetaMrs(
  238. // 'domain', 'text', clashPath, clashMrsPath
  239. // );
  240. // });
  241. // }
  242. // }
  243. });