doc-typecheck.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. 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 markdownFences(readFileSync(absPath, 'utf8')).flatMap((fence) => {
  43. const kind = KIND_BY_INFO[fence.info]
  44. return kind === undefined ? [] : [{ file, line: fence.line, kind, code: fence.code }]
  45. })
  46. }
  47. const configHost: ts.ParseConfigFileHost = {
  48. ...ts.sys,
  49. getCurrentDirectory: () => root,
  50. onUnRecoverableConfigFileDiagnostic(diagnostic) {
  51. throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))
  52. },
  53. }
  54. /**
  55. * Load host-aggregate settings and redirect workspace aliases to declarations
  56. * from the coordinated build. Doc fragments speak the host vocabulary; the host
  57. * aggregate (never the root solution — it has no compilerOptions) carries the
  58. * workspace paths via tsconfig.base.json.
  59. */
  60. function builtTypeCompilerOptions(): ts.CompilerOptions {
  61. const configPath = join(root, 'tsconfig.host.json')
  62. const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, configHost)
  63. if (!parsed) throw new Error(`doc-typecheck: cannot parse ${configPath}`)
  64. if (parsed.errors.length > 0) {
  65. throw new Error(parsed.errors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'))
  66. }
  67. if (parsed.options.paths === undefined) throw new Error('doc-typecheck: host tsconfig has no workspace paths')
  68. const paths = Object.fromEntries(Object.entries(parsed.options.paths).map(([specifier, candidates]) => [
  69. specifier,
  70. candidates.map(builtDeclarationPath),
  71. ]))
  72. const options: ts.CompilerOptions = {
  73. ...parsed.options,
  74. paths,
  75. noEmit: true,
  76. composite: false,
  77. incremental: false,
  78. declaration: false,
  79. declarationMap: false,
  80. sourceMap: false,
  81. noUnusedLocals: false,
  82. noUnusedParameters: false,
  83. }
  84. delete options.tsBuildInfoFile
  85. return options
  86. }
  87. /** Compile Markdown blocks as virtual files against declarations from the coordinated build. */
  88. function compileBlocksAgainstBuiltTypes(blocks: Block[]): readonly ts.Diagnostic[] {
  89. const options = builtTypeCompilerOptions()
  90. const sources = new Map<string, string>()
  91. for (const [index, block] of blocks.entries()) {
  92. const fileName = resolve(root, '.doc-typecheck', `block-${index}.ts`)
  93. sources.set(fileName, block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  94. }
  95. const baseHost = ts.createCompilerHost(options, true)
  96. const host: ts.CompilerHost = {
  97. ...baseHost,
  98. fileExists(fileName) {
  99. return sources.has(resolve(fileName)) || baseHost.fileExists(fileName)
  100. },
  101. readFile(fileName) {
  102. return sources.get(resolve(fileName)) ?? baseHost.readFile(fileName)
  103. },
  104. getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
  105. const source = sources.get(resolve(fileName))
  106. if (source !== undefined) return ts.createSourceFile(fileName, source, languageVersion, true)
  107. return baseHost.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile)
  108. },
  109. writeFile() {
  110. throw new Error('doc-typecheck: noEmit compilation attempted to write output')
  111. },
  112. }
  113. const program = ts.createProgram([...sources.keys()], options, host)
  114. return ts.getPreEmitDiagnostics(program)
  115. }
  116. /** Render compiler diagnostics with virtual block paths mapped back to Markdown. */
  117. function formatDiagnostics(diagnostics: readonly ts.Diagnostic[], blocks: Block[]): string {
  118. const formatted = ts.formatDiagnostics(diagnostics, {
  119. getCanonicalFileName: fileName => fileName,
  120. getCurrentDirectory: () => root,
  121. getNewLine: () => ts.sys.newLine,
  122. })
  123. return remapBlockPaths(formatted, blocks)
  124. }
  125. /**
  126. * Reuse the host-aggregate references from a temp project one directory below
  127. * root. Doc fragments speak the host vocabulary, so the standalone project
  128. * seeds tsconfig.host.json (never the root solution: flattening host+client
  129. * into one program collides the cordis Context merges).
  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 })) files.push(resolve(root, match))
  193. }
  194. files.sort()
  195. const extracted = files.flatMap(extractBlocks)
  196. const { primary: all, derivatives } = partitionPairedMarkdownDerivatives(
  197. extracted,
  198. block => block.file,
  199. block => `${block.kind}\0${block.code}`,
  200. )
  201. const checked = all.filter(b => b.kind === 'check')
  202. const ignored = all.filter(b => b.kind === 'ignore')
  203. // Only compile-eligible fences belong in the opt-out ratio; every other skipped
  204. // kind has an independent verifier named in BlockKind's contract above.
  205. const ratioDenominator = checked.length + ignored.length
  206. if (checked.length === 0) {
  207. console.log('doc-typecheck: no ts code blocks to check.')
  208. process.exit(0)
  209. }
  210. const useBuiltTypes = process.env.DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT === '1'
  211. const compilationError = useBuiltTypes
  212. ? (() => {
  213. const diagnostics = compileBlocksAgainstBuiltTypes(checked)
  214. return diagnostics.length === 0 ? undefined : formatDiagnostics(diagnostics, checked)
  215. })()
  216. : compileBlocksStandalone(checked)
  217. if (compilationError !== undefined) {
  218. console.error('doc-typecheck: documentation code blocks failed to compile.\n')
  219. console.error(compilationError)
  220. process.exit(1)
  221. }
  222. const ratio = ignored.length / ratioDenominator
  223. const skipped = all.length - ratioDenominator
  224. 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).`)
  225. // Guard against the escape hatch becoming the norm.
  226. if (ratioDenominator >= 4 && ratio > 0.5) {
  227. console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${ratioDenominator}). Make them compile or delete them.`)
  228. process.exit(1)
  229. }