doc-typecheck.ts 7.8 KB

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