doc-typecheck.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. /**
  2. * Typecheck Markdown `ts` fences against the workspace API. `ignore-check` fences are reported as
  3. * opt-outs; generated catalog fragments and source-equivalence blocks are skipped here because their
  4. * owning gates verify them. A build-coordinated mode consumes existing declarations without emit.
  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. import { builtDeclarationPath } from './doc-typecheck-paths.ts'
  11. import { extractFences } from './md-fences.ts'
  12. const root = resolve(import.meta.dirname, '..')
  13. /**
  14. * TypeScript-fence ownership. `check` compiles; `ignore` is an unchecked sketch
  15. * counted in the opt-out ratio; the catalog and type-equivalence variants are
  16. * excluded from that ratio because their owning gates verify them.
  17. */
  18. type BlockKind = 'check' | 'ignore' | 'type-equiv' | 'cordis-catalog' | 'persistence-catalog' | 'config-catalog'
  19. /** One extracted code block. */
  20. interface Block {
  21. file: string
  22. /** 1-based line of the opening fence. */
  23. line: number
  24. kind: BlockKind
  25. code: string
  26. }
  27. /** The info-string → kind table this gate tracks. */
  28. const KIND_BY_INFO: Record<string, BlockKind> = {
  29. 'ts': 'check',
  30. 'ts ignore-check': 'ignore',
  31. 'ts type-equiv': 'type-equiv',
  32. 'ts public-api': 'type-equiv',
  33. 'ts cordis-catalog': 'cordis-catalog',
  34. 'ts persistence-catalog': 'persistence-catalog',
  35. 'ts config-catalog': 'config-catalog',
  36. }
  37. /** Extract every recognized TypeScript fence from one Markdown file. */
  38. function extractBlocks(absPath: string): Block[] {
  39. const file = relative(root, absPath)
  40. return extractFences(absPath, info => KIND_BY_INFO[info] ?? null)
  41. .map(f => ({ file, line: f.line, kind: f.kind, code: f.code }))
  42. }
  43. const configHost: ts.ParseConfigFileHost = {
  44. ...ts.sys,
  45. getCurrentDirectory: () => root,
  46. onUnRecoverableConfigFileDiagnostic(diagnostic) {
  47. throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))
  48. },
  49. }
  50. /** Load root settings and redirect workspace aliases to declarations from the coordinated build. */
  51. function builtTypeCompilerOptions(): ts.CompilerOptions {
  52. const configPath = join(root, 'tsconfig.json')
  53. const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, configHost)
  54. if (!parsed) throw new Error(`doc-typecheck: cannot parse ${configPath}`)
  55. if (parsed.errors.length > 0) {
  56. throw new Error(parsed.errors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'))
  57. }
  58. if (parsed.options.paths === undefined) throw new Error('doc-typecheck: root tsconfig has no workspace paths')
  59. const paths = Object.fromEntries(Object.entries(parsed.options.paths).map(([specifier, candidates]) => [
  60. specifier,
  61. candidates.map(builtDeclarationPath),
  62. ]))
  63. const options: ts.CompilerOptions = {
  64. ...parsed.options,
  65. paths,
  66. noEmit: true,
  67. composite: false,
  68. incremental: false,
  69. declaration: false,
  70. declarationMap: false,
  71. sourceMap: false,
  72. noUnusedLocals: false,
  73. noUnusedParameters: false,
  74. }
  75. delete options.tsBuildInfoFile
  76. return options
  77. }
  78. /** Compile Markdown blocks as virtual files against declarations from the coordinated build. */
  79. function compileBlocksAgainstBuiltTypes(blocks: Block[]): readonly ts.Diagnostic[] {
  80. const options = builtTypeCompilerOptions()
  81. const sources = new Map<string, string>()
  82. for (const [index, block] of blocks.entries()) {
  83. const fileName = resolve(root, '.doc-typecheck', `block-${index}.ts`)
  84. sources.set(fileName, block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  85. }
  86. const baseHost = ts.createCompilerHost(options, true)
  87. const host: ts.CompilerHost = {
  88. ...baseHost,
  89. fileExists(fileName) {
  90. return sources.has(resolve(fileName)) || baseHost.fileExists(fileName)
  91. },
  92. readFile(fileName) {
  93. return sources.get(resolve(fileName)) ?? baseHost.readFile(fileName)
  94. },
  95. getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
  96. const source = sources.get(resolve(fileName))
  97. if (source !== undefined) return ts.createSourceFile(fileName, source, languageVersion, true)
  98. return baseHost.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile)
  99. },
  100. writeFile() {
  101. throw new Error('doc-typecheck: noEmit compilation attempted to write output')
  102. },
  103. }
  104. const program = ts.createProgram([...sources.keys()], options, host)
  105. return ts.getPreEmitDiagnostics(program)
  106. }
  107. /** Render compiler diagnostics with virtual block paths mapped back to Markdown. */
  108. function formatDiagnostics(diagnostics: readonly ts.Diagnostic[], blocks: Block[]): string {
  109. const formatted = ts.formatDiagnostics(diagnostics, {
  110. getCanonicalFileName: fileName => fileName,
  111. getCurrentDirectory: () => root,
  112. getNewLine: () => ts.sys.newLine,
  113. })
  114. return remapBlockPaths(formatted, blocks)
  115. }
  116. /** Reuse the repo typecheck graph references from a temp project one directory below root. */
  117. function workspaceReferences(): { path: string }[] {
  118. const file = join(root, 'tsconfig.json')
  119. // Parse with TypeScript's own JSONC reader: a regex comment stripper corrupts the `/*/` path
  120. // candidate in the workspace wildcard.
  121. const result = ts.readConfigFile(file, path => readFileSync(path, 'utf8'))
  122. if (result.error) {
  123. throw new Error(`doc-typecheck: cannot read ${file}: ${ts.flattenDiagnosticMessageText(result.error.messageText, '\n')}`)
  124. }
  125. // `config` is typed `any` by the TS API; narrow it to the one field read here.
  126. const { references } = result.config as { references: { path: string }[] }
  127. return references.map(({ path }) => ({
  128. path: path.startsWith('./') ? `../${path.slice(2)}` : `../${path}`,
  129. }))
  130. }
  131. /** The standalone temp project used when no coordinated build owns declaration freshness. */
  132. function tempTsconfig(): string {
  133. return JSON.stringify({
  134. extends: '../tsconfig.json',
  135. compilerOptions: {
  136. noUnusedLocals: false,
  137. noUnusedParameters: false,
  138. tsBuildInfoFile: './tsconfig.tsbuildinfo',
  139. },
  140. include: ['block-*.ts'],
  141. references: workspaceReferences(),
  142. })
  143. }
  144. /** Compile blocks through project references for the standalone command. */
  145. function compileBlocksStandalone(blocks: Block[]): string | undefined {
  146. const tmp = mkdtempSync(join(root, '.doc-typecheck-'))
  147. try {
  148. writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig())
  149. for (const [index, block] of blocks.entries()) {
  150. writeFileSync(join(tmp, `block-${index}.ts`), block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  151. }
  152. try {
  153. // Invoke tsc's JS entry through Node instead of a platform-specific shell shim.
  154. execFileSync(process.execPath, ['node_modules/typescript/bin/tsc', '-b', join(tmp, 'tsconfig.json')], {
  155. cwd: root,
  156. stdio: 'pipe',
  157. })
  158. return undefined
  159. } catch (error: unknown) {
  160. const failed = error as { stdout?: Buffer; stderr?: Buffer }
  161. return remapBlockPaths(`${failed.stdout?.toString() ?? ''}${failed.stderr?.toString() ?? ''}`, blocks)
  162. }
  163. } finally {
  164. rmSync(tmp, { recursive: true, force: true })
  165. }
  166. }
  167. /** Map virtual or temporary block paths back to their owning Markdown fences. */
  168. function remapBlockPaths(output: string, blocks: Block[]): string {
  169. return output.replace(/(?:[^\s:()]*[/\\])?block-(\d+)\.ts\((\d+),(\d+)\)/g, (_match, index: string, line: string, column: string) => {
  170. const block = blocks[Number(index)]
  171. if (!block) return `block-${index}.ts(${line},${column})`
  172. return `${block.file} (block at line ${block.line}, +${line}:${column})`
  173. })
  174. }
  175. const markdownGlobs = ['README.md', '.agents/notes/**/*.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md']
  176. const files: string[] = []
  177. for (const pattern of markdownGlobs) {
  178. for (const match of globSync(pattern, { cwd: root })) files.push(resolve(root, match))
  179. }
  180. files.sort()
  181. const all = files.flatMap(extractBlocks)
  182. const checked = all.filter(b => b.kind === 'check')
  183. const ignored = all.filter(b => b.kind === 'ignore')
  184. // Only compile-eligible fences belong in the opt-out ratio; every other skipped
  185. // kind has an independent verifier named in BlockKind's contract above.
  186. const ratioDenominator = checked.length + ignored.length
  187. if (checked.length === 0) {
  188. console.log('doc-typecheck: no ts code blocks to check.')
  189. process.exit(0)
  190. }
  191. const useBuiltTypes = process.env.DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT === '1'
  192. const compilationError = useBuiltTypes
  193. ? (() => {
  194. const diagnostics = compileBlocksAgainstBuiltTypes(checked)
  195. return diagnostics.length === 0 ? undefined : formatDiagnostics(diagnostics, checked)
  196. })()
  197. : compileBlocksStandalone(checked)
  198. if (compilationError !== undefined) {
  199. console.error('doc-typecheck: documentation code blocks failed to compile.\n')
  200. console.error(compilationError)
  201. process.exit(1)
  202. }
  203. const ratio = ignored.length / ratioDenominator
  204. const skipped = all.length - ratioDenominator
  205. console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out), ${skipped} type-equiv/catalog (checked elsewhere).`)
  206. // Guard against the escape hatch becoming the norm.
  207. if (ratioDenominator >= 4 && ratio > 0.5) {
  208. console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${ratioDenominator}). Make them compile or delete them.`)
  209. process.exit(1)
  210. }