verify-md-links.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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, realpathSync } from 'node:fs'
  35. import { dirname, relative, resolve } from 'node:path'
  36. import { glob } from 'node:fs/promises'
  37. import { fromMarkdown } from 'mdast-util-from-markdown'
  38. import { gfmFromMarkdown } from 'mdast-util-gfm'
  39. import { gfm } from 'micromark-extension-gfm'
  40. import type { Nodes } from 'mdast'
  41. const root = resolve(import.meta.dirname, '..')
  42. /**
  43. * Files to check: doc-typecheck's scope, example Markdown, the AGENTS.md pair,
  44. * and repo-authored agent-skill Markdown.
  45. */
  46. const PATTERNS = [
  47. 'README.md',
  48. 'README.zh.md',
  49. 'docs/**/*.md',
  50. 'packages/*/*.md',
  51. 'packages/*/*/*.md',
  52. 'examples/**/*.md',
  53. 'AGENTS.md',
  54. 'packages/AGENTS.md',
  55. '.agents/skills/**/*.md',
  56. ]
  57. /** A broken relative link: a target path that does not resolve to a file. */
  58. interface Violation {
  59. file: string
  60. /** 1-based line where the link/image/definition node starts. */
  61. line: number
  62. url: string
  63. }
  64. /**
  65. * True for targets this gate must NOT check: scheme-qualified URLs (`https:`,
  66. * `mailto:`, …), protocol-relative (`//host`), root-absolute (`/path`), and
  67. * pure in-page anchors (`#frag`). Everything else is a relative path we own.
  68. */
  69. function isExternalOrAnchor(url: string): boolean {
  70. if (url.startsWith('#')) return true
  71. if (url.startsWith('//')) return true
  72. if (url.startsWith('/')) return true
  73. // A scheme like `https:` / `mailto:` — a colon before any slash, dot, or hash.
  74. return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
  75. }
  76. /**
  77. * Strip the `#fragment` and `?query` from a link target, then percent-decode
  78. * the remaining path so an encoded target (`My%20File.md`, `READ%4DE.md`)
  79. * probes the real filename on disk, the way a Markdown renderer resolves it. A
  80. * malformed escape (`%zz`) makes `decodeURIComponent` throw; we keep the raw
  81. * path in that case so the link is reported as broken (a `%zz` target is not a
  82. * file anyone meant to link) rather than crashing the gate.
  83. */
  84. function pathPart(url: string): string {
  85. const raw = url.replace(/[#?].*$/, '')
  86. try {
  87. return decodeURIComponent(raw)
  88. } catch {
  89. // decodeURIComponent throws only on a malformed percent-escape; the raw
  90. // string is then a path no renderer resolves, so fall through to the
  91. // existence check, which reports it broken.
  92. return raw
  93. }
  94. }
  95. /** Find every broken relative cross-link in one Markdown file via its AST. */
  96. function findViolations(absPath: string): Violation[] {
  97. const file = relative(root, absPath)
  98. const dir = dirname(absPath)
  99. const source = readFileSync(absPath, 'utf8')
  100. const tree = fromMarkdown(source, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] })
  101. const out: Violation[] = []
  102. const check = (url: string, node: Nodes): void => {
  103. if (isExternalOrAnchor(url)) return
  104. const target = pathPart(url)
  105. // A bare `#anchor` reduced to empty path is a same-file anchor — skip.
  106. if (target === '') return
  107. const resolved = resolve(dir, target)
  108. if (!existsSync(resolved)) {
  109. out.push({ file, line: node.position?.start.line ?? 0, url })
  110. }
  111. }
  112. const visit = (node: Nodes): void => {
  113. if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && 'url' in node) {
  114. check(node.url, node)
  115. }
  116. if ('children' in node) {
  117. for (const child of node.children) visit(child)
  118. }
  119. }
  120. visit(tree)
  121. return out
  122. }
  123. const seen = new Set<string>()
  124. const all: Violation[] = []
  125. let checked = 0
  126. for (const pattern of PATTERNS) {
  127. for await (const match of glob(pattern, { cwd: root })) {
  128. const abs = resolve(root, match)
  129. // CLAUDE.md symlinks resolve onto AGENTS.md; dedupe by real path so a file
  130. // matched twice (or via symlink) is checked once.
  131. const real = realpathSync(abs)
  132. if (seen.has(real)) continue
  133. seen.add(real)
  134. checked++
  135. all.push(...findViolations(abs))
  136. }
  137. }
  138. if (all.length === 0) {
  139. console.log(`verify-md-links: ${checked} file(s) checked, all relative cross-links resolve.`)
  140. process.exit(0)
  141. }
  142. console.error('verify-md-links: broken relative cross-links found (target does not exist):')
  143. for (const v of all) {
  144. console.error(` ${v.file}:${v.line} ${v.url}`)
  145. }
  146. process.exit(1)