ip.ts 2.0 KB

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