doc-typecheck.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. /**
  2. * Typecheck Markdown `ts` fences against workspace sources. `ignore-check`
  3. * fences are reported as opt-outs; generated catalog fragments and
  4. * `type-equiv` blocks are skipped here because their owning gates verify them.
  5. */
  6. import { execFileSync } from 'node:child_process'
  7. import { globSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  8. import { join, relative, resolve } from 'node:path'
  9. import ts from 'typescript'
  10. const root = resolve(import.meta.dirname, '..')
  11. /**
  12. * TypeScript-fence ownership. `check` compiles; `ignore` is an unchecked sketch
  13. * counted in the opt-out ratio; the catalog and type-equivalence variants are
  14. * excluded from that ratio because their owning gates verify them.
  15. */
  16. type BlockKind = 'check' | 'ignore' | 'type-equiv' | 'cordis-catalog' | 'persistence-catalog' | 'config-catalog'
  17. /** One extracted code block. */
  18. interface Block {
  19. file: string
  20. /** 1-based line of the opening fence. */
  21. line: number
  22. kind: BlockKind
  23. code: string
  24. }
  25. /** Extract every recognized TypeScript fence from one Markdown file. */
  26. function extractBlocks(absPath: string): Block[] {
  27. const text = readFileSync(absPath, 'utf8')
  28. const lines = text.split('\n')
  29. const file = relative(root, absPath)
  30. const blocks: Block[] = []
  31. let open: { line: number; kind: BlockKind; body: string[] } | null = null
  32. lines.forEach((raw, i) => {
  33. const fence = /^```(\s*)(\S.*)?$/.exec(raw)
  34. if (!fence) {
  35. if (open) open.body.push(raw)
  36. return
  37. }
  38. if (open) {
  39. // closing fence
  40. blocks.push({ file, line: open.line, kind: open.kind, code: open.body.join('\n') })
  41. open = null
  42. return
  43. }
  44. // Ignore non-TypeScript fences.
  45. const info = (fence[2] ?? '').trim()
  46. const kind: BlockKind | null =
  47. info === 'ts' ? 'check'
  48. : info === 'ts ignore-check' ? 'ignore'
  49. : info === 'ts type-equiv' ? 'type-equiv'
  50. : info === 'ts cordis-catalog' ? 'cordis-catalog'
  51. : info === 'ts persistence-catalog' ? 'persistence-catalog'
  52. : info === 'ts config-catalog' ? 'config-catalog'
  53. : null
  54. if (kind) open = { line: i + 1, kind, body: [] }
  55. })
  56. return blocks
  57. }
  58. /** Reuse the repo typecheck graph references from a temp project one directory below root. */
  59. function workspaceReferences(): { path: string }[] {
  60. const file = join(root, 'tsconfig.json')
  61. // Parse with TypeScript's own JSONC reader, not a hand-rolled comment strip:
  62. // a regex strip mistakes the `/*/` in a wildcard path candidate
  63. // (`./packages/core/*/src`) for a block comment and corrupts the map.
  64. const result = ts.readConfigFile(file, p => readFileSync(p, 'utf8'))
  65. if (result.error) {
  66. throw new Error(`doc-typecheck: cannot read ${file}: ${ts.flattenDiagnosticMessageText(result.error.messageText, '\n')}`)
  67. }
  68. // `config` is typed `any` by the TS API; narrow it to the one field we read.
  69. const { references } = result.config as { compilerOptions: { paths: Record<string, string[]> }; references: { path: string }[] }
  70. return references.map(({ path }) => {
  71. const relativeToTemp = path.startsWith('./') ? `../${path.slice(2)}` : `../${path}`
  72. return { path: relativeToTemp }
  73. })
  74. }
  75. /** The standalone tsconfig for the temp typecheck project. */
  76. function tempTsconfig(): string {
  77. return JSON.stringify({
  78. extends: '../tsconfig.json',
  79. compilerOptions: {
  80. noUnusedLocals: false,
  81. noUnusedParameters: false,
  82. tsBuildInfoFile: './tsconfig.tsbuildinfo',
  83. },
  84. include: ['block-*.ts'],
  85. references: workspaceReferences(),
  86. })
  87. }
  88. const markdownGlobs = ['README.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md']
  89. const files: string[] = []
  90. for (const pattern of markdownGlobs) {
  91. for (const match of globSync(pattern, { cwd: root })) files.push(resolve(root, match))
  92. }
  93. files.sort()
  94. const all = files.flatMap(extractBlocks)
  95. const checked = all.filter(b => b.kind === 'check')
  96. const ignored = all.filter(b => b.kind === 'ignore')
  97. // Only compile-eligible fences belong in the opt-out ratio; every other skipped
  98. // kind has an independent verifier named in BlockKind's contract above.
  99. const ratioDenominator = checked.length + ignored.length
  100. if (checked.length === 0) {
  101. console.log('doc-typecheck: no ts code blocks to check.')
  102. process.exit(0)
  103. }
  104. const tmp = mkdtempSync(join(root, '.doc-typecheck-'))
  105. try {
  106. writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig())
  107. const fileForBlock = new Map<string, Block>()
  108. checked.forEach((block, i) => {
  109. const name = `block-${i}.ts`
  110. writeFileSync(join(tmp, name), block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  111. fileForBlock.set(name, block)
  112. })
  113. try {
  114. // tsc's JS entry via the current node, not the .bin shim: the extensionless
  115. // shim is not spawnable on Windows (the CVE-2024-27980 class the sibling
  116. // scripts hit), and the .cmd variant would need shell:true, which
  117. // concatenates args UNESCAPED — a hazard for the temp project path. The JS
  118. // entry behaves identically on every platform.
  119. execFileSync(process.execPath, ['node_modules/typescript/bin/tsc', '-b', join(tmp, 'tsconfig.json')], { cwd: root, stdio: 'pipe' })
  120. } catch (error: unknown) {
  121. const failed = error as { stdout?: Buffer; stderr?: Buffer }
  122. const out = `${failed.stdout?.toString() ?? ''}${failed.stderr?.toString() ?? ''}`
  123. // Rewrite "block-N.ts(line,col)" to the real "file:fenceLine" for triage.
  124. const remapped = out.replace(/(?:[^\s:()]*[/\\])?block-(\d+)\.ts\((\d+),(\d+)\)/g, (_m, idx: string, ln: string, col: string) => {
  125. const block = fileForBlock.get(`block-${idx}.ts`)
  126. if (!block) return `block-${idx}.ts(${ln},${col})`
  127. return `${block.file} (block at line ${block.line}, +${ln}:${col})`
  128. })
  129. console.error('doc-typecheck: documentation code blocks failed to compile.\n')
  130. console.error(remapped)
  131. process.exit(1)
  132. }
  133. const ratio = ignored.length / ratioDenominator
  134. const skipped = all.length - ratioDenominator
  135. console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out), ${skipped} type-equiv/catalog (checked elsewhere).`)
  136. // Guard against the escape hatch becoming the norm.
  137. if (ratioDenominator >= 4 && ratio > 0.5) {
  138. console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${ratioDenominator}). Make them compile or delete them.`)
  139. process.exit(1)
  140. }
  141. } finally {
  142. rmSync(tmp, { recursive: true, force: true })
  143. }