doc-typecheck.ts 8.5 KB

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