doc-typecheck.ts 9.5 KB

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