doc-typecheck.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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 file and compiled with `tsc --noEmit` against the
  7. * workspace sources (resolved through the same `paths` map vitest uses, so no
  8. * build is required first). A block that is a deliberate sketch rather than
  9. * compilable code opts out with an explicit ` ```ts ignore-check ` info string
  10. * — the opt-out is visible in the source, and this script reports the ratio so
  11. * the escape hatch can't quietly become the norm. A third info string,
  12. * ` ```ts type-equiv `, marks a verbatim paste of a source type definition that
  13. * `scripts/verify-type-equiv.ts` drift-checks against the source symbol; it is
  14. * skipped here and EXCLUDED from the opt-out ratio (a separately-checked
  15. * category, not an unchecked sketch).
  16. *
  17. * Run: `tsx scripts/doc-typecheck.ts`.
  18. */
  19. import { execFileSync } from 'node:child_process'
  20. import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  21. import { join, relative, resolve } from 'node:path'
  22. import { glob } from 'node:fs/promises'
  23. const root = resolve(import.meta.dirname, '..')
  24. /**
  25. * How a fenced block participates in this gate:
  26. * - `check` (` ```ts `) — compiled.
  27. * - `ignore` (` ```ts ignore-check `) — a deliberate sketch; skipped, and
  28. * counted in the opt-out ratio so the escape hatch can't quietly take over.
  29. * - `type-equiv` (` ```ts type-equiv `) — a verbatim paste of a source type
  30. * definition, drift-checked by `scripts/verify-type-equiv.ts` against the
  31. * source symbol. Skipped HERE (it is not standalone-compilable — no imports)
  32. * and EXCLUDED from the opt-out ratio: it is a separate fully-checked
  33. * category, not an unchecked sketch.
  34. */
  35. type BlockKind = 'check' | 'ignore' | 'type-equiv'
  36. /** One extracted code block. */
  37. interface Block {
  38. file: string
  39. /** 1-based line of the opening fence. */
  40. line: number
  41. kind: BlockKind
  42. code: string
  43. }
  44. /** Extract every ```ts / ```ts ignore-check / ```ts type-equiv block from one Markdown file. */
  45. function extractBlocks(absPath: string): Block[] {
  46. const text = readFileSync(absPath, 'utf8')
  47. const lines = text.split('\n')
  48. const file = relative(root, absPath)
  49. const blocks: Block[] = []
  50. let open: { line: number; kind: BlockKind; body: string[] } | null = null
  51. lines.forEach((raw, i) => {
  52. const fence = /^```(\s*)(\S.*)?$/.exec(raw)
  53. if (!fence) {
  54. if (open) open.body.push(raw)
  55. return
  56. }
  57. if (open) {
  58. // closing fence
  59. blocks.push({ file, line: open.line, kind: open.kind, code: open.body.join('\n') })
  60. open = null
  61. return
  62. }
  63. // opening fence — only care about ts blocks
  64. const info = (fence[2] ?? '').trim()
  65. const kind: BlockKind | null =
  66. info === 'ts' ? 'check'
  67. : info === 'ts ignore-check' ? 'ignore'
  68. : info === 'ts type-equiv' ? 'type-equiv'
  69. : null
  70. if (kind) open = { line: i + 1, kind, body: [] }
  71. })
  72. return blocks
  73. }
  74. /**
  75. * Read the workspace `paths` map from tsconfig.typecheck.json (JSONC). This map
  76. * resolves vendored packages to their BUILT declarations (`lib`) and harness
  77. * packages to source (`src`) — the same resolution `pnpm run lint`/`typecheck` use.
  78. * Resolving vendor to `lib` (not `src`) is essential: otherwise tsc type-checks
  79. * raw vendor source and floods the run with unrelated errors. Requires the
  80. * vendor `lib/` to exist (a fresh clone runs `pnpm run build` first; CI does too).
  81. */
  82. function workspacePaths(): Record<string, string[]> {
  83. const raw = readFileSync(join(root, 'tsconfig.typecheck.json'), 'utf8')
  84. // Strip // line comments and /* */ block comments so JSON.parse accepts it.
  85. const stripped = raw
  86. .replace(/\/\*[\s\S]*?\*\//g, '')
  87. .replace(/(^|[^:])\/\/.*$/gm, '$1')
  88. return (JSON.parse(stripped) as { compilerOptions: { paths: Record<string, string[]> } })
  89. .compilerOptions.paths
  90. }
  91. /** The standalone tsconfig for the temp project (copies base resolution, no
  92. * composite/declaration settings that would fight `--noEmit`). */
  93. function tempTsconfig(): string {
  94. return JSON.stringify({
  95. compilerOptions: {
  96. target: 'es2024',
  97. module: 'esnext',
  98. moduleResolution: 'bundler',
  99. allowImportingTsExtensions: true,
  100. strict: true,
  101. noEmit: true,
  102. skipLibCheck: true,
  103. types: ['node'],
  104. baseUrl: root,
  105. ignoreDeprecations: '6.0',
  106. paths: workspacePaths(),
  107. },
  108. })
  109. }
  110. const markdownGlobs = ['README.md', 'docs/**/*.md', 'packages/*/README.md']
  111. const files: string[] = []
  112. for (const pattern of markdownGlobs) {
  113. for await (const match of glob(pattern, { cwd: root })) files.push(resolve(root, match))
  114. }
  115. files.sort()
  116. const all = files.flatMap(extractBlocks)
  117. const checked = all.filter(b => b.kind === 'check')
  118. const ignored = all.filter(b => b.kind === 'ignore')
  119. // `type-equiv` blocks are verified by verify-type-equiv.ts, not here: neither
  120. // compiled nor counted toward the opt-out ratio (they are a separate
  121. // fully-checked category, not an unchecked sketch). The ratio's denominator is
  122. // therefore the compile-eligible blocks only.
  123. const ratioDenominator = checked.length + ignored.length
  124. if (checked.length === 0) {
  125. console.log('doc-typecheck: no ts code blocks to check.')
  126. process.exit(0)
  127. }
  128. const tmp = mkdtempSync(join(root, '.doc-typecheck-'))
  129. try {
  130. writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig())
  131. const fileForBlock = new Map<string, Block>()
  132. checked.forEach((block, i) => {
  133. const name = `block-${i}.ts`
  134. writeFileSync(join(tmp, name), block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  135. fileForBlock.set(name, block)
  136. })
  137. try {
  138. execFileSync('node_modules/.bin/tsc', ['-p', join(tmp, 'tsconfig.json')], { cwd: root, stdio: 'pipe' })
  139. } catch (error: unknown) {
  140. const out = (error as { stdout?: Buffer }).stdout?.toString() ?? ''
  141. // Rewrite "block-N.ts(line,col)" to the real "file:fenceLine" for triage.
  142. const remapped = out.replace(/block-(\d+)\.ts\((\d+),(\d+)\)/g, (_m, idx: string, ln: string, col: string) => {
  143. const block = fileForBlock.get(`block-${idx}.ts`)
  144. if (!block) return `block-${idx}.ts(${ln},${col})`
  145. return `${block.file} (block at line ${block.line}, +${ln}:${col})`
  146. })
  147. console.error('doc-typecheck: documentation code blocks failed to compile.\n')
  148. console.error(remapped)
  149. process.exit(1)
  150. }
  151. const ratio = ignored.length / ratioDenominator
  152. console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out), ${all.length - ratioDenominator} type-equiv (checked by verify-type-equiv).`)
  153. // Guard against the escape hatch becoming the norm.
  154. if (ratioDenominator >= 4 && ratio > 0.5) {
  155. console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${ratioDenominator}). Make them compile or delete them.`)
  156. process.exit(1)
  157. }
  158. } finally {
  159. rmSync(tmp, { recursive: true, force: true })
  160. }