verify-md-links.ts 8.4 KB

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