Open History to see the last commit
1import { existsSync, readFileSync, statSync } from 'node:fs'
2import path, { dirname, 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β
7type LinkError = {
8 link: string
9 reason: string
10 resolvedPath: string
11 source: string
12}
13β
14const docsRoot = resolve('docs')
15const examplesRoot = resolve('examples')
16β
17function isRelativeLink(link: string) {
18 return (
19 link &&
20 !link.startsWith('/') &&
21 !link.startsWith('http://') &&
22 !link.startsWith('https://') &&
23 !link.startsWith('//') &&
24 !link.startsWith('#') &&
25 !link.startsWith('mailto:')
26 )
27}
28β
29function isInside(root: string, target: string) {
30 const relative = path.relative(root, target)
31 return (
32 relative === '' ||
33 (!relative.startsWith('..') && !path.isAbsolute(relative))
34 )
35}
36β
37function stripHashAndQuery(link: string) {
38 return link.split(/[?#]/)[0]
39}
40β
41function examplePathFromRoute(route: string) {
42 const match = route.match(/^framework\/([^/]+)\/examples\/(.+)$/)
43β
44 if (!match) {
45 return null
46 }
47β
48 return resolve(examplesRoot, match[1]!, match[2]!)
49}
50β
51function fileExistsForMarkdownLink(
52 link: string,
53 markdownFile: string,
54 errors: Array<LinkError>,
55): boolean {
56 const filePart = stripHashAndQuery(link)
57β
58 if (!filePart) {
59 return true
60 }
61β
62 let absPath = resolve(dirname(resolve(markdownFile)), filePart)
63β
64 if (!isInside(docsRoot, absPath)) {
65 errors.push({
66 link,
67 reason: 'navigates outside docs',
68 resolvedPath: absPath,
69 source: markdownFile,
70 })
71 return false
72 }
73β
74 const docsRelativePath = path
75 .relative(docsRoot, absPath)
76 .replaceAll(path.sep, '/')
77 const examplePath = examplePathFromRoute(docsRelativePath)
78β
79 if (examplePath) {
80 const exists =
81 existsSync(examplePath) && statSync(examplePath).isDirectory()
82β
83 if (!exists) {
84 errors.push({
85 link,
86 reason: 'example route not found',
87 resolvedPath: examplePath,
88 source: markdownFile,
89 })
90 }
91β
92 return exists
93 }
94β
95 if (!path.extname(absPath)) {
96 absPath = `${absPath}.md`
97 }
98β
99 const exists = existsSync(absPath)
100β
101 if (!exists) {
102 errors.push({
103 link,
104 reason: 'not found',
105 resolvedPath: absPath,
106 source: markdownFile,
107 })
108 }
109β
110 return exists
111}
112β
113function getConfigRoutes(value: unknown, routes = new Set<string>()) {
114 if (Array.isArray(value)) {
115 value.forEach((child) => getConfigRoutes(child, routes))
116 return routes
117 }
118β
119 if (!value || typeof value !== 'object') {
120 return routes
121 }
122β
123 const record = value as Record<string, unknown>
124β
125 if (typeof record.to === 'string') {
126 routes.add(record.to)
127 }
128β
129 Object.values(record).forEach((child) => getConfigRoutes(child, routes))
130β
131 return routes
132}
133β
134function fileExistsForConfigRoute(
135 route: string,
136 errors: Array<LinkError>,
137): boolean {
138 const cleanRoute = stripHashAndQuery(route)
139 .replace(/^\.\//, '')
140 .replace(/\.md$/, '')
141β
142 if (!cleanRoute || cleanRoute.startsWith('http')) {
143 return true
144 }
145β
146 const examplePath = examplePathFromRoute(cleanRoute)
147 const resolvedPath = examplePath ?? resolve(docsRoot, `${cleanRoute}.md`)
148 const exists = examplePath
149 ? existsSync(resolvedPath) && statSync(resolvedPath).isDirectory()
150 : existsSync(resolvedPath)
151β
152 if (!exists) {
153 errors.push({
154 link: route,
155 reason: examplePath ? 'example route not found' : 'docs route not found',
156 resolvedPath,
157 source: 'docs/config.json',
158 })
159 }
160β
161 return exists
162}
163β
164function extractHref(link: unknown) {
165 if (typeof link === 'string') {
166 return link
167 }
168β
169 if (
170 link &&
171 typeof link === 'object' &&
172 'href' in link &&
173 typeof link.href === 'string'
174 ) {
175 return link.href
176 }
177β
178 return null
179}
180β
181async function verifyLinks() {
182 const markdownFiles = await glob('docs/**/*.md', {
183 ignore: ['**/node_modules/**'],
184 })
185β
186 console.log(`Found ${markdownFiles.length} markdown files\n`)
187β
188 const errors: Array<LinkError> = []
189β
190 for (const file of markdownFiles) {
191 const content = readFileSync(file, 'utf-8')
192 const links: Array<unknown> = markdownLinkExtractor(content)
193β
194 links.forEach((link) => {
195 const href = extractHref(link)
196β
197 if (href && isRelativeLink(href)) {
198 fileExistsForMarkdownLink(href, file, errors)
199 }
200 })
201 }
202β
203 const config = JSON.parse(readFileSync('docs/config.json', 'utf-8'))
204 const configRoutes = getConfigRoutes(config)
205β
206 configRoutes.forEach((route) => {
207 fileExistsForConfigRoute(route, errors)
208 })
209β
210 const expectedExampleRoutes = new Set(
211 (await glob('examples/*/*/package.json')).map((packageJson) => {
212 const [, framework, example] = packageJson.split('/')
213 return `framework/${framework}/examples/${example}`
214 }),
215 )
216β
217 expectedExampleRoutes.forEach((route) => {
218 if (!configRoutes.has(route)) {
219 errors.push({
220 link: route,
221 reason: 'example missing from docs config',
222 resolvedPath: resolve('docs/config.json'),
223 source: route.replace(
224 /^framework\/([^/]+)\/examples\/(.+)$/,
225 'examples/$1/$2/package.json',
226 ),
227 })
228 }
229 })
230β
231 if (errors.length > 0) {
232 console.log(`\nFound ${errors.length} broken links or routes:`)
233 errors.forEach((err) => {
234 console.log(
235 `${err.link}\n in: ${err.source}\n path: ${err.resolvedPath}\n why: ${err.reason}\n`,
236 )
237 })
238 process.exit(1)
239 } else {
240 console.log('\nNo broken links or routes found!')
241 }
242}
243β
244verifyLinks().catch(console.error)