OverviewFilesCommitsIssuesDocsReleasesPeers

keet-deobfuscated / @holepunchto / keet-link-preview / index.js

54 lines · javascript ref:
import t from "fast-meta-tags"
import { getFile as n, getDomain as e, htmlToText as i } from "./utils.js"
import { fetchOembed as r } from "./oembed.js"
export default async function o(i, o) {
  i.startsWith("http://") && (i = "https" + i.slice(4))
  const [a, c] = await Promise.all([r(i, o), t(i, o)])
  if (!a && !c) return null
  const s = a?.image || (c ? m(c) : null),
    u = c ? l({ ...c, image: s }) : {}
  return {
    url: i,
    favicon: c?.favicon || null,
    title: a?.title || u.title || null,
    name: a?.name || u.name || e(i),
    description: a?.description || u.description || null,
    file: await n(s, o),
  }
}
function l(t) {
  return { url: t.url, favicon: t.favicon, title: c(t), name: a(t), description: s(t) }
}
function a(t) {
  return u(t.meta, { name: "og:site_name", property: "og:site_name" }) || e(t.url)
}
function c(t) {
  return u(t.meta, { name: "og:title", property: "og:title" }) || t.title
}
function s(t) {
  const n = u(t.meta, { name: "description", property: "og:description" })
  if (n) {
    const t = i(n)
    return t && t.length > 500 ? t.slice(0, 500) : t
  }
  if (!t.image && t.html) {
    const n = t.html.match(/<p(\s[^>]*)?>.*?<\/p>/gis) || []
    for (const t of n) {
      const n = i(t)
      if (n && n.length > 100) return n.length > 500 ? n.slice(0, 500) : n
    }
  }
  return null
}
function m(t) {
  return u(t.meta, { name: "og:image", property: "og:image" })
}
function u(t, n) {
  const e = Object.entries(n)
  return (
    t.find((t) => {
      for (const [n, i] of e) if (t[n] === i) return !0
    })?.content || null
  )
}