ts-project.ts 4.2 KB

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