doc-typecheck.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. 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. /**
  85. * Read the workspace `paths` map from tsconfig.typecheck.json (JSONC). This map
  86. * resolves vendored packages to their BUILT declarations (`lib`) and harness
  87. * packages to source (`src`) — the same resolution `pnpm run lint`/`typecheck` use.
  88. * Resolving vendor to `lib` (not `src`) is essential: otherwise tsc type-checks
  89. * raw vendor source and floods the run with unrelated errors. Requires the
  90. * vendor `lib/` to exist (a fresh clone runs `pnpm run build` first; CI does too).
  91. */
  92. function workspacePaths(): Record<string, string[]> {
  93. const file = join(root, 'tsconfig.typecheck.json')
  94. // Parse with TypeScript's own JSONC reader, not a hand-rolled comment strip:
  95. // a regex strip mistakes the `/*/` in a wildcard path candidate
  96. // (`./packages/core/*/src`) for a block comment and corrupts the map.
  97. const result = ts.readConfigFile(file, p => readFileSync(p, 'utf8'))
  98. if (result.error) {
  99. throw new Error(`doc-typecheck: cannot read ${file}: ${ts.flattenDiagnosticMessageText(result.error.messageText, '\n')}`)
  100. }
  101. // `config` is typed `any` by the TS API; narrow it to the one field we read.
  102. const config = result.config as { compilerOptions: { paths: Record<string, string[]> } }
  103. return config.compilerOptions.paths
  104. }
  105. /** The standalone tsconfig for the temp project (copies base resolution, no
  106. * composite/declaration settings that would fight `--noEmit`). */
  107. function tempTsconfig(): string {
  108. return JSON.stringify({
  109. compilerOptions: {
  110. target: 'es2024',
  111. module: 'esnext',
  112. moduleResolution: 'bundler',
  113. allowImportingTsExtensions: true,
  114. strict: true,
  115. noEmit: true,
  116. skipLibCheck: true,
  117. types: ['node'],
  118. baseUrl: root,
  119. ignoreDeprecations: '6.0',
  120. paths: workspacePaths(),
  121. },
  122. })
  123. }
  124. const markdownGlobs = ['README.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md']
  125. const files: string[] = []
  126. for (const pattern of markdownGlobs) {
  127. for await (const match of glob(pattern, { cwd: root })) files.push(resolve(root, match))
  128. }
  129. files.sort()
  130. const all = files.flatMap(extractBlocks)
  131. const checked = all.filter(b => b.kind === 'check')
  132. const ignored = all.filter(b => b.kind === 'ignore')
  133. // `type-equiv` and `cordis-catalog` blocks are verified elsewhere
  134. // (verify-type-equiv.ts and the gen-cordis-catalog `--check` freshness gate),
  135. // not here: neither compiled nor counted toward the opt-out ratio (each is a
  136. // separate fully-checked category, not an unchecked sketch). The ratio's
  137. // denominator is therefore the compile-eligible blocks only.
  138. const ratioDenominator = checked.length + ignored.length
  139. if (checked.length === 0) {
  140. console.log('doc-typecheck: no ts code blocks to check.')
  141. process.exit(0)
  142. }
  143. const tmp = mkdtempSync(join(root, '.doc-typecheck-'))
  144. try {
  145. writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig())
  146. const fileForBlock = new Map<string, Block>()
  147. checked.forEach((block, i) => {
  148. const name = `block-${i}.ts`
  149. writeFileSync(join(tmp, name), block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  150. fileForBlock.set(name, block)
  151. })
  152. try {
  153. execFileSync('node_modules/.bin/tsc', ['-p', join(tmp, 'tsconfig.json')], { cwd: root, stdio: 'pipe' })
  154. } catch (error: unknown) {
  155. const out = (error as { stdout?: Buffer }).stdout?.toString() ?? ''
  156. // Rewrite "block-N.ts(line,col)" to the real "file:fenceLine" for triage.
  157. const remapped = out.replace(/block-(\d+)\.ts\((\d+),(\d+)\)/g, (_m, idx: string, ln: string, col: string) => {
  158. const block = fileForBlock.get(`block-${idx}.ts`)
  159. if (!block) return `block-${idx}.ts(${ln},${col})`
  160. return `${block.file} (block at line ${block.line}, +${ln}:${col})`
  161. })
  162. console.error('doc-typecheck: documentation code blocks failed to compile.\n')
  163. console.error(remapped)
  164. process.exit(1)
  165. }
  166. const ratio = ignored.length / ratioDenominator
  167. const skipped = all.length - ratioDenominator
  168. 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).`)
  169. // Guard against the escape hatch becoming the norm.
  170. if (ratioDenominator >= 4 && ratio > 0.5) {
  171. console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${ratioDenominator}). Make them compile or delete them.`)
  172. process.exit(1)
  173. }
  174. } finally {
  175. rmSync(tmp, { recursive: true, force: true })
  176. }