export function secureArtifactHtml(source) {
  const html = String(source || "").trim()
  if (!html || typeof DOMParser === "undefined") return ""

  const documentNode = new DOMParser().parseFromString(html, "text/html")

  const monitor = documentNode.createElement("script")
  monitor.textContent = `
    (() => {
      const notify = (type, message = "") => {
        window.parent.postMessage({ source: "smart-artifact", type, message: String(message).slice(0, 240) }, "*");
      };
      window.addEventListener("error", (event) => notify("runtime-error", event.message || "界面运行异常"));
      window.addEventListener("unhandledrejection", (event) => notify("runtime-error", event.reason?.message || event.reason || "界面运行异常"));
      window.addEventListener("DOMContentLoaded", () => notify("ready"));
    })();
  `
  documentNode.head.prepend(monitor)

  return `<!doctype html>\n${documentNode.documentElement.outerHTML}`
}
