verify-md-links.ts 6.0 KB

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