build-telegram-cidr.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // @ts-check
  2. import { defaultRequestInit, fetchWithRetry } from './lib/fetch-retry';
  3. import { createReadlineInterfaceFromResponse } from './lib/fetch-remote-text-by-line';
  4. import path from 'path';
  5. import { isIPv4, isIPv6 } from 'net';
  6. import { processLine } from './lib/process-line';
  7. import { createRuleset } from './lib/create-file';
  8. import { task } from './lib/trace-runner';
  9. export const buildTelegramCIDR = task(__filename, async () => {
  10. const resp = await fetchWithRetry('https://core.telegram.org/resources/cidr.txt', defaultRequestInit);
  11. const lastModified = resp.headers.get('last-modified');
  12. const date = lastModified ? new Date(lastModified) : new Date();
  13. /** @type {string[]} */
  14. const results = [];
  15. for await (const line of createReadlineInterfaceFromResponse(resp)) {
  16. const cidr = processLine(line);
  17. if (!cidr) continue;
  18. const [subnet] = cidr.split('/');
  19. if (isIPv4(subnet)) {
  20. results.push(`IP-CIDR,${cidr},no-resolve`);
  21. }
  22. if (isIPv6(subnet)) {
  23. results.push(`IP-CIDR6,${cidr},no-resolve`);
  24. }
  25. }
  26. if (results.length === 0) {
  27. throw new Error('Failed to fetch data!');
  28. }
  29. const description = [
  30. 'License: AGPL 3.0',
  31. 'Homepage: https://ruleset.skk.moe',
  32. 'GitHub: https://github.com/SukkaW/Surge',
  33. 'Data from:',
  34. ' - https://core.telegram.org/resources/cidr.txt'
  35. ];
  36. return Promise.all(createRuleset(
  37. 'Sukka\'s Ruleset - Telegram IP CIDR',
  38. description,
  39. date,
  40. results,
  41. 'ruleset',
  42. path.resolve(__dirname, '../List/ip/telegram.conf'),
  43. path.resolve(__dirname, '../Clash/ip/telegram.txt')
  44. ));
  45. });
  46. if (import.meta.main) {
  47. buildTelegramCIDR();
  48. }