verify-md-links.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /**
  2. * Verify that relative Markdown links, images, and definitions resolve — the
  3. * target file must exist AND a `#fragment` onto a Markdown target (including
  4. * a same-file `#anchor`) must name a real heading slug or explicit `<a id>`.
  5. * URL and root-absolute targets are excluded; query strings do not affect
  6. * resolution against the source file. The checker never rewrites, and
  7. * symlinked instruction files are deduped.
  8. */
  9. import { existsSync, readFileSync } from 'node:fs'
  10. import { dirname, relative, resolve } from 'node:path'
  11. import type { Nodes } from 'mdast'
  12. import { markdownHeadingLines, parseMarkdown, visitMarkdown } from './markdown.ts'
  13. import { isArchivedAgentNotePath, uniqueRepoFiles } from './repo-files.ts'
  14. const root = resolve(import.meta.dirname, '..')
  15. /** Repo-authored Markdown checked for relative links. */
  16. const PATTERNS = [
  17. 'README.md',
  18. 'README.zh.md',
  19. '.agents/notes/**/*.md',
  20. 'docs/**/*.md',
  21. 'packages/*.md',
  22. 'packages/*/*.md',
  23. 'packages/*/*/*.md',
  24. 'AGENTS.md',
  25. '.agents/skills/**/*.md',
  26. ]
  27. /**
  28. * Discover authored Markdown sources, deduplicating symlinks.
  29. * Archived notes are excluded as sources, but links to them remain checked.
  30. * @param scanRoot - absolute repository root; pass the same root to findViolations for matching diagnostics.
  31. * @returns forward-slash source paths relative to scanRoot.
  32. */
  33. export function markdownLinkSourcePaths(scanRoot: string = root): string[] {
  34. return uniqueRepoFiles(scanRoot, PATTERNS, isArchivedAgentNotePath)
  35. .map(file => relative(scanRoot, file.abs).replaceAll('\\', '/'))
  36. }
  37. /** A broken relative link: a missing target path or a missing anchor on it. */
  38. interface Violation {
  39. file: string
  40. /** 1-based line where the link/image/definition node starts. */
  41. line: number
  42. url: string
  43. /** What failed: the target file or the fragment onto it. */
  44. reason: 'target' | 'anchor'
  45. }
  46. /**
  47. * True for targets this gate must NOT check: scheme-qualified URLs (`https:`,
  48. * `mailto:`, …), protocol-relative (`//host`), and root-absolute (`/path`).
  49. * Pure in-page anchors (`#frag`) ARE checked, against the source file itself.
  50. */
  51. function isExternal(url: string): boolean {
  52. if (url.startsWith('//')) return true
  53. if (url.startsWith('/')) return true
  54. // A scheme like `https:` / `mailto:` — a colon before any slash, dot, or hash.
  55. return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
  56. }
  57. /**
  58. * Strip the `#fragment` and `?query` from a link target, then percent-decode
  59. * the remaining path so an encoded target (`My%20File.md`, `READ%4DE.md`)
  60. * probes the real filename on disk, the way a Markdown renderer resolves it. A
  61. * malformed escape (`%zz`) makes `decodeURIComponent` throw; we keep the raw
  62. * path in that case so the link is reported as broken (a `%zz` target is not a
  63. * file anyone meant to link) rather than crashing the gate.
  64. */
  65. function pathPart(url: string): string {
  66. const raw = url.replace(/[#?].*$/, '')
  67. try {
  68. return decodeURIComponent(raw)
  69. } catch {
  70. // decodeURIComponent throws only on a malformed percent-escape; the raw
  71. // string is then a path no renderer resolves, so fall through to the
  72. // existence check, which reports it broken.
  73. return raw
  74. }
  75. }
  76. /** The percent-decoded `#fragment` of a link target, or null when it has none. */
  77. function fragmentPart(url: string): string | null {
  78. const hash = url.indexOf('#')
  79. if (hash === -1) return null
  80. const raw = url.slice(hash + 1).replace(/\?.*$/, '')
  81. try {
  82. return decodeURIComponent(raw)
  83. } catch {
  84. // Same stance as pathPart: a malformed escape names no anchor anyone
  85. // meant, so the raw text flows into the lookup and is reported missing.
  86. return raw
  87. }
  88. }
  89. /**
  90. * GitHub's heading-slug algorithm (lowercase; drop everything but letters,
  91. * numbers, underscores, spaces, hyphens; spaces become hyphens). Underscores
  92. * survive (`## Showcase: web_fetch` → `#showcase-web_fetch`), unlike
  93. * `gen-cordis-catalog`'s region-anchor slugs — the generator's headings are
  94. * always reachable through its explicit `<a id>` anchors, so the two need not
  95. * share one rule.
  96. * @param heading - the RENDERED heading text (Markdown syntax already gone).
  97. * @returns the anchor GitHub assigns the first occurrence of the heading.
  98. */
  99. export function githubSlug(heading: string): string {
  100. return heading.toLowerCase().replace(/[^\p{L}\p{N}_ -]/gu, '').replaceAll(' ', '-')
  101. }
  102. /**
  103. * Every anchor one Markdown document exposes: each heading's GitHub slug —
  104. * computed from the RENDERED heading text, so links, images, inline code, and
  105. * emphasis inside a heading slug the way GitHub renders them — plus every
  106. * explicit `<a id="…">` that appears in real HTML flow (a fenced or inline
  107. * code sample and a commented-out anchor register nothing). Repeated slugs
  108. * get GitHub's occupied-set `-1`, `-2`, … suffixes: each collision bumps the
  109. * ORIGINAL slug's counter until a free name is found, so `Repeat`, `Repeat-1`,
  110. * `Repeat` yields `repeat`, `repeat-1`, `repeat-2`. Matching is exact —
  111. * element ids are case-sensitive.
  112. * @param source - the document's full Markdown text.
  113. * @param tree - the GFM parse of exactly `source`, when the caller already has it.
  114. * @returns the set of valid fragments for links into this document.
  115. */
  116. export function documentAnchors(source: string, tree: Nodes = parseMarkdown(source)): Set<string> {
  117. const anchors = new Set<string>()
  118. const occurrences = new Map<string, number>()
  119. for (const heading of markdownHeadingLines(source, tree)) {
  120. const base = githubSlug(heading.text)
  121. let result = base
  122. let bump = occurrences.get(base) ?? 0
  123. while (anchors.has(result)) {
  124. bump += 1
  125. result = `${base}-${bump}`
  126. }
  127. occurrences.set(base, bump)
  128. anchors.add(result)
  129. }
  130. visitMarkdown(tree, (node: Nodes): void => {
  131. if (node.type !== 'html') return
  132. const html = node.value.replace(/<!--[\s\S]*?-->/g, '')
  133. for (const match of html.matchAll(/<a id="([^"]+)"/g)) anchors.add(match[1] ?? '')
  134. })
  135. return anchors
  136. }
  137. /** One Markdown file's link inputs and exposed anchors, collected from a single parse. */
  138. export interface MarkdownLinkDocument {
  139. /** Link, image, and definition destinations with their 1-based start lines, in document order. */
  140. destinations: { url: string; line: number }[]
  141. /** Fragments that links into this document may name. */
  142. anchors: Set<string>
  143. }
  144. /** Per-run reads, parses, and target probes shared by every scanned source and link target. */
  145. export interface MarkdownLinkCache {
  146. /** Read and parse one Markdown file at most once per run. */
  147. document: (absPath: string) => MarkdownLinkDocument
  148. /** Whether a resolved link target exists, probed at most once per path. */
  149. exists: (absPath: string) => boolean
  150. }
  151. function markdownLinkDocument(source: string): MarkdownLinkDocument {
  152. const tree = parseMarkdown(source)
  153. const destinations: MarkdownLinkDocument['destinations'] = []
  154. visitMarkdown(tree, (node: Nodes): void => {
  155. if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && 'url' in node) {
  156. destinations.push({ url: node.url, line: node.position?.start.line ?? 0 })
  157. }
  158. })
  159. return { destinations, anchors: documentAnchors(source, tree) }
  160. }
  161. /**
  162. * Create the memoized file reads and existence probes for one checker run.
  163. * A file that is both a scanned source and a fragment target parses once; the
  164. * repository is assumed not to change while the run lasts.
  165. * @returns the cache to pass to every {@link findViolations} call of the run.
  166. */
  167. export function markdownLinkCache(): MarkdownLinkCache {
  168. const documents = new Map<string, MarkdownLinkDocument>()
  169. const existence = new Map<string, boolean>()
  170. return {
  171. document: (absPath) => {
  172. const hit = documents.get(absPath)
  173. if (hit) return hit
  174. const document = markdownLinkDocument(readFileSync(absPath, 'utf8'))
  175. documents.set(absPath, document)
  176. return document
  177. },
  178. exists: (absPath) => {
  179. const hit = existence.get(absPath)
  180. if (hit !== undefined) return hit
  181. const exists = existsSync(absPath)
  182. existence.set(absPath, exists)
  183. return exists
  184. },
  185. }
  186. }
  187. /**
  188. * Find every broken relative cross-link in one Markdown file via its AST: a
  189. * relative target that does not exist, or a fragment onto a Markdown file
  190. * (same-file `#anchor` links included) that names no heading slug or explicit
  191. * `<a id>` there. Fragments onto non-Markdown targets (`file.ts#L10`) carry
  192. * renderer-owned semantics and are not judged.
  193. * @param absPath - absolute path of the Markdown source to scan.
  194. * @param cache - parses and target probes shared across files for cross-link checks.
  195. * @param scanRoot - repository root violations are reported relative to.
  196. * @returns one entry per broken link, in document order.
  197. */
  198. export function findViolations(
  199. absPath: string,
  200. cache: MarkdownLinkCache = markdownLinkCache(),
  201. scanRoot: string = root,
  202. ): Violation[] {
  203. const file = relative(scanRoot, absPath)
  204. const dir = dirname(absPath)
  205. const out: Violation[] = []
  206. for (const { url, line } of cache.document(absPath).destinations) {
  207. if (isExternal(url)) continue
  208. const target = pathPart(url)
  209. const resolved = target === '' ? absPath : resolve(dir, target)
  210. if (!cache.exists(resolved)) {
  211. out.push({ file, line, url, reason: 'target' })
  212. continue
  213. }
  214. const fragment = fragmentPart(url)
  215. if (fragment === null || !resolved.endsWith('.md')) continue
  216. if (!cache.document(resolved).anchors.has(fragment)) {
  217. out.push({ file, line, url, reason: 'anchor' })
  218. }
  219. }
  220. return out
  221. }
  222. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  223. const files = markdownLinkSourcePaths(root)
  224. const cache = markdownLinkCache()
  225. const all = files.flatMap(file => findViolations(resolve(root, file), cache))
  226. const checked = files.length
  227. if (all.length === 0) {
  228. console.log(`verify-md-links: ${checked} file(s) checked, all relative cross-links and fragments resolve.`)
  229. process.exit(0)
  230. }
  231. console.error('verify-md-links: broken relative cross-links found:')
  232. for (const v of all) {
  233. console.error(` ${v.file}:${v.line} ${v.url} (${v.reason === 'target' ? 'target does not exist' : 'no such anchor in target'})`)
  234. }
  235. process.exit(1)
  236. }