|
| 1 | +// Rewrites absolute internal links (e.g. "/start/quickstart/") in markdown |
| 2 | +// and MDX content to be prefixed with the configured site base, so that |
| 3 | +// hosting under a subpath like /simpledeploy/ does not produce 404s. |
| 4 | +// |
| 5 | +// Skips: external URLs, protocol-relative URLs, fragment-only links, |
| 6 | +// already-prefixed paths, and asset paths Astro handles itself (_astro, etc). |
| 7 | + |
| 8 | +const DEFAULT_SKIP_PREFIXES = ["/_astro/", "/@", "/api/"]; |
| 9 | + |
| 10 | +function shouldRewrite(url, base) { |
| 11 | + if (typeof url !== "string" || url.length === 0) return false; |
| 12 | + if (!url.startsWith("/")) return false; |
| 13 | + if (url.startsWith("//")) return false; |
| 14 | + if (url.startsWith(base + "/") || url === base) return false; |
| 15 | + for (const p of DEFAULT_SKIP_PREFIXES) if (url.startsWith(p)) return false; |
| 16 | + return true; |
| 17 | +} |
| 18 | + |
| 19 | +function rewrite(url, base) { |
| 20 | + return base + url; |
| 21 | +} |
| 22 | + |
| 23 | +function visitNode(node, base) { |
| 24 | + if (!node || typeof node !== "object") return; |
| 25 | + |
| 26 | + if ((node.type === "link" || node.type === "image") && shouldRewrite(node.url, base)) { |
| 27 | + node.url = rewrite(node.url, base); |
| 28 | + } |
| 29 | + |
| 30 | + if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") { |
| 31 | + if (Array.isArray(node.attributes)) { |
| 32 | + for (const attr of node.attributes) { |
| 33 | + if ( |
| 34 | + attr && |
| 35 | + attr.type === "mdxJsxAttribute" && |
| 36 | + (attr.name === "href" || attr.name === "src" || attr.name === "link") && |
| 37 | + typeof attr.value === "string" && |
| 38 | + shouldRewrite(attr.value, base) |
| 39 | + ) { |
| 40 | + attr.value = rewrite(attr.value, base); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + if (Array.isArray(node.children)) { |
| 47 | + for (const child of node.children) visitNode(child, base); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +export default function remarkPrefixBase(options = {}) { |
| 52 | + const base = (options.base || "").replace(/\/$/, ""); |
| 53 | + if (!base) return () => {}; |
| 54 | + return (tree) => { |
| 55 | + visitNode(tree, base); |
| 56 | + }; |
| 57 | +} |
0 commit comments