doc-typecheck.ts 9.0 KB

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