main
 1import type { RehypePlugin } from "@astrojs/markdown-remark";
 2import { visit } from "unist-util-visit";
 3import { SITE_CONFIG } from "../config";
 4
 5export const rehypeExternalLinks: RehypePlugin =
 6  (options?: { protocols?: string[] }) => (tree) => {
 7    visit(tree, "element", (node) => {
 8      if (node.tagName === "a" && typeof node.properties?.href === "string") {
 9        const href = node.properties.href;
10        const protocol = href.split("://")[0].toLowerCase();
11        const allowedProtocols = options?.protocols || ["http", "https"];
12        if (!allowedProtocols.includes(protocol)) return;
13
14        const siteWithoutProtocol = SITE_CONFIG.website.replace(
15          /^https?:\/\//,
16          "",
17        );
18        const hrefWithoutProtocol = href.split("://")[1] || href;
19        if (hrefWithoutProtocol.startsWith(siteWithoutProtocol)) return;
20
21        node.properties.target = "_blank";
22        node.properties.rel = "noopener noreferrer nofollow";
23      }
24    });
25  };