doc-typecheck.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. /**
  2. * Doc-sync gate (doc-sync-enforcement RFC, part 1): typecheck the fenced `ts` code blocks in our
  3. * Markdown so documentation can't drift from the API it documents.
  4. *
  5. * Every ```ts block in README.md, docs/** and packages/* /README.md is
  6. * extracted to a temp typecheck project and compiled against the workspace
  7. * sources through the same project-reference boundaries used by repo
  8. * typecheck. A block that is a deliberate sketch rather than compilable code
  9. * opts out with an explicit ` ```ts ignore-check ` info string — the opt-out
  10. * is visible in the source, and this script reports the ratio so the escape
  11. * hatch can't quietly become the norm.
  12. *
  13. * Run: `tsx scripts/doc-typecheck.ts`.
  14. */
  15. import { execFileSync } from 'node:child_process'
  16. import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  17. import { join, relative, resolve } from 'node:path'
  18. import { glob } from 'node:fs/promises'
  19. const root = resolve(import.meta.dirname, '..')
  20. /** One extracted code block. */
  21. interface Block {
  22. file: string
  23. /** 1-based line of the opening fence. */
  24. line: number
  25. /** `true` when the fence is ` ```ts ignore-check ` (skip compilation). */
  26. ignored: boolean
  27. code: string
  28. }
  29. /** Strip JSONC comments from checked-in tsconfig files before JSON.parse. */
  30. function stripJsonComments(raw: string): string {
  31. return raw
  32. .replace(/\/\*[\s\S]*?\*\//g, '')
  33. .replace(/(^|[^:])\/\/.*$/gm, '$1')
  34. }
  35. /** Extract every ```ts / ```ts ignore-check block from one Markdown file. */
  36. function extractBlocks(absPath: string): Block[] {
  37. const text = readFileSync(absPath, 'utf8')
  38. const lines = text.split('\n')
  39. const file = relative(root, absPath)
  40. const blocks: Block[] = []
  41. let open: { line: number; ignored: boolean; body: string[] } | null = null
  42. lines.forEach((raw, i) => {
  43. const fence = /^```(\s*)(\S.*)?$/.exec(raw)
  44. if (!fence) {
  45. if (open) open.body.push(raw)
  46. return
  47. }
  48. if (open) {
  49. // closing fence
  50. blocks.push({ file, line: open.line, ignored: open.ignored, code: open.body.join('\n') })
  51. open = null
  52. return
  53. }
  54. // opening fence — only care about ts blocks
  55. const info = (fence[2] ?? '').trim()
  56. if (info === 'ts' || info === 'ts ignore-check') {
  57. open = { line: i + 1, ignored: info === 'ts ignore-check', body: [] }
  58. }
  59. })
  60. return blocks
  61. }
  62. /** Reuse the repo typecheck graph references from a temp project one directory below root. */
  63. function workspaceReferences(): { path: string }[] {
  64. const raw = readFileSync(join(root, 'tsconfig.json'), 'utf8')
  65. const { references } = JSON.parse(stripJsonComments(raw)) as { references: { path: string }[] }
  66. return references.map(({ path }) => {
  67. const relativeToTemp = path.startsWith('./') ? `../${path.slice(2)}` : `../${path}`
  68. return { path: relativeToTemp }
  69. })
  70. }
  71. /** The standalone tsconfig for the temp typecheck project. */
  72. function tempTsconfig(): string {
  73. return JSON.stringify({
  74. extends: '../tsconfig.json',
  75. compilerOptions: {
  76. noUnusedLocals: false,
  77. noUnusedParameters: false,
  78. tsBuildInfoFile: './tsconfig.tsbuildinfo',
  79. },
  80. include: ['block-*.ts'],
  81. references: workspaceReferences(),
  82. })
  83. }
  84. const markdownGlobs = ['README.md', 'docs/**/*.md', 'packages/*/README.md']
  85. const files: string[] = []
  86. for (const pattern of markdownGlobs) {
  87. for await (const match of glob(pattern, { cwd: root })) files.push(resolve(root, match))
  88. }
  89. files.sort()
  90. const all = files.flatMap(extractBlocks)
  91. const checked = all.filter(b => !b.ignored)
  92. const ignored = all.filter(b => b.ignored)
  93. if (checked.length === 0) {
  94. console.log('doc-typecheck: no ts code blocks to check.')
  95. process.exit(0)
  96. }
  97. const tmp = mkdtempSync(join(root, '.doc-typecheck-'))
  98. try {
  99. writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig())
  100. const fileForBlock = new Map<string, Block>()
  101. checked.forEach((block, i) => {
  102. const name = `block-${i}.ts`
  103. writeFileSync(join(tmp, name), block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  104. fileForBlock.set(name, block)
  105. })
  106. try {
  107. execFileSync('node_modules/.bin/tsc', ['-b', join(tmp, 'tsconfig.json')], { cwd: root, stdio: 'pipe' })
  108. } catch (error: unknown) {
  109. const failed = error as { stdout?: Buffer; stderr?: Buffer }
  110. const out = `${failed.stdout?.toString() ?? ''}${failed.stderr?.toString() ?? ''}`
  111. // Rewrite "block-N.ts(line,col)" to the real "file:fenceLine" for triage.
  112. const remapped = out.replace(/(?:[^\s:()]*[/\\])?block-(\d+)\.ts\((\d+),(\d+)\)/g, (_m, idx: string, ln: string, col: string) => {
  113. const block = fileForBlock.get(`block-${idx}.ts`)
  114. if (!block) return `block-${idx}.ts(${ln},${col})`
  115. return `${block.file} (block at line ${block.line}, +${ln}:${col})`
  116. })
  117. console.error('doc-typecheck: documentation code blocks failed to compile.\n')
  118. console.error(remapped)
  119. process.exit(1)
  120. }
  121. const ratio = ignored.length / all.length
  122. console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out).`)
  123. // Guard against the escape hatch becoming the norm.
  124. if (all.length >= 4 && ratio > 0.5) {
  125. console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${all.length}). Make them compile or delete them.`)
  126. process.exit(1)
  127. }
  128. } finally {
  129. rmSync(tmp, { recursive: true, force: true })
  130. }