doc-typecheck.ts 10 KB

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