import type MarkdownIt from "markdown-it"; export function addAiRef(href: string, enabled = false): string { if (!enabled || href.startsWith("#")) return href; try { const url = new URL(href, window.location.href); if (url.protocol !== "http:" && url.protocol !== "https:") return href; url.searchParams.set("ref", "ai"); return url.href; } catch { return href; } } export function aiLinkReferences(markdown: MarkdownIt): void { const renderLink = markdown.renderer.rules.link_open; markdown.renderer.rules.link_open = ( tokens, index, options, env, renderer, ) => { const token = tokens[index]; const href = token.attrGet("href"); if (href) token.attrSet("href", addAiRef(href, env?.addAiRef)); return renderLink ? renderLink(tokens, index, options, env, renderer) : renderer.renderToken(tokens, index, options); }; }