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

verify-links.ts

130 lines3.6 KB

1import { existsSync, readFileSync, statSync } from 'node:fs'
2import { extname, resolve, sep } 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 // `resolve` uses the platform separator, but the patterns below are written
57 // with forward slashes, so match against a normalized copy of the path.
58 // Node accepts forward slashes on Windows too, so the result stays usable.
59 absPath = absPath.split(sep).join('/')
60​
61 // Check if this is an example path
62 const isExample = absPath.includes('/examples/')
63​
64 let exists = false
65​
66 if (isExample) {
67 // Transform /docs/framework/{framework}/examples/ to /examples/{framework}/
68 absPath = absPath.replace(
69 /\/docs\/framework\/([^/]+)\/examples\//,
70 '/examples/$1/',
71 )
72 // For examples, we want to check if the directory exists
73 exists = existsSync(absPath) && statSync(absPath).isDirectory()
74 } else {
75 // For non-examples, we want to check if the .md file exists
76 if (!absPath.endsWith('.md')) {
77 absPath = `${absPath}.md`
78 }
79 exists = existsSync(absPath)
80 }
81​
82 if (!exists) {
83 errors.push({
84 link,
85 file,
86 resolvedPath: absPath,
87 reason: 'Not found',
88 })
89 }
90 return exists
92​
93async function verifyMarkdownLinks() {
94 // Find all markdown files in docs directory
95 const markdownFiles = await glob('docs/**/*.md', {
96 ignore: ['**/node_modules/**'],
97 })
98​
99 console.log(`Found ${markdownFiles.length} markdown files\n`)
100​
101 // Process each file
102 for (const file of markdownFiles) {
103 const content = readFileSync(file, 'utf-8')
104 const links: Array<string> = markdownLinkExtractor(content)
105​
106 const relativeLinks = links.filter((link: string) => {
107 return isRelativeLink(link)
108 })
109​
110 if (relativeLinks.length > 0) {
111 relativeLinks.forEach((link) => {
112 relativeLinkExists(link, file)
113 })
114 }
115 }
116​
117 if (errors.length > 0) {
118 console.log(`\n❌ Found ${errors.length} broken links:`)
119 errors.forEach((err) => {
120 console.log(
121 `${err.file}\n link: ${err.link}\n resolved: ${err.resolvedPath}\n why: ${err.reason}\n`,
122 )
123 })
124 process.exit(1)
125 } else {
126 console.log('\nβœ… No broken links found!')
127 }
129​
130verifyMarkdownLinks().catch(console.error)