verify-md-links.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. /**
  2. * Doc-sync gate: verify that every relative Markdown cross-link resolves to a
  3. * file that exists. Docs in this repo link to each other by relative path
  4. * (`[topic](../implemented/2026-…-….md)`, `[the cookbook](adding-a-tool.md)`);
  5. * a rename or a move silently breaks those links, and nothing caught it before
  6. * review. The RFC tree reorganization (one `docs/rfc/` with proposed/
  7. * implemented/ rejected/ subfolders, every file renamed to a dated slug) is the
  8. * motivating case: ~40 inter-doc links were rewritten by hand, and a single
  9. * fat-fingered path would have shipped a dead link.
  10. *
  11. * Detection is AST-based, mirroring verify-md-wrap: parse each file with
  12. * mdast-util-from-markdown + GFM, then walk every `link`, `image`, and
  13. * `definition` node. A target is checked when it is a RELATIVE path; these are
  14. * skipped because they are not ours to verify:
  15. * - absolute URLs with a scheme (`https:`, `http:`, `mailto:`, …),
  16. * - protocol-relative URLs (`//host/path`),
  17. * - root-absolute paths (`/foo` — no stable base in a repo checkout),
  18. * - pure in-page anchors (`#section`).
  19. * For a relative target the `#fragment` and `?query` are stripped, the path is
  20. * resolved against the linking file's directory, and the result must exist on
  21. * disk. This is checker, not fixer: it reports and never rewrites.
  22. *
  23. * Scope is the other doc-sync gates' set plus example Markdown, AGENTS.md
  24. * files in those checked trees, AND the repo-authored agent-skill Markdown under
  25. * `.agents/skills/` — those skill files cross-link into the docs tree (e.g. the
  26. * dsh-code-review skill cites the RFC index), so a rename must not silently
  27. * break them either: README.md, docs/** /*.md, packages/* /README.md,
  28. * examples/** /*.md, AGENTS.md, packages/AGENTS.md, .agents/skills/** /*.md.
  29. * The root, packages/, and examples/ CLAUDE.md files are symlinks to the
  30. * AGENTS.md files, so they are deduped by real path.
  31. *
  32. * Run: `tsx scripts/verify-md-links.ts`.
  33. */
  34. import { existsSync, readFileSync } from 'node:fs'
  35. import { dirname, relative, resolve } from 'node:path'
  36. import type { Nodes } from 'mdast'
  37. import { parseMarkdown, visitMarkdown } from './markdown.ts'
  38. import { uniqueRepoFiles } from './repo-files.ts'
  39. const root = resolve(import.meta.dirname, '..')
  40. /**
  41. * Files to check: doc-typecheck's scope, example Markdown, the AGENTS.md pair,
  42. * and repo-authored agent-skill Markdown.
  43. */
  44. const PATTERNS = [
  45. 'README.md',
  46. 'README.zh.md',
  47. 'docs/**/*.md',
  48. 'packages/*/*.md',
  49. 'packages/*/*/*.md',
  50. 'examples/**/*.md',
  51. 'AGENTS.md',
  52. 'packages/AGENTS.md',
  53. '.agents/skills/**/*.md',
  54. ]
  55. /** A broken relative link: a target path that does not resolve to a file. */
  56. interface Violation {
  57. file: string
  58. /** 1-based line where the link/image/definition node starts. */
  59. line: number
  60. url: string
  61. }
  62. /**
  63. * True for targets this gate must NOT check: scheme-qualified URLs (`https:`,
  64. * `mailto:`, …), protocol-relative (`//host`), root-absolute (`/path`), and
  65. * pure in-page anchors (`#frag`). Everything else is a relative path we own.
  66. */
  67. function isExternalOrAnchor(url: string): boolean {
  68. if (url.startsWith('#')) return true
  69. if (url.startsWith('//')) return true
  70. if (url.startsWith('/')) return true
  71. // A scheme like `https:` / `mailto:` — a colon before any slash, dot, or hash.
  72. return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
  73. }
  74. /**
  75. * Strip the `#fragment` and `?query` from a link target, then percent-decode
  76. * the remaining path so an encoded target (`My%20File.md`, `READ%4DE.md`)
  77. * probes the real filename on disk, the way a Markdown renderer resolves it. A
  78. * malformed escape (`%zz`) makes `decodeURIComponent` throw; we keep the raw
  79. * path in that case so the link is reported as broken (a `%zz` target is not a
  80. * file anyone meant to link) rather than crashing the gate.
  81. */
  82. function pathPart(url: string): string {
  83. const raw = url.replace(/[#?].*$/, '')
  84. try {
  85. return decodeURIComponent(raw)
  86. } catch {
  87. // decodeURIComponent throws only on a malformed percent-escape; the raw
  88. // string is then a path no renderer resolves, so fall through to the
  89. // existence check, which reports it broken.
  90. return raw
  91. }
  92. }
  93. /** Find every broken relative cross-link in one Markdown file via its AST. */
  94. function findViolations(absPath: string): Violation[] {
  95. const file = relative(root, absPath)
  96. const dir = dirname(absPath)
  97. const source = readFileSync(absPath, 'utf8')
  98. const tree = parseMarkdown(source)
  99. const out: Violation[] = []
  100. const check = (url: string, node: Nodes): void => {
  101. if (isExternalOrAnchor(url)) return
  102. const target = pathPart(url)
  103. // A bare `#anchor` reduced to empty path is a same-file anchor — skip.
  104. if (target === '') return
  105. const resolved = resolve(dir, target)
  106. if (!existsSync(resolved)) {
  107. out.push({ file, line: node.position?.start.line ?? 0, url })
  108. }
  109. }
  110. visitMarkdown(tree, (node: Nodes): void => {
  111. if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && 'url' in node) {
  112. check(node.url, node)
  113. }
  114. })
  115. return out
  116. }
  117. const files = uniqueRepoFiles(root, PATTERNS)
  118. const all = files.flatMap(file => findViolations(file.abs))
  119. const checked = files.length
  120. if (all.length === 0) {
  121. console.log(`verify-md-links: ${checked} file(s) checked, all relative cross-links resolve.`)
  122. process.exit(0)
  123. }
  124. console.error('verify-md-links: broken relative cross-links found (target does not exist):')
  125. for (const v of all) {
  126. console.error(` ${v.file}:${v.line} ${v.url}`)
  127. }
  128. process.exit(1)