|
| 1 | +import * as Path from "path"; |
| 2 | +import * as File from "fs"; |
| 3 | + |
| 4 | +import ts, { ParsedCommandLine, Program } from "typescript"; |
| 5 | + |
| 6 | +import { Project } from "../project/Project"; |
| 7 | +import { TypeScriptConfigurationParseError } from "./TypeScriptConfigurationParseError"; |
| 8 | +import { TypeScriptConfigurationFileNotFoundError } from "./TypeScriptConfigurationFileNotFoundError"; |
| 9 | +import { TypeScriptConfigurationMissingError } from "./TypeScriptConfigurationMissingError"; |
| 10 | + |
| 11 | + |
| 12 | +export class TypeScriptConfiguration { |
| 13 | + private static parseFile(filePath: string): ParsedCommandLine { |
| 14 | + const file: any = ts.readConfigFile(filePath, ts.sys.readFile); |
| 15 | + |
| 16 | + if (file.error) { |
| 17 | + throw new TypeScriptConfigurationParseError(filePath); |
| 18 | + } |
| 19 | + |
| 20 | + const parsedCommandLine: ParsedCommandLine = ts.parseJsonConfigFileContent( |
| 21 | + file.config, |
| 22 | + ts.sys, |
| 23 | + Path.dirname(filePath) |
| 24 | + ); |
| 25 | + |
| 26 | + if (parsedCommandLine.errors.length > 0) { |
| 27 | + throw new TypeScriptConfigurationParseError(filePath, parsedCommandLine.errors); |
| 28 | + } |
| 29 | + |
| 30 | + return parsedCommandLine; |
| 31 | + } |
| 32 | + |
| 33 | + private readonly filePath: string; |
| 34 | + |
| 35 | + public constructor(project: Project) { |
| 36 | + this.filePath = Path.join(project.getPath(), "tsconfig.json"); |
| 37 | + |
| 38 | + if (!File.existsSync(this.filePath)) { |
| 39 | + throw new TypeScriptConfigurationFileNotFoundError(project.getPath()); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + public getEmittedDirectory(): string { |
| 44 | + const parsedCommandLine: ParsedCommandLine = TypeScriptConfiguration.parseFile(this.filePath); |
| 45 | + const emittedDirectory: string | undefined = parsedCommandLine.options.outDir; |
| 46 | + |
| 47 | + if (!emittedDirectory) { |
| 48 | + throw new TypeScriptConfigurationMissingError(this.filePath, "outDir"); |
| 49 | + } |
| 50 | + |
| 51 | + return emittedDirectory; |
| 52 | + } |
| 53 | + |
| 54 | + public getCompiledDirectoryStructure(): Array<string> { |
| 55 | + const parsedCommandLine: ParsedCommandLine = TypeScriptConfiguration.parseFile(this.filePath); |
| 56 | + |
| 57 | + const program: Program = ts.createProgram({ |
| 58 | + rootNames: parsedCommandLine.fileNames, |
| 59 | + options: parsedCommandLine.options, |
| 60 | + }); |
| 61 | + |
| 62 | + const emittedFilePaths: Array<string> = new Array<string>(); |
| 63 | + const emittedDirectory: string = this.getEmittedDirectory(); |
| 64 | + |
| 65 | + program.emit(undefined, (fileName: string): void => { |
| 66 | + emittedFilePaths.push(fileName); |
| 67 | + }); |
| 68 | + |
| 69 | + return emittedFilePaths.map((filePath: string): string => { |
| 70 | + return Path.relative(emittedDirectory, filePath).replace(/\\/g, "/") |
| 71 | + }); |
| 72 | + } |
| 73 | +} |
0 commit comments