import { parseHTML } from "linkedom";
import { createLogger } from "../logger.js";
const log = createLogger("jsonld");
function extractJsonLd(html) {
  const { document: doc } = parseHTML(html);
  const scripts = doc.querySelectorAll('script[type="application/ld+json"]');
  const results = [];
  for (const script of scripts) {
    try {
      const text = script.textContent?.trim();
      if (!text) continue;
      const parsed = JSON.parse(text);
      if (Array.isArray(parsed)) {
        results.push(...parsed);
      } else if (parsed["@graph"] && Array.isArray(parsed["@graph"])) {
        results.push(...parsed["@graph"]);
      } else {
        results.push(parsed);
      }
    } catch (err) {
      log.warn("Failed to parse JSON-LD block", { error: String(err) });
    }
  }
  return results;
}
function matchJsonLdToSchema(jsonLdBlocks, schema) {
  if (!schema.properties || jsonLdBlocks.length === 0) return {};
  const result = {};
  const flattened = flattenJsonLd(jsonLdBlocks);
  for (const fieldName of Object.keys(schema.properties)) {
    if (flattened[fieldName] !== void 0) {
      result[fieldName] = flattened[fieldName];
    }
  }
  return result;
}
function flattenJsonLd(blocks) {
  const flat = {};
  for (const block of blocks) {
    flattenObject(block, flat);
  }
  return flat;
}
function flattenObject(obj, target) {
  for (const [key, value] of Object.entries(obj)) {
    if (key.startsWith("@")) continue;
    if (!(key in target)) {
      if (typeof value === "object" && value !== null && !Array.isArray(value)) {
        flattenObject(value, target);
      } else {
        target[key] = value;
      }
    }
  }
}
export {
  extractJsonLd,
  matchJsonLdToSchema
};
//# sourceMappingURL=jsonld.js.map