diff --git a/astro.config.ts b/astro.config.ts index fcf13e786ff74b6..7f194d4ab2f643e 100644 --- a/astro.config.ts +++ b/astro.config.ts @@ -14,6 +14,7 @@ import rehypeMermaid from "./src/plugins/rehype/mermaid.ts"; import rehypeAutolinkHeadings from "./src/plugins/rehype/autolink-headings.ts"; import rehypeExternalLinks from "./src/plugins/rehype/external-links.ts"; import rehypeHeadingSlugs from "./src/plugins/rehype/heading-slugs.ts"; +import rehypeRewriteUrls from "./src/plugins/rehype/rewrite-urls.ts"; import { sidebar } from "./src/util/sidebar.ts"; @@ -31,6 +32,7 @@ export default defineConfig({ rehypeAutolinkHeadings, // @ts-expect-error plugins types are outdated but functional rehypeTitleFigure, + rehypeRewriteUrls, ], }, experimental: { diff --git a/src/plugins/rehype/rewrite-urls.ts b/src/plugins/rehype/rewrite-urls.ts new file mode 100644 index 000000000000000..a63e35997a4582d --- /dev/null +++ b/src/plugins/rehype/rewrite-urls.ts @@ -0,0 +1,22 @@ +import config from "../../../astro.config.ts"; +import { visit } from "unist-util-visit"; +import type { Root } from "hast"; + +// Rewrite relative /api/ links to be absolute, using the `site` base from the Astro config. +export default function () { + return function (tree: Root) { + visit(tree, "element", function (element) { + if (element.tagName === "a") { + if (element.properties.href) { + const url = new URL(element.properties.href as string, config.site); + + if (url.origin === config.site) { + if (url.pathname.startsWith("/api/")) { + element.properties.href = url.toString(); + } + } + } + } + }); + }; +}