doc-typecheck.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. /**
  51. * Load host-aggregate settings and redirect workspace aliases to declarations
  52. * from the coordinated build. Doc fragments speak the host vocabulary; the host
  53. * aggregate (never the root solution — it has no compilerOptions) carries the
  54. * workspace paths via tsconfig.base.json.
  55. */
  56. function builtTypeCompilerOptions(): ts.CompilerOptions {
  57. const configPath = join(root, 'tsconfig.host.json')
  58. const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, configHost)
  59. if (!parsed) throw new Error(`doc-typecheck: cannot parse ${configPath}`)
  60. if (parsed.errors.length > 0) {
  61. throw new Error(parsed.errors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'))
  62. }
  63. if (parsed.options.paths === undefined) throw new Error('doc-typecheck: host tsconfig has no workspace paths')
  64. const paths = Object.fromEntries(Object.entries(parsed.options.paths).map(([specifier, candidates]) => [
  65. specifier,
  66. candidates.map(builtDeclarationPath),
  67. ]))
  68. const options: ts.CompilerOptions = {
  69. ...parsed.options,
  70. paths,
  71. noEmit: true,
  72. composite: false,
  73. incremental: false,
  74. declaration: false,
  75. declarationMap: false,
  76. sourceMap: false,
  77. noUnusedLocals: false,
  78. noUnusedParameters: false,
  79. }
  80. delete options.tsBuildInfoFile
  81. return options
  82. }
  83. /** Compile Markdown blocks as virtual files against declarations from the coordinated build. */
  84. function compileBlocksAgainstBuiltTypes(blocks: Block[]): readonly ts.Diagnostic[] {
  85. const options = builtTypeCompilerOptions()
  86. const sources = new Map<string, string>()
  87. for (const [index, block] of blocks.entries()) {
  88. const fileName = resolve(root, '.doc-typecheck', `block-${index}.ts`)
  89. sources.set(fileName, block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  90. }
  91. const baseHost = ts.createCompilerHost(options, true)
  92. const host: ts.CompilerHost = {
  93. ...baseHost,
  94. fileExists(fileName) {
  95. return sources.has(resolve(fileName)) || baseHost.fileExists(fileName)
  96. },
  97. readFile(fileName) {
  98. return sources.get(resolve(fileName)) ?? baseHost.readFile(fileName)
  99. },
  100. getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
  101. const source = sources.get(resolve(fileName))
  102. if (source !== undefined) return ts.createSourceFile(fileName, source, languageVersion, true)
  103. return baseHost.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile)
  104. },
  105. writeFile() {
  106. throw new Error('doc-typecheck: noEmit compilation attempted to write output')
  107. },
  108. }
  109. const program = ts.createProgram([...sources.keys()], options, host)
  110. return ts.getPreEmitDiagnostics(program)
  111. }
  112. /** Render compiler diagnostics with virtual block paths mapped back to Markdown. */
  113. function formatDiagnostics(diagnostics: readonly ts.Diagnostic[], blocks: Block[]): string {
  114. const formatted = ts.formatDiagnostics(diagnostics, {
  115. getCanonicalFileName: fileName => fileName,
  116. getCurrentDirectory: () => root,
  117. getNewLine: () => ts.sys.newLine,
  118. })
  119. return remapBlockPaths(formatted, blocks)
  120. }
  121. /**
  122. * Reuse the host-aggregate references from a temp project one directory below
  123. * root. Doc fragments speak the host vocabulary, so the standalone project
  124. * seeds tsconfig.host.json (never the root solution: flattening host+client
  125. * into one program collides the cordis Context merges).
  126. */
  127. function workspaceReferences(): { path: string }[] {
  128. const file = join(root, 'tsconfig.host.json')
  129. // Parse with TypeScript's own JSONC reader: a regex comment stripper corrupts the `/*/` path
  130. // candidate in the workspace wildcard.
  131. const result = ts.readConfigFile(file, path => readFileSync(path, 'utf8'))
  132. if (result.error) {
  133. throw new Error(`doc-typecheck: cannot read ${file}: ${ts.flattenDiagnosticMessageText(result.error.messageText, '\n')}`)
  134. }
  135. // `config` is typed `any` by the TS API; narrow it to the one field read here.
  136. const { references } = result.config as { references: { path: string }[] }
  137. return references.map(({ path }) => ({
  138. path: path.startsWith('./') ? `../${path.slice(2)}` : `../${path}`,
  139. }))
  140. }
  141. /** The standalone temp project used when no coordinated build owns declaration freshness. */
  142. function tempTsconfig(): string {
  143. return JSON.stringify({
  144. extends: '../tsconfig.host.json',
  145. compilerOptions: {
  146. noUnusedLocals: false,
  147. noUnusedParameters: false,
  148. tsBuildInfoFile: './tsconfig.tsbuildinfo',
  149. },
  150. include: ['block-*.ts'],
  151. references: workspaceReferences(),
  152. })
  153. }
  154. /** Compile blocks through project references for the standalone command. */
  155. function compileBlocksStandalone(blocks: Block[]): string | undefined {
  156. const tmp = mkdtempSync(join(root, '.doc-typecheck-'))
  157. try {
  158. writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig())
  159. for (const [index, block] of blocks.entries()) {
  160. writeFileSync(join(tmp, `block-${index}.ts`), block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  161. }
  162. try {
  163. // Invoke tsc's JS entry through Node instead of a platform-specific shell shim.
  164. execFileSync(process.execPath, ['node_modules/typescript/bin/tsc', '-b', join(tmp, 'tsconfig.json')], {
  165. cwd: root,
  166. stdio: 'pipe',
  167. })
  168. return undefined
  169. } catch (error: unknown) {
  170. const failed = error as { stdout?: Buffer; stderr?: Buffer }
  171. return remapBlockPaths(`${failed.stdout?.toString() ?? ''}${failed.stderr?.toString() ?? ''}`, blocks)
  172. }
  173. } finally {
  174. rmSync(tmp, { recursive: true, force: true })
  175. }
  176. }
  177. /** Map virtual or temporary block paths back to their owning Markdown fences. */
  178. function remapBlockPaths(output: string, blocks: Block[]): string {
  179. return output.replace(/(?:[^\s:()]*[/\\])?block-(\d+)\.ts\((\d+),(\d+)\)/g, (_match, index: string, line: string, column: string) => {
  180. const block = blocks[Number(index)]
  181. if (!block) return `block-${index}.ts(${line},${column})`
  182. return `${block.file} (block at line ${block.line}, +${line}:${column})`
  183. })
  184. }
  185. const markdownGlobs = ['README.md', '.agents/notes/**/*.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md']
  186. const files: string[] = []
  187. for (const pattern of markdownGlobs) {
  188. for (const match of globSync(pattern, { cwd: root })) files.push(resolve(root, match))
  189. }
  190. files.sort()
  191. const all = files.flatMap(extractBlocks)
  192. const checked = all.filter(b => b.kind === 'check')
  193. const ignored = all.filter(b => b.kind === 'ignore')
  194. // Only compile-eligible fences belong in the opt-out ratio; every other skipped
  195. // kind has an independent verifier named in BlockKind's contract above.
  196. const ratioDenominator = checked.length + ignored.length
  197. if (checked.length === 0) {
  198. console.log('doc-typecheck: no ts code blocks to check.')
  199. process.exit(0)
  200. }
  201. const useBuiltTypes = process.env.DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT === '1'
  202. const compilationError = useBuiltTypes
  203. ? (() => {
  204. const diagnostics = compileBlocksAgainstBuiltTypes(checked)
  205. return diagnostics.length === 0 ? undefined : formatDiagnostics(diagnostics, checked)
  206. })()
  207. : compileBlocksStandalone(checked)
  208. if (compilationError !== undefined) {
  209. console.error('doc-typecheck: documentation code blocks failed to compile.\n')
  210. console.error(compilationError)
  211. process.exit(1)
  212. }
  213. const ratio = ignored.length / ratioDenominator
  214. const skipped = all.length - ratioDenominator
  215. console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out), ${skipped} type-equiv/catalog (checked elsewhere).`)
  216. // Guard against the escape hatch becoming the norm.
  217. if (ratioDenominator >= 4 && ratio > 0.5) {
  218. console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${ratioDenominator}). Make them compile or delete them.`)
  219. process.exit(1)
  220. }