Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

5.9 KB
Raw Blame
export const isValidUrl = (url: string) => {
  try {
    new URL(url);
    return true;
  } catch (e) {
    return false;
  }
};

export function safeDecodeURIComponent(value: string): string {
  try {
    return decodeURIComponent(value);
  } catch {
    return value;
  }
}

const SAFE_LINK_SCHEMES = new Set(["http:", "https:", "mailto:"]);

export function isSafeLinkHref(
  href: string | null | undefined,
): href is string {
  if (!href) {
    return false;
  }

  try {
    return SAFE_LINK_SCHEMES.has(new URL(href).protocol);
  } catch {
    return false;
  }
}

export const getUrlFromString = (str: string) => {
  if (isValidUrl(str)) return str;
  try {
    if (str.includes(".") && !str.includes(" ")) {
      return new URL(`https://${str}`).toString();
    }
  } catch (_) {}
  return str;
};

export const getUrlObjFromString = (str: string) => {
  if (isValidUrl(str)) return new URL(str);
  try {
    if (str.includes(".") && !str.includes(" ")) {
      return new URL(`https://${str}`);
    }
  } catch (_) {}
  return null;
};

export const getUrlFromStringIfValid = (str: string) => {
  if (isValidUrl(str)) return str;
  try {
    if (str.includes(".") && !str.includes(" ")) {
      return new URL(`https://${str}`).toString();
    }
  } catch (_) {}
  return null;
};

export const getSearchParams = (url: string) => {
  // Create a params object
  let params = {} as Record<string, string>;

  new URL(url).searchParams.forEach(function (val, key) {
    params[key] = val;
  });

  return params;
};

export const getSearchParamsWithArray = (url: string) => {
  let params = {} as Record<string, string | string[]>;

  new URL(url).searchParams.forEach(function (val, key) {
    if (key in params) {
      const param = params[key];
      Array.isArray(param) ? param.push(val) : (params[key] = [param, val]);
    } else {
      params[key] = val;
    }
  });

  return params;
};

export const getParamsFromURL = (url: string) => {
  if (!url) return {};
  try {
    const params = new URL(url).searchParams;
    const paramsObj: Record<string, string> = {};
    for (const [key, value] of params.entries()) {
      if (value && value !== "") {
        paramsObj[key] = value;
      }
    }
    return paramsObj;
  } catch (e) {
    return {};
  }
};

export const UTMTags = [
  "utm_source",
  "utm_medium",
  "utm_campaign",
  "utm_term",
  "utm_content",
  "ref",
] as const;

export const constructURLFromUTMParams = (
  url: string,
  utmParams: Record<string, string | null>,
) => {
  if (!url) return "";
  try {
    const newURL = new URL(url);
    for (const [key, value] of Object.entries(utmParams)) {
      if (!value) {
        newURL.searchParams.delete(key);
      } else {
        newURL.searchParams.set(key, value.replace("+", " "));
      }
    }
    return newURL.toString();
  } catch (e) {
    return "";
  }
};

export const paramsMetadata = [
  { display: "UTM Source", key: "utm_source", examples: "google, twitter" },
  { display: "UTM Medium", key: "utm_medium", examples: "social, email" },
  { display: "UTM Campaign", key: "utm_campaign", examples: "summer sale" },
  { display: "UTM Term", key: "utm_term", examples: "blue shoes" },
  { display: "UTM Content", key: "utm_content", examples: "logo link" },
  { display: "Referral (ref)", key: "ref", examples: "google, twitter" },
];

export const getUTMParamsFromURL = (url: string) => {
  return Object.fromEntries(
    Object.entries(getParamsFromURL(url)).filter(([key]) =>
      UTMTags.includes(key as (typeof UTMTags)[number]),
    ),
  );
};

export const getUrlWithoutUTMParams = (url: string) => {
  try {
    const newURL = new URL(url);
    paramsMetadata.forEach((param) => newURL.searchParams.delete(param.key));
    return newURL.toString();
  } catch (e) {
    return url;
  }
};

export const getPrettyUrl = (url?: string | null) => {
  if (!url) return "";
  // remove protocol (http/https) and www.
  // also remove trailing slash
  return url
    .replace(/(^\w+:|^)\/\//, "")
    .replace("www.", "")
    .replace(/\/$/, "");
};

export const createHref = (
  href: string,
  domain: string,
  // any params, doesn't have to be all of them
  utmParams?: Partial<Record<(typeof UTMTags)[number], string>>,
) => {
  if (domain === "dub.co") return href;
  const url = new URL(href.startsWith("/") ? `https://dub.co${href}` : href);
  if (utmParams) {
    Object.entries(utmParams).forEach(([key, value]) => {
      url.searchParams.set(key, value);
    });
  }
  return url.toString();
};

export const getPathnameFromUrl = (url: string) => {
  try {
    const u = new URL(url, "https://dummy-base.local");

    // Keep ?query intact
    let pathname = u.pathname + u.search;

    // Remove leading slash for relative-style URLs
    pathname = pathname.startsWith("/") ? pathname.slice(1) : pathname;

    return pathname;
  } catch (e) {
    return url;
  }
};

// Helper function to normalize URL by removing query params
export const normalizeUrl = (url: string): string => {
  try {
    const urlObj = new URL(url);
    return `https://${urlObj.hostname}${urlObj.pathname}`;
  } catch {
    return url;
  }
};

export function buildUrl(
  baseUrl: string,
  params?: Record<string, string | number | boolean | null | undefined>,
) {
  const url = new URL(
    baseUrl,
    typeof window !== "undefined" ? window.location.origin : "http://localhost",
  );

  if (params) {
    Object.entries(params).forEach(([key, value]) => {
      if (value !== null && value !== undefined && value !== "") {
        url.searchParams.append(key, String(value));
      }
    });
  }

  return url.toString();
}

export const getFileExtension = (url: string): string | null => {
  try {
    const pathname = new URL(url).pathname;
    const extension = pathname.split(".").pop();
    return extension ? extension.toUpperCase() : null;
  } catch {
    // If URL parsing fails, try to extract from the string directly
    const extension = url.split(".").pop()?.split("?")[0];
    return extension ? extension.toUpperCase() : null;
  }
};