1import redirects from "./generated/reference-redirects.json";
2
3const referenceRedirects: Record<string, string> = redirects;
4
5/** Shared by the Worker and build output so links and redirects stay in sync. */
6export function referenceDestination(href: string): string | undefined {
7 const url = new URL(href, "https://alchemy.run");
8 let pathname = url.pathname.replace(/\/$/, "");
9 const markdown = pathname.endsWith(".md");
10 if (markdown) pathname = pathname.slice(0, -3);
11 const target = referenceRedirects[pathname];
12 if (!target) return undefined;
13 const [page, resource] = target.split("#");
14 if (markdown) return `${page}.md${url.search}`;
15 const anchor = url.hash ? `${resource}-${url.hash.slice(1)}` : resource;
16 return `${page}${url.search}#${anchor}`;
17}
18
19/** Rewrite authored links without rewriting the hand-maintained guide sources. */
20export function rewriteReferenceLinks(source: string): string {
21 return source.replace(
22 /(?:href=["']|\]\()(\/providers\/[^\s"'<>)]*)/g,
23 (match, href: string) =>
24 match.replace(href, referenceDestination(href) ?? href),
25 );
26}