ts-simple-ast
Version:
TypeScript compiler wrapper for AST navigation and code generation.
420 lines (419 loc) • 18.7 kB
JavaScript
"use strict";
var __assign = (this && this.__assign)/* istanbul ignore next */ || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __generator = (this && this.__generator)/* istanbul ignore next */ || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values)/* istanbul ignore next */ || function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
};
var __read = (this && this.__read)/* istanbul ignore next */ || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread)/* istanbul ignore next */ || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var minimatch_1 = require("minimatch");
var errors = require("./errors");
var utils_1 = require("./utils");
var fileSystem_1 = require("./fileSystem");
var GlobalContainer_1 = require("./GlobalContainer");
/**
* Compiler wrapper.
*/
var TsSimpleAst = /** @class */ (function () {
/**
* Initializes a new instance.
* @param options - Optional options.
* @param fileSystem - Optional file system host. Useful for mocking access to the file system.
*/
function TsSimpleAst(options, fileSystem) {
if (options === void 0) { options = {}; }
if (fileSystem != null && options.useVirtualFileSystem)
throw new errors.InvalidOperationError("Cannot provide a file system when specifying to use a virtual file system.");
else if (options.useVirtualFileSystem)
fileSystem = new fileSystem_1.VirtualFileSystemHost();
else if (fileSystem == null)
fileSystem = new fileSystem_1.DefaultFileSystemHost();
this.global = new GlobalContainer_1.GlobalContainer(fileSystem, getCompilerOptionsFromOptions(options, fileSystem), { createLanguageService: true });
if (options.manipulationSettings != null)
this.global.manipulationSettings.set(options.manipulationSettings);
}
Object.defineProperty(TsSimpleAst.prototype, "manipulationSettings", {
/** Gets the manipulation settings. */
get: function () {
return this.global.manipulationSettings;
},
enumerable: true,
configurable: true
});
/**
* Adds an existing directory from the path or returns undefined if it doesn't exist.
*
* Will return the directory if it was already added.
* @param dirPath - Path to add the directory at.
*/
TsSimpleAst.prototype.addDirectoryIfExists = function (dirPath) {
dirPath = utils_1.FileUtils.getStandardizedAbsolutePath(this.global.fileSystem, dirPath);
return this.global.compilerFactory.getDirectoryFromPath(dirPath);
};
/**
* Adds an existing directory from the path or throws if it doesn't exist.
*
* Will return the directory if it was already added.
* @param dirPath - Path to add the directory at.
* @throws DirectoryNotFoundError when the directory does not exist.
*/
TsSimpleAst.prototype.addExistingDirectory = function (dirPath) {
var directory = this.addDirectoryIfExists(dirPath);
if (directory == null)
throw new errors.DirectoryNotFoundError(utils_1.FileUtils.getStandardizedAbsolutePath(this.global.fileSystem, dirPath));
return directory;
};
/**
* Creates a directory at the specified path.
* Note: Will not save the directory to disk until one of its source files is saved.
* @param dirPath - Path to create the directory at.
* @throws - InvalidOperationError if a directory already exists at the provided file path.
*/
TsSimpleAst.prototype.createDirectory = function (dirPath) {
dirPath = utils_1.FileUtils.getStandardizedAbsolutePath(this.global.fileSystem, dirPath);
return this.global.compilerFactory.createDirectory(dirPath);
};
/**
* Gets a directory by the specified path or throws it doesn't exist.
* @param dirPath - Path to create the directory at.
*/
TsSimpleAst.prototype.getDirectoryOrThrow = function (dirPath) {
var _this = this;
return errors.throwIfNullOrUndefined(this.getDirectory(dirPath), function () { return "Could not find a directory at the specified path: " + utils_1.FileUtils.getStandardizedAbsolutePath(_this.global.fileSystem, dirPath); });
};
/**
* Gets a directory by the specified path or returns undefined if it doesn't exist.
* @param dirPath - Directory path.
*/
TsSimpleAst.prototype.getDirectory = function (dirPath) {
dirPath = utils_1.FileUtils.getStandardizedAbsolutePath(this.global.fileSystem, dirPath);
return this.global.compilerFactory.getDirectory(dirPath);
};
/**
* Gets all the directories.
*/
TsSimpleAst.prototype.getDirectories = function () {
return utils_1.ArrayUtils.from(this.global.compilerFactory.getDirectoriesByDepth());
};
/**
* Gets the directories without a parent.
*/
TsSimpleAst.prototype.getRootDirectories = function () {
return this.global.compilerFactory.getOrphanDirectories();
};
/**
* Add source files based on file globs.
* @param fileGlobs - File globs to add files based on.
* @returns The matched source files.
*/
TsSimpleAst.prototype.addExistingSourceFiles = function () {
var fileGlobs = [];
for (var _i = 0; _i < arguments.length; _i++) {
fileGlobs[_i] = arguments[_i];
}
var sourceFiles = [];
try {
for (var _a = __values(this.global.fileSystem.glob(fileGlobs)), _b = _a.next(); !_b.done; _b = _a.next()) {
var filePath = _b.value;
var sourceFile = this.addSourceFileIfExists(filePath);
if (sourceFile != null)
sourceFiles.push(sourceFile);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
}
finally { if (e_1) throw e_1.error; }
}
return sourceFiles;
var e_1, _c;
};
/**
* Adds a source file from a file path if it exists or returns undefined.
*
* Will return the source file if it was already added.
* @param filePath - File path to get the file from.
*/
TsSimpleAst.prototype.addSourceFileIfExists = function (filePath) {
return this.global.compilerFactory.getSourceFileFromFilePath(filePath);
};
/**
* Adds an existing source file from a file path or throws if it doesn't exist.
*
* Will return the source file if it was already added.
* @param filePath - File path to get the file from.
* @throws FileNotFoundError when the file is not found.
*/
TsSimpleAst.prototype.addExistingSourceFile = function (filePath) {
var sourceFile = this.addSourceFileIfExists(filePath);
if (sourceFile == null) {
var absoluteFilePath = utils_1.FileUtils.getStandardizedAbsolutePath(this.global.fileSystem, filePath);
throw new errors.FileNotFoundError(absoluteFilePath);
}
return sourceFile;
};
TsSimpleAst.prototype.createSourceFile = function (filePath, structureOrText) {
return this.global.compilerFactory.createSourceFile(filePath, structureOrText);
};
/**
* Removes a source file from the AST.
* @param sourceFile - Source file to remove.
* @returns True if removed.
*/
TsSimpleAst.prototype.removeSourceFile = function (sourceFile) {
var previouslyForgotten = sourceFile.wasForgotten();
sourceFile.forget();
return !previouslyForgotten;
};
TsSimpleAst.prototype.getSourceFileOrThrow = function (fileNameOrSearchFunction) {
var sourceFile = this.getSourceFile(fileNameOrSearchFunction);
if (sourceFile == null) {
if (typeof fileNameOrSearchFunction === "string")
throw new errors.InvalidOperationError("Could not find source file based on the provided name or path: " + fileNameOrSearchFunction + ".");
else
throw new errors.InvalidOperationError("Could not find source file based on the provided condition.");
}
return sourceFile;
};
TsSimpleAst.prototype.getSourceFile = function (fileNameOrSearchFunction) {
var searchFunction = fileNameOrSearchFunction;
if (typeof fileNameOrSearchFunction === "string")
searchFunction = function (def) { return utils_1.FileUtils.filePathMatches(def.getFilePath(), fileNameOrSearchFunction); };
return utils_1.ArrayUtils.find(this.global.compilerFactory.getSourceFilesByDirectoryDepth(), searchFunction);
};
/**
* Gets all the source files contained in the compiler wrapper.
* @param globPattern - Glob pattern for filtering out the source files.
*/
TsSimpleAst.prototype.getSourceFiles = function (globPattern) {
var sourceFiles = this.global.compilerFactory.getSourceFilesByDirectoryDepth();
if (typeof globPattern === "string")
return utils_1.ArrayUtils.from(getFilteredSourceFiles());
else
return utils_1.ArrayUtils.from(sourceFiles);
function getFilteredSourceFiles() {
var mm, sourceFiles_1, sourceFiles_1_1, sourceFile, e_2_1, e_2, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
mm = new minimatch_1.Minimatch(globPattern, { matchBase: true });
_b.label = 1;
case 1:
_b.trys.push([1, 6, 7, 8]);
sourceFiles_1 = __values(sourceFiles), sourceFiles_1_1 = sourceFiles_1.next();
_b.label = 2;
case 2:
if (!!sourceFiles_1_1.done) return [3 /*break*/, 5];
sourceFile = sourceFiles_1_1.value;
if (!mm.match(sourceFile.getFilePath())) return [3 /*break*/, 4];
return [4 /*yield*/, sourceFile];
case 3:
_b.sent();
_b.label = 4;
case 4:
sourceFiles_1_1 = sourceFiles_1.next();
return [3 /*break*/, 2];
case 5: return [3 /*break*/, 8];
case 6:
e_2_1 = _b.sent();
e_2 = { error: e_2_1 };
return [3 /*break*/, 8];
case 7:
try {
if (sourceFiles_1_1 && !sourceFiles_1_1.done && (_a = sourceFiles_1.return)) _a.call(sourceFiles_1);
}
finally { if (e_2) throw e_2.error; }
return [7 /*endfinally*/];
case 8: return [2 /*return*/];
}
});
}
};
/**
* Saves all the unsaved source files.
*/
TsSimpleAst.prototype.saveUnsavedSourceFiles = function () {
return Promise.all(this.getUnsavedSourceFiles().map(function (f) { return f.save(); }));
};
/**
* Saves all the unsaved source files synchronously.
*
* Remarks: This might be very slow compared to the asynchronous version if there are a lot of files.
*/
TsSimpleAst.prototype.saveUnsavedSourceFilesSync = function () {
try {
// sidenote: I wish I could do something like in c# where I do this all asynchronously then
// wait synchronously on the task. It would not be as bad as this is performance wise. Maybe there
// is a way, but people just shouldn't be using this method unless they're really lazy.
for (var _a = __values(this.getUnsavedSourceFiles()), _b = _a.next(); !_b.done; _b = _a.next()) {
var file = _b.value;
file.saveSync();
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
}
finally { if (e_3) throw e_3.error; }
}
var e_3, _c;
};
TsSimpleAst.prototype.getUnsavedSourceFiles = function () {
return utils_1.ArrayUtils.from(getUnsavedIterator(this.global.compilerFactory.getSourceFilesByDirectoryDepth()));
function getUnsavedIterator(sourceFiles) {
var sourceFiles_2, sourceFiles_2_1, sourceFile, e_4_1, e_4, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 5, 6, 7]);
sourceFiles_2 = __values(sourceFiles), sourceFiles_2_1 = sourceFiles_2.next();
_b.label = 1;
case 1:
if (!!sourceFiles_2_1.done) return [3 /*break*/, 4];
sourceFile = sourceFiles_2_1.value;
if (!!sourceFile.isSaved()) return [3 /*break*/, 3];
return [4 /*yield*/, sourceFile];
case 2:
_b.sent();
_b.label = 3;
case 3:
sourceFiles_2_1 = sourceFiles_2.next();
return [3 /*break*/, 1];
case 4: return [3 /*break*/, 7];
case 5:
e_4_1 = _b.sent();
e_4 = { error: e_4_1 };
return [3 /*break*/, 7];
case 6:
try {
if (sourceFiles_2_1 && !sourceFiles_2_1.done && (_a = sourceFiles_2.return)) _a.call(sourceFiles_2);
}
finally { if (e_4) throw e_4.error; }
return [7 /*endfinally*/];
case 7: return [2 /*return*/];
}
});
}
};
/**
* Gets the compiler diagnostics.
*/
TsSimpleAst.prototype.getDiagnostics = function () {
return __spread(this.global.program.getSyntacticDiagnostics(), this.global.program.getSemanticDiagnostics(), this.global.program.getDeclarationDiagnostics());
};
/**
* Gets the pre-emit diagnostics.
*/
TsSimpleAst.prototype.getPreEmitDiagnostics = function () {
return this.global.program.getPreEmitDiagnostics();
};
/**
* Gets the language service.
*/
TsSimpleAst.prototype.getLanguageService = function () {
return this.global.languageService;
};
/**
* Gets the program.
*/
TsSimpleAst.prototype.getProgram = function () {
return this.global.program;
};
/**
* Gets the type checker.
*/
TsSimpleAst.prototype.getTypeChecker = function () {
return this.global.typeChecker;
};
/**
* Gets the file system.
*/
TsSimpleAst.prototype.getFileSystem = function () {
return this.global.fileSystem;
};
/**
* Emits all the source files.
* @param emitOptions - Optional emit options.
*/
TsSimpleAst.prototype.emit = function (emitOptions) {
if (emitOptions === void 0) { emitOptions = {}; }
return this.global.program.emit(emitOptions);
};
/**
* Gets the compiler options.
*/
TsSimpleAst.prototype.getCompilerOptions = function () {
// return a copy
return __assign({}, this.global.compilerOptions);
};
TsSimpleAst.prototype.forgetNodesCreatedInBlock = function (block) {
return this.global.compilerFactory.forgetNodesCreatedInBlock(block);
};
return TsSimpleAst;
}());
exports.TsSimpleAst = TsSimpleAst;
function getCompilerOptionsFromOptions(options, fileSystem) {
return __assign({}, (options.tsConfigFilePath == null ? {} : utils_1.getCompilerOptionsFromTsConfig(options.tsConfigFilePath, fileSystem)), (options.compilerOptions || {}));
}