normalize-domain.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. // https://github.com/remusao/tldts/issues/2121
  2. // In short, single label domain suffix is ignored due to the size optimization, so no isIcann
  3. // import tldts from 'tldts-experimental';
  4. import tldts from 'tldts';
  5. import { normalizeTldtsOpt } from '../constants/loose-tldts-opt';
  6. type TldTsParsed = ReturnType<typeof tldts.parse>;
  7. export function normalizeDomain(domain: string, parsed: TldTsParsed | null = null) {
  8. if (domain.length === 0) return null;
  9. parsed ??= tldts.parse(domain, normalizeTldtsOpt);
  10. if (parsed.isIp) return null;
  11. let h = parsed.hostname;
  12. if (h === null) return null;
  13. // Private invalid domain (things like .tor, .dn42, etc)
  14. if (!parsed.isIcann && !parsed.isPrivate) return null;
  15. let sliceStart = 0;
  16. let sliceEnd = 0;
  17. if (h[0] === '.') sliceStart = 1;
  18. // eslint-disable-next-line sukka/string/prefer-string-starts-ends-with -- performance
  19. if (h[h.length - 1] === '.') sliceEnd = -1;
  20. if (sliceStart !== 0 || sliceEnd !== 0) {
  21. h = h.slice(sliceStart, sliceEnd);
  22. }
  23. return h.length > 0 ? h : null;
  24. }