1 import path from "path"
2 import { getFrontMatterFromString, getFileSlugSync } from "docs-utils"
3
4 export type FixLinkOptions = {
5 currentPageFilePath: string
6 linkedPath: string
7 appsPath: string
8 r2BaseUrl?: string
9 }
10
11 export async function fixLinkUtil({
12 currentPageFilePath,
13 linkedPath,
14 appsPath: basePath,
15 r2BaseUrl,
16 }: FixLinkOptions) {
17 let fullLinkedFilePath = path.resolve(currentPageFilePath, linkedPath)
18 // persist hash in new URL
19 const hash = fullLinkedFilePath.includes("#")
20 ? fullLinkedFilePath.substring(fullLinkedFilePath.indexOf("#"))
21 : ""
22 fullLinkedFilePath = fullLinkedFilePath.replace(hash, "")
23 // get absolute path of the URL
24 const linkedFilePath = fullLinkedFilePath.replace(basePath, "")
25 let linkedFileSlug: string | undefined
26 try {
27 if (r2BaseUrl) {
28 const res = await fetch(`${r2BaseUrl}${linkedFilePath}`)
29 if (res.ok) {
30 linkedFileSlug = (await getFrontMatterFromString(await res.text()))?.slug
31 }
32 } else {
33 linkedFileSlug = getFileSlugSync(fullLinkedFilePath)
34 }
35 } catch {
36 // fetch failed — fall back to path-based URL
37 }
38
39 const newLink =
40 linkedFileSlug ||
41 linkedFilePath.substring(
42 0,
43 linkedFilePath.indexOf(`/${path.basename(linkedFilePath)}`)
44 )
45
46 return `${newLink}${hash}`
47 }