doc-typecheck.ts 9.0 KB

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