"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments)).next());
    });
};
const path = require("path");
const os = require("os");
const temp = require("temp");
const decorators_1 = require("../decorators");
const constants_1 = require("../constants");
temp.track();
class TypeScriptService {
    constructor($childProcess, $fs, $logger, $npmService, $options, $projectConstants, $processService, $errors) {
        this.$childProcess = $childProcess;
        this.$fs = $fs;
        this.$logger = $logger;
        this.$npmService = $npmService;
        this.$options = $options;
        this.$projectConstants = $projectConstants;
        this.$processService = $processService;
        this.$errors = $errors;
    }
    transpile(projectDir, typeScriptFiles, definitionFiles, options) {
        return __awaiter(this, void 0, void 0, function* () {
            options = options || {};
            let compilerOptions = this.getCompilerOptions(projectDir, options);
            let typeScriptCompilerSettings = yield this.getTypeScriptCompilerSettings({ useLocalTypeScriptCompiler: options.useLocalTypeScriptCompiler });
            this.noEmitOnError = compilerOptions.noEmitOnError;
            this.typeScriptFiles = typeScriptFiles || [];
            this.definitionFiles = definitionFiles || [];
            let runTranspilationOptions = { compilerOptions };
            if (this.typeScriptFiles.length > 0) {
                let typeScriptDefinitionsFiles = [];
                if (!this.hasTsConfigFile(projectDir)) {
                    typeScriptDefinitionsFiles = this.getDefaultTypeScriptDefinitionsFiles(options.pathToDefaultDefinitionFiles);
                }
                typeScriptDefinitionsFiles = typeScriptDefinitionsFiles.concat(this.getTypeScriptFilesData(projectDir).definitionFiles);
                let filesToTranspile = this.typeScriptFiles.concat(typeScriptDefinitionsFiles);
                this.$logger.out("Compiling...".yellow);
                _.each(this.typeScriptFiles, file => {
                    this.$logger.out(`### Compile ${file}`.cyan);
                });
                runTranspilationOptions.filesToTranspile = filesToTranspile;
            }
            this.$logger.out(`Using tsc version ${typeScriptCompilerSettings.version}`.cyan);
            return yield this.runTranspilation(projectDir, typeScriptCompilerSettings.pathToCompiler, runTranspilationOptions);
        });
    }
    getTypeScriptFilesData(projectDir) {
        let rootNodeModules = path.join(projectDir, constants_1.NODE_MODULES_DIR_NAME);
        let projectFiles = this.$fs.enumerateFilesInDirectorySync(projectDir, (fileName, fstat) => fileName !== rootNodeModules);
        let typeScriptFiles = _.filter(projectFiles, this.isTypeScriptFile);
        let definitionFiles = _.filter(typeScriptFiles, file => _.endsWith(file, constants_1.FileExtensions.TYPESCRIPT_DEFINITION_FILE));
        return { definitionFiles: definitionFiles, typeScriptFiles: _.difference(typeScriptFiles, definitionFiles) };
    }
    isTypeScriptProject(projectDir) {
        let typeScriptFilesData = this.getTypeScriptFilesData(projectDir);
        return !!typeScriptFilesData.typeScriptFiles.length;
    }
    isTypeScriptFile(file) {
        return path.extname(file) === constants_1.FileExtensions.TYPESCRIPT_FILE;
    }
    hasTsConfigFile(projectDir) {
        return this.$fs.exists(this.getPathToTsConfigFile(projectDir));
    }
    getPathToTsConfigFile(projectDir) {
        return path.join(projectDir, this.$projectConstants.TSCONFIG_JSON_NAME);
    }
    getCompilerOptions(projectDir, options) {
        let tsConfigFile;
        let pathToConfigJsonFile = this.getPathToTsConfigFile(projectDir);
        if (this.hasTsConfigFile(projectDir)) {
            tsConfigFile = this.$fs.readJson(pathToConfigJsonFile);
        }
        tsConfigFile = tsConfigFile || { compilerOptions: {} };
        let compilerOptions = options.compilerOptions || {};
        let defaultOptions = options.defaultCompilerOptions || {};
        let compilerOptionsKeys = _.union(_.keys(compilerOptions), _.keys(tsConfigFile.compilerOptions), _.keys(defaultOptions));
        let result = {};
        _.each(compilerOptionsKeys, (key) => {
            result[key] = this.getCompilerOptionByKey(key, compilerOptions, tsConfigFile.compilerOptions, defaultOptions);
        });
        result.noEmitOnError = result.noEmitOnError || false;
        return result;
    }
    getCompilerOptionByKey(key, compilerOptions, tsConfigFileOptions, defaultOptions) {
        if (_.has(compilerOptions, key)) {
            return compilerOptions[key];
        }
        if (_.has(tsConfigFileOptions, key)) {
            return tsConfigFileOptions[key];
        }
        return defaultOptions[key];
    }
    getTypeScriptCompilerSettings(options) {
        return __awaiter(this, void 0, void 0, function* () {
            let typeScriptInNodeModulesDir = path.join(constants_1.NODE_MODULES_DIR_NAME, TypeScriptService.TYPESCRIPT_MODULE_NAME);
            if (!this.typeScriptModuleFilePath) {
                if (options.useLocalTypeScriptCompiler) {
                    let typeScriptJsFilePath = require.resolve(TypeScriptService.TYPESCRIPT_MODULE_NAME);
                    this.typeScriptModuleFilePath = typeScriptJsFilePath.substring(0, typeScriptJsFilePath.indexOf(typeScriptInNodeModulesDir) + typeScriptInNodeModulesDir.length);
                }
                else {
                    let typeScriptModuleInstallationDir = this.createTempDirectoryForTsc();
                    let pluginToInstall = {
                        name: TypeScriptService.TYPESCRIPT_MODULE_NAME,
                        version: TypeScriptService.DEFAULT_TSC_VERSION,
                        installTypes: false
                    };
                    yield this.$npmService.install(typeScriptModuleInstallationDir, pluginToInstall);
                    this.typeScriptModuleFilePath = path.join(typeScriptModuleInstallationDir, typeScriptInNodeModulesDir);
                }
            }
            let typeScriptCompilerPath = path.join(this.typeScriptModuleFilePath, "lib", "tsc");
            let typeScriptCompilerVersion = this.$fs.readJson(path.join(this.typeScriptModuleFilePath, this.$projectConstants.PACKAGE_JSON_NAME)).version;
            return { pathToCompiler: typeScriptCompilerPath, version: typeScriptCompilerVersion };
        });
    }
    runTranspilation(projectDir, typeScriptCompilerPath, options) {
        return __awaiter(this, void 0, void 0, function* () {
            options = options || {};
            let startTime = new Date().getTime();
            let params = _([])
                .concat(typeScriptCompilerPath)
                .concat(options.filesToTranspile || [])
                .concat(this.getTypeScriptCompilerOptionsAsArguments(options.compilerOptions) || [])
                .value();
            let output = yield this.$childProcess.spawnFromEvent(process.argv[0], params, "close", { cwd: projectDir }, { throwError: false });
            let compilerOutput = output.stderr || output.stdout;
            let compilerMessages = this.getCompilerMessages(compilerOutput);
            this.logCompilerMessages(compilerMessages, compilerOutput);
            let endTime = new Date().getTime();
            let time = (endTime - startTime) / 1000;
            this.$logger.out(`${os.EOL}Success: ${time.toFixed(2)}s${os.EOL}.`.green);
            this.startWatchProcess(params, projectDir);
            return compilerOutput;
        });
    }
    startWatchProcess(params, projectDir) {
        if (!this._watchProcess && this.$options.watch) {
            params.push("--watch");
            this._watchProcess = this.$childProcess.spawn(process.argv[0], params, { cwd: projectDir });
            this.$processService.attachToProcessExitSignals(null, this._watchProcess.kill);
        }
    }
    getCompilerMessages(compilerOutput) {
        let level1ErrorCount = 0, level5ErrorCount = 0, nonEmitPreventingWarningCount = 0;
        let hasPreventEmitErrors = _.reduce(compilerOutput.split("\n"), (memo, errorMsg) => {
            let isPreventEmitError = !!this.noEmitOnError;
            if (errorMsg.search(/error TS1\d+:/) >= 0) {
                level1ErrorCount += 1;
            }
            else if (errorMsg.search(/error TS5\d+:/) >= 0) {
                level5ErrorCount += 1;
            }
            else if (errorMsg.search(/error TS\d+:/) >= 0) {
                nonEmitPreventingWarningCount += 1;
            }
            return memo || isPreventEmitError;
        }, false) || false;
        return {
            level1ErrorCount,
            level5ErrorCount,
            nonEmitPreventingWarningCount,
            hasPreventEmitErrors
        };
    }
    logCompilerMessages(compilerMessages, errorMessage) {
        let level1ErrorCount = compilerMessages.level1ErrorCount, level5ErrorCount = compilerMessages.level5ErrorCount, nonEmitPreventingWarningCount = compilerMessages.nonEmitPreventingWarningCount, hasPreventEmitErrors = compilerMessages.hasPreventEmitErrors;
        if (level1ErrorCount + level5ErrorCount + nonEmitPreventingWarningCount > 0) {
            let colorizedMessage = (level1ErrorCount + level5ErrorCount > 0) ? ">>>".red : ">>>".green;
            this.$logger.out(colorizedMessage);
            let errorTitle = "";
            if (level5ErrorCount > 0) {
                errorTitle += this.composeErrorTitle(level5ErrorCount, "compiler flag error");
            }
            if (level1ErrorCount > 0) {
                errorTitle += this.composeErrorTitle(level1ErrorCount, "syntax error");
            }
            if (nonEmitPreventingWarningCount > 0) {
                if (!level1ErrorCount && !level5ErrorCount && this.noEmitOnError) {
                    errorTitle += this.composeErrorTitle(nonEmitPreventingWarningCount, "non-emit-preventing type errors, but output is not generated as noEmitOnError option is true.");
                }
                else {
                    errorTitle += this.composeErrorTitle(nonEmitPreventingWarningCount, "non-emit-preventing type warning");
                }
            }
            if (hasPreventEmitErrors) {
                this.$errors.failWithoutHelp(`${os.EOL}${errorTitle}${os.EOL}${errorMessage.red}${os.EOL}${">>> ".red}`);
            }
            else {
                this.$logger.out(errorTitle);
                this.$logger.warn(errorMessage);
                this.$logger.out(">>>".green);
            }
        }
    }
    composeErrorTitle(count, title) {
        return `${count} ${title}${(count === 1) ? '' : 's'} ${os.EOL}`;
    }
    getTypeScriptCompilerOptionsAsArguments(options) {
        this.noEmitOnError = options.noEmitOnError;
        return _(options)
            .keys()
            .map((option) => {
            let value = options[option];
            if (typeof (value) === "string") {
                return [`--${option}`, value];
            }
            else if (value) {
                return [`--${option}`];
            }
            else {
                return null;
            }
        })
            .filter(argument => !!argument)
            .flatten()
            .value();
    }
    getDefaultTypeScriptDefinitionsFiles(defaultTypeScriptDefinitionsFilesPath) {
        if (!this.$fs.exists(defaultTypeScriptDefinitionsFilesPath)) {
            return [];
        }
        let defaultDefinitionsFiles = this.$fs.readDirectory(defaultTypeScriptDefinitionsFilesPath);
        let remainingDefaultDefinitionFiles = _.filter(defaultDefinitionsFiles, defFile => !_.some(this.definitionFiles, f => path.basename(f) === defFile));
        return _.map(remainingDefaultDefinitionFiles, (definitionFilePath) => {
            return path.join(defaultTypeScriptDefinitionsFilesPath, definitionFilePath);
        }).concat(this.definitionFiles);
    }
    createTempDirectoryForTsc() {
        let tempDir = temp.mkdirSync(`typescript-compiler-${TypeScriptService.DEFAULT_TSC_VERSION}`);
        this.$fs.writeJson(path.join(tempDir, this.$projectConstants.PACKAGE_JSON_NAME), { name: "tsc-container", version: "1.0.0" });
        return tempDir;
    }
}
TypeScriptService.DEFAULT_TSC_VERSION = "2.0.10";
TypeScriptService.TYPESCRIPT_MODULE_NAME = "typescript";
__decorate([
    decorators_1.exportedPromise("typeScriptService")
], TypeScriptService.prototype, "transpile", null);
exports.TypeScriptService = TypeScriptService;
$injector.register("typeScriptService", TypeScriptService);
