|
1
|
import { workerCompatibleFetch } from "docs-utils" |
|
2
|
import path from "path" |
|
3
|
import { loadReferenceFromBinding } from "./load-reference-from-binding" |
|
4
|
import { fetchFromAssetsBinding } from "./fetch-from-assets-binding" |
|
5
|
|
|
6
|
export async function fetchMdxContent( |
|
7
|
baseUrl: string, |
|
8
|
filePathFromMap: string |
|
9
|
): Promise<string | null> { |
|
10
|
const isCloudflare = !!process.env.CLOUDFLARE_ENV |
|
11
|
// References files come from R2, so we need to fetch them directly from R2 instead of going through the app route |
|
12
|
if (filePathFromMap.includes("/references/")) { |
|
13
|
const r2Base = process.env.REFERENCES_R2_BASE_URL |
|
14
|
const relPath = filePathFromMap.replace(/^.*\/references\//, "") |
|
15
|
return ( |
|
16
|
(await loadReferenceFromBinding(`resources/references/${relPath}`)) ?? |
|
17
|
(await workerCompatibleFetch<string | null>({ |
|
18
|
url: `${r2Base}/references/${relPath}`, |
|
19
|
responseTransformer: async (res) => { |
|
20
|
return res.ok ? res.text() : null |
|
21
|
}, |
|
22
|
fallbackAction: async () => { |
|
23
|
try { |
|
24
|
const { promises: fs } = await import("fs") |
|
25
|
const relPath = filePathFromMap.replace(/^.*\/references\//, "") |
|
26
|
return await fs.readFile( |
|
27
|
path.join(process.cwd(), "references", relPath), |
|
28
|
"utf-8" |
|
29
|
) |
|
30
|
} catch { |
|
31
|
return null |
|
32
|
} |
|
33
|
}, |
|
34
|
useRemote: isCloudflare, |
|
35
|
})) |
|
36
|
) |
|
37
|
} |
|
38
|
|
|
39
|
// app/ pages: derive app-relative path and use workerCompatibleFetch |
|
40
|
const relPath = filePathFromMap.replace(/^.*\/app\//, "") |
|
41
|
const rawMdxUrl = `${baseUrl}/raw-mdx/${relPath}` |
|
42
|
return ( |
|
43
|
(await fetchFromAssetsBinding(rawMdxUrl)) ?? |
|
44
|
(await workerCompatibleFetch<string | null>({ |
|
45
|
url: rawMdxUrl, |
|
46
|
responseTransformer: async (res) => { |
|
47
|
return res.ok ? res.text() : null |
|
48
|
}, |
|
49
|
fallbackAction: async () => { |
|
50
|
try { |
|
51
|
const { promises: fs } = await import("fs") |
|
52
|
return await fs.readFile( |
|
53
|
path.join(process.cwd(), "app", relPath), |
|
54
|
"utf-8" |
|
55
|
) |
|
56
|
} catch { |
|
57
|
return null |
|
58
|
} |
|
59
|
}, |
|
60
|
useRemote: isCloudflare, |
|
61
|
})) |
|
62
|
) |
|
63
|
} |