ip.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import type { Span } from '../../trace';
  2. import { appendArrayInPlace } from '../append-array-in-place';
  3. import { appendArrayFromSet } from '../misc';
  4. import type { SingboxSourceFormat } from '../singbox';
  5. import { RuleOutput } from './base';
  6. import { merge } from 'fast-cidr-tools';
  7. type Preprocessed = string[];
  8. export class IPListOutput extends RuleOutput<Preprocessed> {
  9. protected type = 'ip' as const;
  10. constructor(span: Span, id: string, private readonly clashUseRule = true) {
  11. super(span, id);
  12. }
  13. protected preprocess() {
  14. const results: string[] = [];
  15. appendArrayInPlace(
  16. results,
  17. merge(
  18. appendArrayInPlace(Array.from(this.ipcidrNoResolve), Array.from(this.ipcidr)),
  19. true
  20. )
  21. );
  22. appendArrayFromSet(results, this.ipcidr6NoResolve);
  23. appendArrayFromSet(results, this.ipcidr6);
  24. return results;
  25. }
  26. private $surge: string[] | null = null;
  27. surge(): string[] {
  28. if (!this.$surge) {
  29. const results: string[] = ['DOMAIN,this_ruleset_is_made_by_sukkaw.ruleset.skk.moe'];
  30. appendArrayInPlace(
  31. results,
  32. merge(Array.from(this.ipcidrNoResolve)).map(i => `IP-CIDR,${i},no-resolve`, true)
  33. );
  34. appendArrayFromSet(results, this.ipcidr6NoResolve, i => `IP-CIDR6,${i},no-resolve`);
  35. appendArrayInPlace(
  36. results,
  37. merge(Array.from(this.ipcidr)).map(i => `IP-CIDR,${i}`, true)
  38. );
  39. appendArrayFromSet(results, this.ipcidr6, i => `IP-CIDR6,${i}`);
  40. this.$surge = results;
  41. }
  42. return this.$surge;
  43. }
  44. clash(): string[] {
  45. if (this.clashUseRule) {
  46. return this.surge();
  47. }
  48. return this.$preprocessed;
  49. }
  50. singbox(): string[] {
  51. const singbox: SingboxSourceFormat = {
  52. version: 2,
  53. rules: [{
  54. domain: ['this_ruleset_is_made_by_sukkaw.ruleset.skk.moe'],
  55. ip_cidr: this.$preprocessed
  56. }]
  57. };
  58. return RuleOutput.jsonToLines(singbox);
  59. }
  60. }