parse-dnsmasq.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { createReadlineInterfaceFromResponse } from './fetch-text-by-line';
  2. // https://github.com/remusao/tldts/issues/2121
  3. // In short, single label domain suffix is ignored due to the size optimization, so no isIcann
  4. // import tldts from 'tldts-experimental';
  5. import tldts from 'tldts';
  6. import type { NodeFetchResponse } from './make-fetch-happen';
  7. import type { UndiciResponseData } from './fetch-retry';
  8. import type { Response } from 'undici';
  9. function isDomainLoose(domain: string): boolean {
  10. const r = tldts.parse(domain);
  11. return !!(!r.isIp && (r.isIcann || r.isPrivate));
  12. }
  13. export function extractDomainsFromFelixDnsmasq(line: string): string | null {
  14. if (line.startsWith('server=/') && line.endsWith('/114.114.114.114')) {
  15. return line.slice(8, -16);
  16. }
  17. return null;
  18. }
  19. export async function parseFelixDnsmasqFromResp(resp: NodeFetchResponse | UndiciResponseData | Response): Promise<string[]> {
  20. const results: string[] = [];
  21. for await (const line of createReadlineInterfaceFromResponse(resp, true)) {
  22. const domain = extractDomainsFromFelixDnsmasq(line);
  23. if (domain && isDomainLoose(domain)) {
  24. results.push(domain);
  25. }
  26. }
  27. return results;
  28. }