-
Notifications
You must be signed in to change notification settings - Fork 7.9k
Expand file tree
/
Copy path[...path].ts
More file actions
104 lines (83 loc) · 2.58 KB
/
[...path].ts
File metadata and controls
104 lines (83 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {NextApiRequest, NextApiResponse} from 'next';
import fs from 'fs';
import path from 'path';
import remark from 'remark';
import visit from 'unist-util-visit';
const CONTENT_ROOT = path.join(process.cwd(), 'src/content');
const NOOP_ORIGIN = 'https://noop';
const FOOTER = `
---
## Sitemap
[Overview of all docs pages](/llms.txt)
`;
function rewriteInternalLinks(markdown: string): string {
const processor = remark().use(() => (tree) => {
visit(tree, 'link', (node: unknown) => {
if (typeof node !== 'object' || node === null || !('url' in node)) {
return;
}
if (typeof node.url !== 'string') {
return;
}
if (!node.url.startsWith('/')) {
return;
}
let url: URL;
try {
url = new URL(node.url, NOOP_ORIGIN);
} catch {
return;
}
const pathname = url.pathname;
// Skip links that already have a file extension (e.g. .png, .svg)
if (/\.\w+$/.test(pathname)) {
return;
}
url.pathname = pathname.endsWith('/')
? `${pathname.slice(0, -1)}.md`
: `${pathname}.md`;
node.url = url.toString().replace(NOOP_ORIGIN, '');
});
});
return processor.processSync(markdown).toString();
}
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const pathSegments = req.query.path;
if (!pathSegments) {
return res.status(404).send('Not found');
}
const filePath = Array.isArray(pathSegments)
? pathSegments.join('/')
: pathSegments;
// Block /index.md URLs - use /foo.md instead of /foo/index.md
if (filePath.endsWith('/index') || filePath === 'index') {
return res.status(404).send('Not found');
}
// Try exact path first, then with /index
const candidates = [
path.join(CONTENT_ROOT, filePath + '.md'),
path.join(CONTENT_ROOT, filePath, 'index.md'),
];
for (const candidate of candidates) {
const fullPath = path.resolve(candidate);
if (!fullPath.startsWith(CONTENT_ROOT + path.sep)) {
continue;
}
try {
const raw = fs.readFileSync(fullPath, 'utf8');
const content = rewriteInternalLinks(raw);
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Cache-Control', 'public, max-age=3600');
return res.status(200).send(content + FOOTER);
} catch {
// Try next candidate
}
}
res.status(404).send('Not found');
}