import { parseHTML } from "linkedom";
import { readabilityExtract } from "../readability.js";
import { extractJsonLd } from "../jsonld.js";
const META_DATE_SELECTORS = [
  'meta[property="article:published_time"]',
  'meta[name="article:published_time"]',
  'meta[itemprop="datePublished"]',
  'meta[name="date"]',
  'meta[name="dc.date"]',
  'meta[name="DC.date.issued"]'
];
async function extractNews(html, url) {
  const base = readabilityExtract(html, url);
  if (!base) return null;
  if (!base.metadata.date) {
    const date = findPublishedDate(html);
    if (date) {
      return { ...base, metadata: { ...base.metadata, date } };
    }
  }
  return base;
}
function findPublishedDate(html) {
  if (!html) return void 0;
  let document;
  try {
    ({ document } = parseHTML(html));
  } catch {
    return void 0;
  }
  for (const selector of META_DATE_SELECTORS) {
    const el = document.querySelector(selector);
    const content = el?.getAttribute("content")?.trim();
    if (content && isValidDate(content)) return content;
  }
  const article = document.querySelector("article");
  const root = article ?? document;
  const timeEl = root.querySelector("time[datetime]");
  const datetime = timeEl?.getAttribute("datetime")?.trim();
  if (datetime && isValidDate(datetime)) return datetime;
  try {
    const blocks = extractJsonLd(html);
    for (const block of blocks) {
      const published = block["datePublished"];
      if (typeof published === "string" && isValidDate(published)) {
        return published;
      }
    }
  } catch {
  }
  return void 0;
}
function isValidDate(value) {
  if (!value) return false;
  const parsed = Date.parse(value);
  return !Number.isNaN(parsed);
}
export {
  extractNews
};
//# sourceMappingURL=news.js.map