Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

verify-links.ts

132 lines3.6 KB

1import { existsSync, readFileSync, statSync } from 'node:fs'
2import { extname, resolve } from 'node:path'
3import { glob } from 'tinyglobby'
4// @ts-ignore Could not find a declaration file for module 'markdown-link-extractor'.
5import markdownLinkExtractor from 'markdown-link-extractor'
6​
7const errors: Array<{
8 file: string
9 link: string
10 resolvedPath: string
11 reason: string
12}> = []
13​
14function isRelativeLink(link: string) {
15 return (
16 !link.startsWith('/') &&
17 !link.startsWith('http://') &&
18 !link.startsWith('https://') &&
19 !link.startsWith('//') &&
20 !link.startsWith('#') &&
21 !link.startsWith('mailto:')
22 )
24​
25/** Remove any trailing .md */
26function stripExtension(p: string): string {
27 return p.replace(`${extname(p)}`, '')
29​
30function relativeLinkExists(link: string, file: string): boolean {
31 // Remove hash if present
32 const linkWithoutHash = link.split('#')[0]
33 // If the link is empty after removing hash, it's not a file
34 if (!linkWithoutHash) return false
35​
36 // Strip the file/link extensions
37 const filePath = stripExtension(file)
38 const linkPath = stripExtension(linkWithoutHash)
39​
40 // Resolve the path relative to the markdown file's directory
41 // Nav up a level to simulate how links are resolved on the web
42 let absPath = resolve(filePath, '..', linkPath)
43​
44 // Ensure the resolved path is within /docs
45 const docsRoot = resolve('docs')
46 if (!absPath.startsWith(docsRoot)) {
47 errors.push({
48 link,
49 file,
50 resolvedPath: absPath,
51 reason: 'Path outside /docs',
52 })
53 return false
54 }
55​
56 // The API reference (docs/reference/**) is TypeDoc-generated at build time
57 // and not committed, so its targets can't be resolved here. These are valid
58 // routes on the built site; skip them rather than flagging false positives.
59 if (absPath.startsWith(resolve(docsRoot, 'reference'))) {
60 return true
61 }
62​
63 // Check if this is an example path
64 const isExample = absPath.includes('/examples/')
65​
66 let exists = false
67​
68 if (isExample) {
69 // Transform /docs/framework/{framework}/examples/ to /examples/{framework}/
70 absPath = absPath.replace(
71 /\/docs\/framework\/([^/]+)\/examples\//,
72 '/examples/$1/',
73 )
74 // For examples, we want to check if the directory exists
75 exists = existsSync(absPath) && statSync(absPath).isDirectory()
76 } else {
77 // For non-examples, we want to check if the .md file exists
78 if (!absPath.endsWith('.md')) {
79 absPath = `${absPath}.md`
80 }
81 exists = existsSync(absPath)
82 }
83​
84 if (!exists) {
85 errors.push({
86 link,
87 file,
88 resolvedPath: absPath,
89 reason: 'Not found',
90 })
91 }
92 return exists
94​
95async function verifyMarkdownLinks() {
96 // Find all markdown files in docs directory
97 const markdownFiles = await glob('docs/**/*.md', {
98 ignore: ['**/node_modules/**'],
99 })
100​
101 console.log(`Found ${markdownFiles.length} markdown files\n`)
102​
103 // Process each file
104 for (const file of markdownFiles) {
105 const content = readFileSync(file, 'utf-8')
106 const links: Array<string> = markdownLinkExtractor(content)
107​
108 const relativeLinks = links.filter((link: string) => {
109 return isRelativeLink(link)
110 })
111​
112 if (relativeLinks.length > 0) {
113 relativeLinks.forEach((link) => {
114 relativeLinkExists(link, file)
115 })
116 }
117 }
118​
119 if (errors.length > 0) {
120 console.log(`\n❌ Found ${errors.length} broken links:`)
121 errors.forEach((err) => {
122 console.log(
123 `${err.file}\n link: ${err.link}\n resolved: ${err.resolvedPath}\n why: ${err.reason}\n`,
124 )
125 })
126 process.exit(1)
127 } else {
128 console.log('\n✅ No broken links found!')
129 }
131​
132verifyMarkdownLinks().catch(console.error)