doc-typecheck.ts 10 KB

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