"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTsProgram = exports.createTsCompilerHost = exports.parseTsConfig = void 0;
const path_1 = require("path");
const ts = require("typescript");
/** Parses the TSConfig file to be used in the TS Compiler Program. */
function parseTsConfig(absoluteTsConfigPath) {
    const { config } = ts.readConfigFile(absoluteTsConfigPath, ts.sys.readFile);
    const parseHost = {
        useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
        fileExists: ts.sys.fileExists,
        readFile: ts.sys.readFile,
        readDirectory: ts.sys.readDirectory
    };
    return ts.parseJsonConfigFileContent(config, parseHost, (0, path_1.dirname)(absoluteTsConfigPath), {});
}
exports.parseTsConfig = parseTsConfig;
/** Creates a file host to be used with with a TS Compiler program. */
function createTsCompilerHost(tree, options, basePath) {
    const host = ts.createCompilerHost(options);
    // Read files from the virtual tree to prevent conflicting changes between project migrations
    host.readFile = (fileName) => {
        var _a;
        // The angular schematic tree reads files using paths relative to the project root
        const filePath = (0, path_1.relative)(basePath, fileName);
        const result = (_a = tree.read(filePath)) === null || _a === void 0 ? void 0 : _a.toString();
        // Remove BOM header to prevent TSC parsing errors
        return result === null || result === void 0 ? void 0 : result.replace(/^\uFEFF/, '');
    };
    return host;
}
exports.createTsCompilerHost = createTsCompilerHost;
function createTsProgram(tree, tsConfigPath, basePath) {
    // Resolve the absolute file system path to the TSConfig file. This is needed for the TS Compiler to resolve files correctly.
    const absoluteTsConfigPath = (0, path_1.resolve)(basePath, tsConfigPath);
    const parsed = parseTsConfig(absoluteTsConfigPath);
    const options = Object.assign(Object.assign({}, parsed.options), { skipLibCheck: true, skipDefaultLibCheck: true });
    const host = createTsCompilerHost(tree, options, basePath);
    return ts.createProgram(parsed.fileNames, options, host);
}
exports.createTsProgram = createTsProgram;
//# sourceMappingURL=typescript.js.map