doc-typecheck.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. 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. import ts from 'typescript'
  27. const root = resolve(import.meta.dirname, '..')
  28. /**
  29. * How a fenced block participates in this gate:
  30. * - `check` (` ```ts `) — compiled.
  31. * - `ignore` (` ```ts ignore-check `) — a deliberate sketch; skipped, and
  32. * counted in the opt-out ratio so the escape hatch can't quietly take over.
  33. * - `type-equiv` (` ```ts type-equiv `) — a verbatim paste of a source type
  34. * definition, drift-checked by `scripts/verify-type-equiv.ts` against the
  35. * source symbol. Skipped HERE (it is not standalone-compilable — no imports)
  36. * and EXCLUDED from the opt-out ratio: it is a separate fully-checked
  37. * category, not an unchecked sketch.
  38. * - `cordis-catalog` (` ```ts cordis-catalog `) — a generated event/service
  39. * signature fragment in the cordis catalog. Skipped HERE for the same reason
  40. * (a bare signature fragment has no imports and does not stand alone) and
  41. * EXCLUDED from the opt-out ratio: the catalog is generated and frozen by
  42. * `scripts/gen-cordis-catalog.ts` + its `--check` freshness gate.
  43. */
  44. type BlockKind = 'check' | 'ignore' | 'type-equiv' | 'cordis-catalog'
  45. /** One extracted code block. */
  46. interface Block {
  47. file: string
  48. /** 1-based line of the opening fence. */
  49. line: number
  50. kind: BlockKind
  51. code: string
  52. }
  53. /** Extract every ts / ts ignore-check / ts type-equiv / ts cordis-catalog block from one Markdown file. */
  54. function extractBlocks(absPath: string): Block[] {
  55. const text = readFileSync(absPath, 'utf8')
  56. const lines = text.split('\n')
  57. const file = relative(root, absPath)
  58. const blocks: Block[] = []
  59. let open: { line: number; kind: BlockKind; body: string[] } | null = null
  60. lines.forEach((raw, i) => {
  61. const fence = /^```(\s*)(\S.*)?$/.exec(raw)
  62. if (!fence) {
  63. if (open) open.body.push(raw)
  64. return
  65. }
  66. if (open) {
  67. // closing fence
  68. blocks.push({ file, line: open.line, kind: open.kind, code: open.body.join('\n') })
  69. open = null
  70. return
  71. }
  72. // opening fence — only care about ts blocks
  73. const info = (fence[2] ?? '').trim()
  74. const kind: BlockKind | null =
  75. info === 'ts' ? 'check'
  76. : info === 'ts ignore-check' ? 'ignore'
  77. : info === 'ts type-equiv' ? 'type-equiv'
  78. : info === 'ts cordis-catalog' ? 'cordis-catalog'
  79. : null
  80. if (kind) open = { line: i + 1, kind, body: [] }
  81. })
  82. return blocks
  83. }
  84. /** Reuse the repo typecheck graph references from a temp project one directory below root. */
  85. function workspaceReferences(): { path: string }[] {
  86. const file = join(root, 'tsconfig.json')
  87. // Parse with TypeScript's own JSONC reader, not a hand-rolled comment strip:
  88. // a regex strip mistakes the `/*/` in a wildcard path candidate
  89. // (`./packages/core/*/src`) for a block comment and corrupts the map.
  90. const result = ts.readConfigFile(file, p => readFileSync(p, 'utf8'))
  91. if (result.error) {
  92. throw new Error(`doc-typecheck: cannot read ${file}: ${ts.flattenDiagnosticMessageText(result.error.messageText, '\n')}`)
  93. }
  94. // `config` is typed `any` by the TS API; narrow it to the one field we read.
  95. const { references } = result.config as { compilerOptions: { paths: Record<string, string[]> }; references: { path: string }[] }
  96. return references.map(({ path }) => {
  97. const relativeToTemp = path.startsWith('./') ? `../${path.slice(2)}` : `../${path}`
  98. return { path: relativeToTemp }
  99. })
  100. }
  101. /** The standalone tsconfig for the temp typecheck project. */
  102. function tempTsconfig(): string {
  103. return JSON.stringify({
  104. extends: '../tsconfig.json',
  105. compilerOptions: {
  106. noUnusedLocals: false,
  107. noUnusedParameters: false,
  108. tsBuildInfoFile: './tsconfig.tsbuildinfo',
  109. },
  110. include: ['block-*.ts'],
  111. references: workspaceReferences(),
  112. })
  113. }
  114. const markdownGlobs = ['README.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md']
  115. const files: string[] = []
  116. for (const pattern of markdownGlobs) {
  117. for await (const match of glob(pattern, { cwd: root })) files.push(resolve(root, match))
  118. }
  119. files.sort()
  120. const all = files.flatMap(extractBlocks)
  121. const checked = all.filter(b => b.kind === 'check')
  122. const ignored = all.filter(b => b.kind === 'ignore')
  123. // `type-equiv` and `cordis-catalog` blocks are verified elsewhere
  124. // (verify-type-equiv.ts and the gen-cordis-catalog `--check` freshness gate),
  125. // not here: neither compiled nor counted toward the opt-out ratio (each is a
  126. // separate fully-checked category, not an unchecked sketch). The ratio's
  127. // denominator is therefore the compile-eligible blocks only.
  128. const ratioDenominator = checked.length + ignored.length
  129. if (checked.length === 0) {
  130. console.log('doc-typecheck: no ts code blocks to check.')
  131. process.exit(0)
  132. }
  133. const tmp = mkdtempSync(join(root, '.doc-typecheck-'))
  134. try {
  135. writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig())
  136. const fileForBlock = new Map<string, Block>()
  137. checked.forEach((block, i) => {
  138. const name = `block-${i}.ts`
  139. writeFileSync(join(tmp, name), block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  140. fileForBlock.set(name, block)
  141. })
  142. try {
  143. execFileSync('node_modules/.bin/tsc', ['-b', join(tmp, 'tsconfig.json')], { cwd: root, stdio: 'pipe' })
  144. } catch (error: unknown) {
  145. const failed = error as { stdout?: Buffer; stderr?: Buffer }
  146. const out = `${failed.stdout?.toString() ?? ''}${failed.stderr?.toString() ?? ''}`
  147. // Rewrite "block-N.ts(line,col)" to the real "file:fenceLine" for triage.
  148. const remapped = out.replace(/(?:[^\s:()]*[/\\])?block-(\d+)\.ts\((\d+),(\d+)\)/g, (_m, idx: string, ln: string, col: string) => {
  149. const block = fileForBlock.get(`block-${idx}.ts`)
  150. if (!block) return `block-${idx}.ts(${ln},${col})`
  151. return `${block.file} (block at line ${block.line}, +${ln}:${col})`
  152. })
  153. console.error('doc-typecheck: documentation code blocks failed to compile.\n')
  154. console.error(remapped)
  155. process.exit(1)
  156. }
  157. const ratio = ignored.length / ratioDenominator
  158. const skipped = all.length - ratioDenominator
  159. 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).`)
  160. // Guard against the escape hatch becoming the norm.
  161. if (ratioDenominator >= 4 && ratio > 0.5) {
  162. console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${ratioDenominator}). Make them compile or delete them.`)
  163. process.exit(1)
  164. }
  165. } finally {
  166. rmSync(tmp, { recursive: true, force: true })
  167. }