OverviewFilesCommitsIssuesDocsReleasesPeers

keet-deobfuscated / @holepunchto / keet-editor / src / extensions / helpers / urls.js

51 lines · javascript ref:
import { TLDS_PLAIN_DOMAIN_ALLOWED as t } from "../../constants.js"
export function isValidUrl(t) {
  return /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi.test(
    t,
  )
}
export function isPartialUrl(t) {
  return /^https?:\/\/.+/i.test(t)
}
export function normalizeUrl(t) {
  try {
    return new URL(t).href
  } catch (r) {
    return t
  }
}
export function getUrls(t, r) {
  const n = new Set()
  return (
    (function t(e) {
      if ((e.content && e.content.forEach(t), e.marks))
        for (const t of e.marks)
          if ("link" === t.type) {
            if (t.attrs.href !== e.text)
              if (isValidUrl(e.text)) r(e.text)
              else if (isPartialUrl(e.text)) {
                r(null)
                continue
              }
            isValidUrl(t.attrs.href) && n.add(normalizeUrl(t.attrs.href))
          }
    })(t),
    n
  )
}
export function hasProtocol(t) {
  return /^[a-z][a-z\d+.-]*:/i.test(t)
}
export function isAllowedPlainDomain(r) {
  const n = r
    .trim()
    .replace(/^www\./i, "")
    .split(/[/?#]/, 1)[0]
    .split(":", 1)[0]
    .split(".")
  return !(n.length < 2) && t.has(n.at(-1)?.toLowerCase())
}
export function isAllowedLink(t, r) {
  return !!hasProtocol(t) || isAllowedPlainDomain(t)
}