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

verify-links.ts

132 lines3.5 KB

1import { existsSync, readFileSync, statSync } from 'node:fs'
2import path, { 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​
7function isRelativeLink(link: string) {
8 return (
9 link &&
10 !link.startsWith('http://') &&
11 !link.startsWith('https://') &&
12 !link.startsWith('//') &&
13 !link.startsWith('#') &&
14 !link.startsWith('mailto:')
15 )
17​
18function normalizePath(p: string): string {
19 // Remove any trailing .md
20 p = p.replace(`${path.extname(p)}`, '')
21 return p
23​
24function fileExistsForLink(
25 link: string,
26 markdownFile: string,
27 errors: Array<any>,
28): boolean {
29 // Remove hash if present
30 const filePart = link.split('#')[0]
31 // If the link is empty after removing hash, it's not a file
32 if (!filePart) return false
33​
34 // Normalize the markdown file path
35 markdownFile = normalizePath(markdownFile)
36​
37 // Normalize the path
38 const normalizedPath = normalizePath(filePart)
39​
40 // Resolve the path relative to the markdown file's directory
41 let absPath = resolve(markdownFile, normalizedPath)
42​
43 // Ensure the resolved path is within /docs
44 const docsRoot = resolve('docs')
45 if (!absPath.startsWith(docsRoot)) {
46 errors.push({
47 link,
48 markdownFile,
49 resolvedPath: absPath,
50 reason: 'navigates above /docs, invalid',
51 })
52 return false
53 }
54​
55 // Check if this is an example path
56 const isExample = absPath.includes('/examples/')
57​
58 let exists = false
59​
60 if (isExample) {
61 // Transform /docs/framework/{framework}/examples/ to /examples/{framework}/
62 absPath = absPath.replace(
63 /\/docs\/framework\/([^/]+)\/examples\//,
64 '/examples/$1/',
65 )
66 // For examples, we want to check if the directory exists
67 exists = existsSync(absPath) && statSync(absPath).isDirectory()
68 } else {
69 // For non-examples, we want to check if the .md file exists
70 if (!absPath.endsWith('.md')) {
71 absPath = `${absPath}.md`
72 }
73 exists = existsSync(absPath)
74 }
75​
76 if (!exists) {
77 errors.push({
78 link,
79 markdownFile,
80 resolvedPath: absPath,
81 reason: 'not found',
82 })
83 }
84 return exists
86​
87async function findMarkdownLinks() {
88 // Find all markdown files in docs directory
89 const markdownFiles = await glob('docs/**/*.md', {
90 ignore: ['**/node_modules/**'],
91 })
92​
93 console.log(`Found ${markdownFiles.length} markdown files\n`)
94​
95 const errors: Array<any> = []
96​
97 // Process each file
98 for (const file of markdownFiles) {
99 const content = readFileSync(file, 'utf-8')
100 const links: Array<any> = markdownLinkExtractor(content)
101​
102 const filteredLinks = links.filter((link: any) => {
103 if (typeof link === 'string') {
104 return isRelativeLink(link)
105 } else if (link && typeof link.href === 'string') {
106 return isRelativeLink(link.href)
107 }
108 return false
109 })
110​
111 if (filteredLinks.length > 0) {
112 filteredLinks.forEach((link) => {
113 const href = typeof link === 'string' ? link : link.href
114 fileExistsForLink(href, file, errors)
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.link}\n in: ${err.markdownFile}\n path: ${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​
132findMarkdownLinks().catch(console.error)