verify-md-links.ts 8.3 KB

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