"use strict";
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const glob = require("glob");
const path = require("path");
const ts = require("typescript");
const util_1 = require("../util");
const error_1 = require("./error");
/**
 * TypeScriptWalker is a class which can parse and walk the syntax tree of a
 * TypeScript profile or folder.
 */
class TypeScriptWalker {
    /**
     * Walks all files in the source directory.
     */
    compile(sourceDir) {
        return __awaiter(this, void 0, void 0, function* () {
            return Promise.all(glob.sync(path.join(sourceDir, 'src/**/*.{ts,tsx,jsx,js}')).map((file) => __awaiter(this, void 0, void 0, function* () {
                return this.parseFile(sourceDir, file);
            }))).then(() => this);
        });
    }
    /**
     * Walks a single TypeScript file.
     */
    parseFile(sourceDir, file) {
        return __awaiter(this, void 0, void 0, function* () {
            return util_1.readFile(file).then(contents => {
                const sourceFile = ts.createSourceFile(file, contents.toString(), ts.ScriptTarget.ES2015, true);
                try {
                    this.visit(sourceFile);
                }
                catch (e) {
                    if (e instanceof error_1.DeclarationError) {
                        throw e.makeRelative(sourceDir);
                    }
                    throw e;
                }
                return this;
            });
        });
    }
    /**
     * Parses the string as a TypeScript source file.
     */
    parseString(str) {
        this.visit(ts.createSourceFile('string', str, ts.ScriptTarget.ES2015, true));
        return this;
    }
}
exports.TypeScriptWalker = TypeScriptWalker;
