Skip to content

Full Toolkit for Next-Level Domain Analysis

4.4 KB
Raw Blame
import { type ClassValue, clsx } from 'clsx';
import { log } from 'evlog';
import { twMerge } from 'tailwind-merge';
import { getDomain, parse as tldtsParse } from 'tldts';

export const DOMAIN_REGEX = /([a-zA-Z0-9-_]+\.)+[a-z]+\.?/gi;
const DOMAIN_LABEL_REGEX =
  /^(?:xn--|_)?[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;
export const IPV4_REGEX =
  /(?<!\w)(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/g;
export const IPV6_REGEX =
  /(?<!\w)((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?/gi;

export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs));

export const deduplicate = <T>(array: T[]): T[] => Array.from(new Set(array));

// evlog JSON-stringifies events in production, which drops an Error's own fields, cause included.
export const serializeError = (error: unknown) => {
  const err = error instanceof Error ? error : new Error(String(error));

  return {
    name: err.name,
    message: err.message,
    stack: err.stack,
    cause: (err.cause as Error | undefined)?.message,
  };
};

// From https://stackoverflow.com/a/30471209/12475254
// onError sees every failed attempt, the last one included. It runs inside the
// existing catch, so observing attempts doesn't delay when the result settles.
export const retry = <T extends Function>(
  fn: T,
  maxRetries: number,
  onError?: (err: Error) => void,
) =>
  fn().catch((err: Error) => {
    onError?.(err);
    if (maxRetries <= 0) {
      throw err;
    }
    log.warn({
      message: 'retrying_after_error',
      error: err.message?.toString(),
    });
    return retry(fn, maxRetries - 1, onError);
  });

// ABased on https://en.wikipedia.org/wiki/Domain_name#Domain_name_syntax
export const isValidDomain = (domain: string) => {
  if (typeof domain !== 'string') {
    if (process?.env.VITEST !== 'true') {
      log.warn({
        message: 'invalid_domain_input_type',
        receivedType: typeof domain,
        received: domain,
      });
    }
    return false;
  }

  // Check total length (maximum 253 characters)
  if (domain.length > 253 || domain.length === 0) return false;

  // Remove wildcard prefix and trailing dot (if fully qualified domain name)
  const cleanedDomain = domain.replace(/^\*\./, '').replace(/\.$/, '');

  // Split domain into labels
  const labels = cleanedDomain.split('.');

  for (const label of labels) {
    // Check label length (between 1 and 63 characters)
    if (label.length < 1 || label.length > 63) {
      return false;
    }

    // Check if label matches the regular expression
    if (!DOMAIN_LABEL_REGEX.test(label)) {
      return false;
    }
  }

  try {
    const result = tldtsParse(cleanedDomain);
    return Boolean(result.isIcann || result.isPrivate);
  } catch (error) {
    return false;
  }
};

/**
 * Extracts the base domain from a given domain
 *
 * Example: www.example.com -> example.com
 */
export const getBaseDomain = (domain: string) => {
  // Remove wildcard prefix to avoid base domain not being extracted correctly
  // Remove trailing dot
  const cleanedDomain = domain
    .replace(/^\*\./, '')
    .replace(/\.$/, '')
    .toLowerCase();
  return getDomain(cleanedDomain) || cleanedDomain;
};

export const isWildcardDomain = (domain: string) =>
  domain.startsWith('*.') && domain.length > 2;

export const isAppleDevice = () => {
  if (typeof window === 'undefined') return false;
  const userAgent = window.navigator.userAgent;
  return /Mac|iPad|iPhone|iPod/.test(userAgent);
};