ts-project.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. /**
  2. * Shared TypeScript Program construction for repository gates that need real
  3. * cross-file symbols and types instead of isolated syntax trees.
  4. */
  5. import { relative, resolve } from 'node:path'
  6. import ts from 'typescript'
  7. interface ProjectGraph {
  8. rootNames: string[]
  9. options: ts.CompilerOptions
  10. }
  11. const configHost: ts.ParseConfigFileHost = {
  12. useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
  13. readDirectory: (...args) => ts.sys.readDirectory(...args),
  14. fileExists: fileName => ts.sys.fileExists(fileName),
  15. readFile: fileName => ts.sys.readFile(fileName),
  16. getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
  17. onUnRecoverableConfigFileDiagnostic(diagnostic) {
  18. throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))
  19. },
  20. }
  21. /**
  22. * Parse the host aggregate tsconfig and flatten all referenced projects into one
  23. * semantic graph. Never seed the root solution: flattening host+client into one
  24. * program collides the cordis Context merges.
  25. */
  26. function loadProjectGraph(projectRoot: string): ProjectGraph {
  27. const rootConfigPath = resolve(projectRoot, 'tsconfig.host.json')
  28. const rootConfig = parseConfig(rootConfigPath)
  29. const rootNames = new Set<string>()
  30. const visited = new Set<string>()
  31. const collect = (configPath: string, parsed: ts.ParsedCommandLine): void => {
  32. if (visited.has(configPath)) return
  33. visited.add(configPath)
  34. for (const fileName of parsed.fileNames) rootNames.add(fileName)
  35. for (const reference of parsed.projectReferences ?? []) {
  36. const referencePath = ts.resolveProjectReferencePath(reference)
  37. collect(referencePath, parseConfig(referencePath))
  38. }
  39. }
  40. collect(rootConfigPath, rootConfig)
  41. return {
  42. rootNames: [...rootNames],
  43. options: rootConfig.options,
  44. }
  45. }
  46. /** Parse one config file and fail loud on any config diagnostic. */
  47. function parseConfig(configPath: string): ts.ParsedCommandLine {
  48. const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, configHost)
  49. if (!parsed) throw new Error(`cannot parse TypeScript config ${configPath}`)
  50. if (parsed.errors.length > 0) {
  51. throw new Error(parsed.errors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'))
  52. }
  53. return parsed
  54. }
  55. /** Disable emit-only options after loading the root solution config. */
  56. function semanticCompilerOptions(options: ts.CompilerOptions): ts.CompilerOptions {
  57. return {
  58. ...options,
  59. noEmit: true,
  60. composite: false,
  61. declaration: false,
  62. declarationMap: false,
  63. sourceMap: false,
  64. incremental: false,
  65. }
  66. }
  67. /** A repository-scoped TypeScript Program and its shared TypeChecker. */
  68. export class TypeScriptProject {
  69. /** The bound cross-file TypeScript program. */
  70. readonly program: ts.Program
  71. /** The checker shared by every semantic query in this project. */
  72. readonly checker: ts.TypeChecker
  73. constructor(private readonly projectRoot: string) {
  74. const graph = loadProjectGraph(projectRoot)
  75. this.program = ts.createProgram(graph.rootNames, semanticCompilerOptions(graph.options))
  76. this.checker = this.program.getTypeChecker()
  77. }
  78. /**
  79. * Return every source file loaded into the flattened root project graph.
  80. * @returns program source files, including libraries and external dependencies.
  81. */
  82. sourceFiles(): readonly ts.SourceFile[] {
  83. return this.program.getSourceFiles()
  84. }
  85. /**
  86. * Render a loaded source file relative to the project root.
  87. * @param sourceFile - a source file from this project.
  88. * @returns a slash-separated repository-relative path.
  89. */
  90. relativePath(sourceFile: ts.SourceFile): string {
  91. return relative(this.projectRoot, sourceFile.fileName).replaceAll('\\', '/')
  92. }
  93. /**
  94. * Return one program source file by repository-relative path.
  95. * @param relativePath - path relative to the project root.
  96. * @returns the source file bound into this project.
  97. * @throws if a requested root or imported source was not loaded.
  98. */
  99. sourceFile(relativePath: string): ts.SourceFile {
  100. const sourceFile = this.program.getSourceFile(resolve(this.projectRoot, relativePath))
  101. if (!sourceFile) throw new Error(`TypeScript project did not load ${relativePath}`)
  102. return sourceFile
  103. }
  104. }