clash.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import picocolors from 'picocolors';
  2. const identity = <T>(x: T): T => x;
  3. const unsupported = Symbol('unsupported');
  4. // https://dreamacro.github.io/clash/configuration/rules.html
  5. const PROCESSOR: Record<string, ((raw: string, type: string, value: string) => string) | typeof unsupported> = {
  6. DOMAIN: identity,
  7. 'DOMAIN-SUFFIX': identity,
  8. 'DOMAIN-KEYWORD': identity,
  9. GEOIP: identity,
  10. 'IP-CIDR': identity,
  11. 'IP-CIDR6': identity,
  12. 'IP-ASN': identity,
  13. 'SRC-IP-CIDR': identity,
  14. 'SRC-PORT': identity,
  15. 'DST-PORT': identity,
  16. 'PROCESS-NAME': identity,
  17. 'PROCESS-PATH': identity,
  18. 'DEST-PORT': (_raw, type, value) => `DST-PORT,${value}`,
  19. 'IN-PORT': (_raw, type, value) => `SRC-PORT,${value}`,
  20. 'URL-REGEX': unsupported,
  21. 'USER-AGENT': unsupported
  22. };
  23. export const surgeRulesetToClashClassicalTextRuleset = (rules: string[] | Set<string>) => {
  24. return Array.from(rules).reduce<string[]>((acc, cur) => {
  25. let buf = '';
  26. let type = '';
  27. let i = 0;
  28. for (const len = cur.length; i < len; i++) {
  29. if (cur[i] === ',') {
  30. type = buf;
  31. break;
  32. }
  33. buf += cur[i];
  34. }
  35. if (type === '') {
  36. return acc;
  37. }
  38. const value = cur.slice(i + 1);
  39. if (type in PROCESSOR) {
  40. const proc = PROCESSOR[type];
  41. if (proc !== unsupported) {
  42. acc.push(proc(cur, type, value));
  43. }
  44. } else {
  45. console.log(picocolors.yellow(`[clash] unknown rule type: ${type}`), cur);
  46. }
  47. return acc;
  48. }, []);
  49. };
  50. export const surgeDomainsetToClashDomainset = (domainset: string[]) => {
  51. return domainset.map(i => (i[0] === '.' ? `+${i}` : i));
  52. };
  53. export const surgeDomainsetToClashRuleset = (domainset: string[]) => {
  54. return domainset.map(i => (i[0] === '.' ? `DOMAIN-SUFFIX,${i.slice(1)}` : `DOMAIN,${i}`));
  55. };