Files
HMDesign/scripts/check-doc-links.mjs
T

35 lines
2.0 KiB
JavaScript

import fs from 'node:fs'
import path from 'node:path'
import { execFileSync } from 'node:child_process'
const root = process.cwd()
const files = [...new Set(execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], { encoding: 'utf8' }).split('\0'))].filter(file => file.endsWith('.md'))
const stripCode = text => text.replace(/^```[^\n]*\n[\s\S]*?^```[^\n]*$/gm, '')
const slug = text => text.toLowerCase().replace(/`/g, '').replace(/[^\p{Letter}\p{Number}\p{Mark}_\- ]/gu, '').replace(/ /g, '-')
const anchors = file => {
const source = stripCode(fs.readFileSync(file, 'utf8'))
const used = new Map(), result = new Set()
for (const [, heading] of source.matchAll(/^#{1,6}\s+(.+)$/gm)) {
const name = slug(heading.trim()), count = used.get(name) ?? 0
result.add(count ? `${name}-${count}` : name); used.set(name, count + 1)
}
for (const [, name] of source.matchAll(/\b(?:id|name)=["']([^"']+)["']/g)) result.add(name)
return result
}
const problems = []; let internalLinks = 0
for (const file of files) for (const [, raw] of stripCode(fs.readFileSync(file, 'utf8')).matchAll(/!?\[[^\]\n]*\]\(([^)\n]+)\)/g)) {
const href = raw.trim().replace(/^<|>$/g, '')
if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue
internalLinks++
try {
const [target, fragment] = href.split('#')
const resolved = target ? path.resolve(path.dirname(file), decodeURIComponent(target)) : path.resolve(file)
const relative = path.relative(root, resolved).replaceAll('\\', '/')
let reason = relative.startsWith('_local/') || relative === '_local' ? 'local evidence is excluded from Git Clone' : !fs.existsSync(resolved) ? 'missing path' : null
if (!reason && fragment && resolved.endsWith('.md') && !anchors(resolved).has(decodeURIComponent(fragment))) reason = 'missing heading'
if (reason) problems.push({ file, href, reason })
} catch (error) { problems.push({ file, href, reason: error.message }) }
}
console.log(JSON.stringify({ files: files.length, internalLinks, problems }, null, 2))
if (problems.length) process.exitCode = 1