function ClassificationTypeNames() {
}n/a
function CoreServicesShimHostAdapter(shimHost) {
var _this = this;
this.shimHost = shimHost;
this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false
;
if ("directoryExists" in this.shimHost) {
this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
}
if ("realpath" in this.shimHost) {
this.realpath = function (path) { return _this.shimHost.realpath(path); };
}
}n/a
function LanguageServiceShimHostAdapter(shimHost) {
var _this = this;
this.shimHost = shimHost;
this.loggingEnabled = false;
this.tracingEnabled = false;
// if shimHost is a COM object then property check will become method call with no arguments.
// 'in' does not have this effect.
if ("getModuleResolutionsForFile" in this.shimHost) {
this.resolveModuleNames = function (moduleNames, containingFile) {
var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile));
return ts.map(moduleNames, function (name) {
var result = ts.getProperty(resolutionsInFile, name);
return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false
} : undefined;
});
};
}
if ("directoryExists" in this.shimHost) {
this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
}
if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile));
return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); });
};
}
}n/a
function OperationCanceledException() {
}n/a
function TextChange() {
}n/a
function TypeScriptServicesFactory() {
this._shims = [];
}n/a
function addEmitHelper(node, helper) {
var emitNode = getOrCreateEmitNode(node);
emitNode.helpers = ts.append(emitNode.helpers, helper);
return node;
}n/a
function addEmitHelpers(node, helpers) {
if (ts.some(helpers)) {
var emitNode = getOrCreateEmitNode(node);
for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
var helper = helpers_1[_i];
if (!ts.contains(emitNode.helpers, helper)) {
emitNode.helpers = ts.append(emitNode.helpers, helper);
}
}
}
return node;
}n/a
function addPrologueDirectives(target, source, ensureUseStrict, visitor) {
ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
var foundUseStrict = false;
var statementOffset = 0;
var numStatements = source.length;
while (statementOffset < numStatements) {
var statement = source[statementOffset];
if (ts.isPrologueDirective(statement)) {
if (isUseStrictPrologue(statement)) {
foundUseStrict = true;
}
target.push(statement);
}
else {
break;
}
statementOffset++;
}
if (ensureUseStrict && !foundUseStrict) {
target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))));
}
while (statementOffset < numStatements) {
var statement = source[statementOffset];
if (ts.getEmitFlags(statement) & 524288 /* CustomPrologue */) {
target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
}
else {
break;
}
statementOffset++;
}
return statementOffset;
}n/a
function addRange(to, from) {
if (from === undefined)
return to;
for (var _i = 0, from_1 = from; _i < from_1.length; _i++) {
var v = from_1[_i];
to = append(to, v);
}
return to;
}n/a
function adjustExtensionPriority(extensionPriority, supportedExtensions) {
if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
return 0 /* TypeScriptFiles */;
}
else if (extensionPriority < supportedExtensions.length) {
return 2 /* DeclarationAndJavaScriptFiles */;
}
else {
return supportedExtensions.length;
}
}n/a
function aggregateTransformFlags(node) {
aggregateTransformFlagsForNode(node);
return node;
}n/a
function append(to, value) {
if (value === undefined)
return to;
if (to === undefined)
return [value];
to.push(value);
return to;
}n/a
function arrayFrom(iterator) {
var result = [];
for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done
, _b) {
result.push(value);
}
return result;
var _b;
}n/a
function arrayIsEqualTo(array1, array2, equaler) {
if (!array1 || !array2) {
return array1 === array2;
}
if (array1.length !== array2.length) {
return false;
}
for (var i = 0; i < array1.length; i++) {
var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i];
if (!equals) {
return false;
}
}
return true;
}n/a
function arrayToMap(array, makeKey, makeValue) {
var result = createMap();
for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
var value = array_8[_i];
result.set(makeKey(value), makeValue ? makeValue(value) : value);
}
return result;
}n/a
function assign(t) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
var arg = args_1[_a];
for (var _b = 0, _c = getOwnKeys(arg); _b < _c.length; _b++) {
var p = _c[_b];
t[p] = arg[p];
}
}
return t;
}n/a
function binarySearch(array, value, comparer, offset) {
if (!array || array.length === 0) {
return -1;
}
var low = offset || 0;
var high = array.length - 1;
comparer = comparer !== undefined
? comparer
: function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); };
while (low <= high) {
var middle = low + ((high - low) >> 1);
var midValue = array[middle];
if (comparer(midValue, value) === 0) {
return middle;
}
else if (comparer(midValue, value) > 0) {
high = middle - 1;
}
else {
low = middle + 1;
}
}
return ~low;
}n/a
function bindSourceFile(file, options) {
ts.performance.mark("beforeBind");
binder(file, options);
ts.performance.mark("afterBind");
ts.performance.measure("Bind", "beforeBind", "afterBind");
}n/a
function breakIntoCharacterSpans(identifier) {
return breakIntoSpans(identifier, /*word:*/ false);
}n/a
function breakIntoWordSpans(identifier) {
return breakIntoSpans(identifier, /*word:*/ true);
}n/a
function chain(a, b, c, d, e) {
if (e) {
var args_2 = [];
for (var i = 0; i < arguments.length; i++) {
args_2[i] = arguments[i];
}
return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); };
}
else if (d) {
return function (t) { return compose(a(t), b(t), c(t), d(t)); };
}
else if (c) {
return function (t) { return compose(a(t), b(t), c(t)); };
}
else if (b) {
return function (t) { return compose(a(t), b(t)); };
}
else if (a) {
return function (t) { return compose(a(t)); };
}
else {
return function (_) { return function (u) { return u; }; };
}
}n/a
function chainDiagnosticMessages(details, message) {
var text = getLocaleSpecificMessage(message);
if (arguments.length > 2) {
text = formatStringFromArgs(text, arguments, 2);
}
return {
messageText: text,
category: message.category,
code: message.code,
next: details
};
}n/a
function changeExtension(path, newExtension) {
return (removeFileExtension(path) + newExtension);
}n/a
function changesAffectModuleResolution(oldOptions, newOptions) {
return !oldOptions ||
(oldOptions.module !== newOptions.module) ||
(oldOptions.moduleResolution !== newOptions.moduleResolution) ||
(oldOptions.noResolve !== newOptions.noResolve) ||
(oldOptions.target !== newOptions.target) ||
(oldOptions.noLib !== newOptions.noLib) ||
(oldOptions.jsx !== newOptions.jsx) ||
(oldOptions.allowJs !== newOptions.allowJs) ||
(oldOptions.rootDir !== newOptions.rootDir) ||
(oldOptions.configFilePath !== newOptions.configFilePath) ||
(oldOptions.baseUrl !== newOptions.baseUrl) ||
(oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) ||
!arrayIsEqualTo(oldOptions.lib, newOptions.lib) ||
!arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) ||
!arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) ||
!equalOwnProperties(oldOptions.paths, newOptions.paths);
}n/a
function childIsDecorated(node) {
switch (node.kind) {
case 228 /* ClassDeclaration */:
return ts.forEach(node.members, nodeOrChildIsDecorated);
case 150 /* MethodDeclaration */:
case 153 /* SetAccessor */:
return ts.forEach(node.parameters, nodeIsDecorated);
}
}n/a
function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
var failedLookupLocations = [];
var containingDirectory = ts.getDirectoryPath(containingFile);
var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations
);
function tryResolve(extensions) {
var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile
, failedLookupLocations, state);
if (resolvedUsingSettings) {
return { value: resolvedUsingSettings };
}
var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName);
if (moduleHasNonRelativeName(moduleName)) {
// Climb up parent directories looking for a module.
var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) {
var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled
, host);
if (resolutionFromCache) {
return resolutionFromCache;
}
var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false
, state));
});
if (resolved_3) {
return resolved_3;
}
if (extensions === Extensions.TypeScript) {
// If we didn't find the file normally, look it up in @types.
return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state);
}
}
else {
var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false,
state));
}
}
}n/a
function climbPastPropertyAccess(node) {
return isRightSideOfPropertyAccess(node) ? node.parent : node;
}n/a
function clone(object) {
var result = {};
for (var id in object) {
if (hasOwnProperty.call(object, id)) {
result[id] = object[id];
}
}
return result;
}n/a
function cloneMap(map) {
var clone = createMap();
copyEntries(map, clone);
return clone;
}n/a
function collapseRangeToEnd(range) {
return isCollapsedRange(range) ? range : moveRangePos(range, range.end);
}n/a
function collapseRangeToStart(range) {
return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos);
}n/a
function collapseTextChangeRangesAcrossMultipleVersions(changes) {
if (changes.length === 0) {
return ts.unchangedTextChangeRange;
}
if (changes.length === 1) {
return changes[0];
}
// We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
// as it makes things much easier to reason about.
var change0 = changes[0];
var oldStartN = change0.span.start;
var oldEndN = textSpanEnd(change0.span);
var newEndN = oldStartN + change0.newLength;
for (var i = 1; i < changes.length; i++) {
var nextChange = changes[i];
// Consider the following case:
// i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting
// at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }.
// i.e. the span starting at 30 with length 30 is increased to length 40.
//
// 0 10 20 30 40 50 60 70 80 90 100
// -------------------------------------------------------------------------------------------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// -------------------------------------------------------------------------------------------------------
// | \
// | \
// T2 | \
// | \
// | \
// -------------------------------------------------------------------------------------------------------
//
// Merging these turns out to not be too difficult. First, determining the new start of the change is trivial
// it's just the min of the old and new starts. i.e.:
//
// 0 10 20 30 40 50 60 70 80 90 100
// ------------------------------------------------------------*------------------------------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// ----------------------------------------$-------------------$------------------------------------------
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// ----------------------------------------------------------------------*--------------------------------
//
// (Note the dots represent the newly inferred start.
// Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the
// absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
// which if the two $'s precedes the other, and we move that one forward until t ...n/a
function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
var externalImports = [];
var exportSpecifiers = ts.createMultiMap();
var exportedBindings = [];
var uniqueExports = ts.createMap();
var exportedNames;
var hasExportDefault = false;
var exportEquals = undefined;
var hasExportStarsToExportValues = false;
var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions);
var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.
createLiteral(ts.externalHelpersModuleNameText));
if (externalHelpersImportDeclaration) {
externalImports.push(externalHelpersImportDeclaration);
}
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var node = _a[_i];
switch (node.kind) {
case 237 /* ImportDeclaration */:
// import "mod"
// import x from "mod"
// import * as x from "mod"
// import { x, y } from "mod"
externalImports.push(node);
break;
case 236 /* ImportEqualsDeclaration */:
if (node.moduleReference.kind === 247 /* ExternalModuleReference */) {
// import x = require("mod")
externalImports.push(node);
}
break;
case 243 /* ExportDeclaration */:
if (node.moduleSpecifier) {
if (!node.exportClause) {
// export * from "mod"
externalImports.push(node);
hasExportStarsToExportValues = true;
}
else {
// export { x, y } from "mod"
externalImports.push(node);
}
}
else {
// export { x, y }
for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) {
var specifier = _c[_b];
if (!uniqueExports.get(specifier.name.text)) {
var name = specifier.propertyName || specifier.name;
exportSpecifiers.add(name.text, specifier);
var decl = resolver.getReferencedImportDeclaration(name)
|| resolver.getReferencedValueDeclaration(name);
if (decl) {
multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name);
}
uniqueExports.set(specifier.name.text, true);
exportedNames = ts.append(exportedNames, specifier.name);
}
}
}
break;
case 242 /* ExportAssignment */:
if (node.isExportEquals && !exportEquals) {
// export = x
exportEquals = node;
}
break;
case 207 /* VariableStatement */:
if (ts.hasModifier(node, 1 /* Export */)) {
for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) {
var decl = _e[_d];
exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
}
}
break;
case 227 /* FunctionDeclaration */:
if (ts.hasModifier(node, 1 /* Export */)) {
if (ts.hasModifier(node, 512 /* Default */)) {
// export default function() { }
if (!hasExportDefault) {
multiMapSparseArrayAdd(exportedBindings, ts.getOr ...n/a
function combinePaths(path1, path2) {
if (!(path1 && path1.length))
return path2;
if (!(path2 && path2.length))
return path1;
if (getRootLength(path2) !== 0)
return path2;
if (path1.charAt(path1.length - 1) === ts.directorySeparator)
return path1 + path2;
return path1 + ts.directorySeparator + path2;
}n/a
function compact(array) {
var result;
if (array) {
for (var i = 0; i < array.length; i++) {
var v = array[i];
if (result || !v) {
if (!result) {
result = array.slice(0, i);
}
if (v) {
result.push(v);
}
}
}
}
return result || array;
}n/a
function compareDataObjects(dst, src) {
for (var e in dst) {
if (typeof dst[e] === "object") {
if (!compareDataObjects(dst[e], src[e])) {
return false;
}
}
else if (typeof dst[e] !== "function") {
if (dst[e] !== src[e]) {
return false;
}
}
}
return true;
}n/a
function compareDiagnostics(d1, d2) {
return compareValues(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) ||
compareValues(d1.start, d2.start) ||
compareValues(d1.length, d2.length) ||
compareValues(d1.code, d2.code) ||
compareMessageText(d1.messageText, d2.messageText) ||
0 /* EqualTo */;
}n/a
function compareEmitHelpers(x, y) {
if (x === y)
return 0 /* EqualTo */;
if (x.priority === y.priority)
return 0 /* EqualTo */;
if (x.priority === undefined)
return 1 /* GreaterThan */;
if (y.priority === undefined)
return -1 /* LessThan */;
return ts.compareValues(x.priority, y.priority);
}n/a
function comparePaths(a, b, currentDirectory, ignoreCase) {
if (a === b)
return 0 /* EqualTo */;
if (a === undefined)
return -1 /* LessThan */;
if (b === undefined)
return 1 /* GreaterThan */;
a = removeTrailingDirectorySeparator(a);
b = removeTrailingDirectorySeparator(b);
var aComponents = getNormalizedPathComponents(a, currentDirectory);
var bComponents = getNormalizedPathComponents(b, currentDirectory);
var sharedLength = Math.min(aComponents.length, bComponents.length);
for (var i = 0; i < sharedLength; i++) {
var result = compareStrings(aComponents[i], bComponents[i], ignoreCase);
if (result !== 0 /* EqualTo */) {
return result;
}
}
return compareValues(aComponents.length, bComponents.length);
}n/a
function compareStrings(a, b, ignoreCase) {
if (a === b)
return 0 /* EqualTo */;
if (a === undefined)
return -1 /* LessThan */;
if (b === undefined)
return 1 /* GreaterThan */;
if (ignoreCase) {
// Checking if "collator exists indicates that Intl is available.
// We still have to check if "collator.compare" is correct. If it is not, use "String.localeComapre"
if (ts.collator) {
var result = ts.localeCompareIsCorrect ?
ts.collator.compare(a, b) :
a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); // accent means a ≠ b, a ≠
á, a = A
return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
}
a = a.toUpperCase();
b = b.toUpperCase();
if (a === b)
return 0 /* EqualTo */;
}
return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */;
}n/a
function compareStringsCaseInsensitive(a, b) {
return compareStrings(a, b, /*ignoreCase*/ true);
}n/a
function compareValues(a, b) {
if (a === b)
return 0 /* EqualTo */;
if (a === undefined)
return -1 /* LessThan */;
if (b === undefined)
return 1 /* GreaterThan */;
return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */;
}n/a
function compose(a, b, c, d, e) {
if (e) {
var args_3 = [];
for (var i = 0; i < arguments.length; i++) {
args_3[i] = arguments[i];
}
return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); };
}
else if (d) {
return function (t) { return d(c(b(a(t)))); };
}
else if (c) {
return function (t) { return c(b(a(t))); };
}
else if (b) {
return function (t) { return b(a(t)); };
}
else if (a) {
return function (t) { return a(t); };
}
else {
return function (t) { return t; };
}
}n/a
function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
var commonPathComponents;
var failed = ts.forEach(fileNames, function (sourceFile) {
// Each file contributes into common source file path
var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
sourcePathComponents.pop(); // The base file name is not part of the common directory path
if (!commonPathComponents) {
// first file
commonPathComponents = sourcePathComponents;
return;
}
var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
for (var i = 0; i < n; i++) {
if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
if (i === 0) {
// Failed to find any common path component
return true;
}
// New common path found that is 0 -> i-1
commonPathComponents.length = i;
break;
}
}
// If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
if (sourcePathComponents.length < commonPathComponents.length) {
commonPathComponents.length = sourcePathComponents.length;
}
});
// A common path can not be found when paths span multiple drives on windows, for example
if (failed) {
return "";
}
if (!commonPathComponents) {
return currentDirectory;
}
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}n/a
function computeLineAndCharacterOfPosition(lineStarts, position) {
var lineNumber = ts.binarySearch(lineStarts, position);
if (lineNumber < 0) {
// If the actual position was not found,
// the binary search returns the 2's-complement of the next line start
// e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
// then the search will return -2.
//
// We want the index of the previous line start, so we subtract 1.
// Review 2's-complement if this is confusing.
lineNumber = ~lineNumber - 1;
ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
}
return {
line: lineNumber,
character: position - lineStarts[lineNumber]
};
}n/a
function computeLineStarts(text) {
var result = new Array();
var pos = 0;
var lineStart = 0;
while (pos < text.length) {
var ch = text.charCodeAt(pos);
pos++;
switch (ch) {
case 13 /* carriageReturn */:
if (text.charCodeAt(pos) === 10 /* lineFeed */) {
pos++;
}
case 10 /* lineFeed */:
result.push(lineStart);
lineStart = pos;
break;
default:
if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
result.push(lineStart);
lineStart = pos;
}
break;
}
}
result.push(lineStart);
return result;
}n/a
function computePositionOfLineAndCharacter(lineStarts, line, character) {
ts.Debug.assert(line >= 0 && line < lineStarts.length);
return lineStarts[line] + character;
}n/a
function computeTransformFlagsForNode(node, subtreeFlags) {
var kind = node.kind;
switch (kind) {
case 180 /* CallExpression */:
return computeCallExpression(node, subtreeFlags);
case 181 /* NewExpression */:
return computeNewExpression(node, subtreeFlags);
case 232 /* ModuleDeclaration */:
return computeModuleDeclaration(node, subtreeFlags);
case 184 /* ParenthesizedExpression */:
return computeParenthesizedExpression(node, subtreeFlags);
case 193 /* BinaryExpression */:
return computeBinaryExpression(node, subtreeFlags);
case 209 /* ExpressionStatement */:
return computeExpressionStatement(node, subtreeFlags);
case 145 /* Parameter */:
return computeParameter(node, subtreeFlags);
case 186 /* ArrowFunction */:
return computeArrowFunction(node, subtreeFlags);
case 185 /* FunctionExpression */:
return computeFunctionExpression(node, subtreeFlags);
case 227 /* FunctionDeclaration */:
return computeFunctionDeclaration(node, subtreeFlags);
case 225 /* VariableDeclaration */:
return computeVariableDeclaration(node, subtreeFlags);
case 226 /* VariableDeclarationList */:
return computeVariableDeclarationList(node, subtreeFlags);
case 207 /* VariableStatement */:
return computeVariableStatement(node, subtreeFlags);
case 221 /* LabeledStatement */:
return computeLabeledStatement(node, subtreeFlags);
case 228 /* ClassDeclaration */:
return computeClassDeclaration(node, subtreeFlags);
case 198 /* ClassExpression */:
return computeClassExpression(node, subtreeFlags);
case 257 /* HeritageClause */:
return computeHeritageClause(node, subtreeFlags);
case 258 /* CatchClause */:
return computeCatchClause(node, subtreeFlags);
case 200 /* ExpressionWithTypeArguments */:
return computeExpressionWithTypeArguments(node, subtreeFlags);
case 151 /* Constructor */:
return computeConstructor(node, subtreeFlags);
case 148 /* PropertyDeclaration */:
return computePropertyDeclaration(node, subtreeFlags);
case 150 /* MethodDeclaration */:
return computeMethod(node, subtreeFlags);
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
return computeAccessor(node, subtreeFlags);
case 236 /* ImportEqualsDeclaration */:
return computeImportEquals(node, subtreeFlags);
case 178 /* PropertyAccessExpression */:
return computePropertyAccess(node, subtreeFlags);
default:
return computeOther(node, kind, subtreeFlags);
}
}n/a
function concatenate(array1, array2) {
if (!some(array2))
return array1;
if (!some(array1))
return array2;
return array1.concat(array2);
}n/a
function concatenateDiagnosticMessageChains(headChain, tailChain) {
var lastChain = headChain;
while (lastChain.next) {
lastChain = lastChain.next;
}
lastChain.next = tailChain;
return headChain;
}n/a
function contains(array, value) {
if (array) {
for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
var v = array_1[_i];
if (v === value) {
return true;
}
}
}
return false;
}n/a
function containsParseError(node) {
aggregateChildData(node);
return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0;
}n/a
function containsPath(parent, child, currentDirectory, ignoreCase) {
if (parent === undefined || child === undefined)
return false;
if (parent === child)
return true;
parent = removeTrailingDirectorySeparator(parent);
child = removeTrailingDirectorySeparator(child);
if (parent === child)
return true;
var parentComponents = getNormalizedPathComponents(parent, currentDirectory);
var childComponents = getNormalizedPathComponents(child, currentDirectory);
if (childComponents.length < parentComponents.length) {
return false;
}
for (var i = 0; i < parentComponents.length; i++) {
var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase);
if (result !== 0 /* EqualTo */) {
return false;
}
}
return true;
}n/a
function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
return false;
}
var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors);
if (typeof result === "boolean" && result) {
return result;
}
return false;
}n/a
function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
var errors = [];
var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
return { options: options, errors: errors };
}n/a
function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
// Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
var result = {
enable: typeAcquisition.enableAutoDiscovery,
include: typeAcquisition.include || [],
exclude: typeAcquisition.exclude || []
};
return result;
}
return typeAcquisition;
}n/a
function convertToArray(iterator, f) {
var result = [];
for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done
, _b) {
result.push(f(value));
}
return result;
var _b;
}n/a
function convertToArrayAssignmentElement(element) {
if (ts.isBindingElement(element)) {
if (element.dotDotDotToken) {
ts.Debug.assertNode(element.name, ts.isIdentifier);
return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element);
}
var expression = convertToAssignmentElementTarget(element.name);
return element.initializer
? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element)
: expression;
}
ts.Debug.assertNode(element, ts.isExpression);
return element;
}n/a
function convertToArrayAssignmentPattern(node) {
if (ts.isArrayBindingPattern(node)) {
return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)),
node), node);
}
ts.Debug.assertNode(node, ts.isArrayLiteralExpression);
return node;
}n/a
function convertToAssignmentElementTarget(node) {
if (ts.isBindingPattern(node)) {
return convertToAssignmentPattern(node);
}
ts.Debug.assertNode(node, ts.isExpression);
return node;
}n/a
function convertToAssignmentPattern(node) {
switch (node.kind) {
case 174 /* ArrayBindingPattern */:
case 176 /* ArrayLiteralExpression */:
return convertToArrayAssignmentPattern(node);
case 173 /* ObjectBindingPattern */:
case 177 /* ObjectLiteralExpression */:
return convertToObjectAssignmentPattern(node);
}
}n/a
function convertToBase64(input) {
var result = "";
var charCodes = getExpandedCharCodes(input);
var i = 0;
var length = charCodes.length;
var byte1, byte2, byte3, byte4;
while (i < length) {
// Convert every 6-bits in the input 3 character points
// into a base64 digit
byte1 = charCodes[i] >> 2;
byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
byte4 = charCodes[i + 2] & 63;
// We are out of characters in the input, set the extra
// digits to 64 (padding character).
if (i + 1 >= length) {
byte3 = byte4 = 64;
}
else if (i + 2 >= length) {
byte4 = 64;
}
// Write to the output
result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4
);
i += 3;
}
return result;
}n/a
function convertToFunctionBody(node, multiLine) {
return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine),
node);
}n/a
function convertToObjectAssignmentElement(element) {
if (ts.isBindingElement(element)) {
if (element.dotDotDotToken) {
ts.Debug.assertNode(element.name, ts.isIdentifier);
return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element);
}
if (element.propertyName) {
var expression = convertToAssignmentElementTarget(element.name);
return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts
.createAssignment(expression, element.initializer) : expression), element), element);
}
ts.Debug.assertNode(element.name, ts.isIdentifier);
return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element
), element);
}
ts.Debug.assertNode(element, ts.isObjectLiteralElementLike);
return element;
}n/a
function convertToObjectAssignmentPattern(node) {
if (ts.isObjectBindingPattern(node)) {
return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)),
node), node);
}
ts.Debug.assertNode(node, ts.isObjectLiteralExpression);
return node;
}n/a
function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
return !isRootedDiskPath(absoluteOrRelativePath)
? absoluteOrRelativePath
: getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl
*/ false);
}n/a
function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
var errors = [];
var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
return { options: options, errors: errors };
}n/a
function copyEntries(source, target) {
source.forEach(function (value, key) {
target.set(key, value);
});
}n/a
function couldStartTrivia(text, pos) {
// Keep in sync with skipTrivia
var ch = text.charCodeAt(pos);
switch (ch) {
case 13 /* carriageReturn */:
case 10 /* lineFeed */:
case 9 /* tab */:
case 11 /* verticalTab */:
case 12 /* formFeed */:
case 32 /* space */:
case 47 /* slash */:
// starts of normal trivia
case 60 /* lessThan */:
case 61 /* equals */:
case 62 /* greaterThan */:
// Starts of conflict marker trivia
return true;
case 35 /* hash */:
// Only if its the beginning can we have #! trivia
return pos === 0;
default:
return ch > 127 /* maxAsciiCharacter */;
}
}n/a
function countWhere(array, predicate) {
var count = 0;
if (array) {
for (var i = 0; i < array.length; i++) {
var v = array[i];
if (predicate(v, i)) {
count++;
}
}
}
return count;
}n/a
function createAdd(left, right) {
return createBinary(left, 36 /* PlusToken */, right);
}n/a
function createArrayBindingPattern(elements) {
var node = createSynthesizedNode(174 /* ArrayBindingPattern */);
node.elements = createNodeArray(elements);
return node;
}n/a
function createArrayConcat(array, values) {
return ts.createCall(ts.createPropertyAccess(array, "concat"),
/*typeArguments*/ undefined, values);
}n/a
function createArrayLiteral(elements, multiLine) {
var node = createSynthesizedNode(176 /* ArrayLiteralExpression */);
node.elements = ts.parenthesizeListElements(createNodeArray(elements));
if (multiLine) {
node.multiLine = true;
}
return node;
}n/a
function createArraySlice(array, start) {
var argumentsList = [];
if (start !== undefined) {
argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start);
}
return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
}n/a
function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
var node = createSynthesizedNode(186 /* ArrowFunction */);
node.modifiers = asNodeArray(modifiers);
node.typeParameters = asNodeArray(typeParameters);
node.parameters = createNodeArray(parameters);
node.type = type;
node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(35 /* EqualsGreaterThanToken */);
node.body = ts.parenthesizeConciseBody(body);
return node;
}n/a
function createAsExpression(expression, type) {
var node = createSynthesizedNode(201 /* AsExpression */);
node.expression = expression;
node.type = type;
return node;
}n/a
function createAssignHelper(context, attributesSegments) {
if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
context.requestEmitHelper(assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}n/a
function createAssignment(left, right) {
return createBinary(left, 57 /* EqualsToken */, right);
}n/a
function createAwait(expression) {
var node = createSynthesizedNode(190 /* AwaitExpression */);
node.expression = ts.parenthesizePrefixOperand(expression);
return node;
}n/a
function createBinary(left, operator, right) {
var node = createSynthesizedNode(193 /* BinaryExpression */);
var operatorToken = asToken(operator);
var operatorKind = operatorToken.kind;
node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
node.operatorToken = operatorToken;
node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
return node;
}n/a
function createBindingElement(propertyName, dotDotDotToken, name, initializer) {
var node = createSynthesizedNode(175 /* BindingElement */);
node.propertyName = asName(propertyName);
node.dotDotDotToken = dotDotDotToken;
node.name = asName(name);
node.initializer = initializer;
return node;
}n/a
function createBlock(statements, multiLine) {
var block = createSynthesizedNode(206 /* Block */);
block.statements = createNodeArray(statements);
if (multiLine)
block.multiLine = multiLine;
return block;
}n/a
function createBreak(label) {
var node = createSynthesizedNode(217 /* BreakStatement */);
node.label = asName(label);
return node;
}n/a
function createBundle(sourceFiles) {
var node = ts.createNode(264 /* Bundle */);
node.sourceFiles = sourceFiles;
return node;
}n/a
function createCall(expression, typeArguments, argumentsArray) {
var node = createSynthesizedNode(180 /* CallExpression */);
node.expression = ts.parenthesizeForAccess(expression);
node.typeArguments = asNodeArray(typeArguments);
node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
return node;
}n/a
function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
var callee = skipOuterExpressions(expression, 7 /* All */);
var thisArg;
var target;
if (ts.isSuperProperty(callee)) {
thisArg = ts.createThis();
target = callee;
}
else if (callee.kind === 96 /* SuperKeyword */) {
thisArg = ts.createThis();
target = languageVersion < 2 /* ES2015 */
? ts.setTextRange(ts.createIdentifier("_super"), callee)
: callee;
}
else {
switch (callee.kind) {
case 178 /* PropertyAccessExpression */: {
if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
// for `a.b()` target is `(_a = a).b` and thisArg is `_a`
thisArg = ts.createTempVariable(recordTempVariable);
target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression
), callee.name);
ts.setTextRange(target, callee);
}
else {
thisArg = callee.expression;
target = callee;
}
break;
}
case 179 /* ElementAccessExpression */: {
if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
// for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
thisArg = ts.createTempVariable(recordTempVariable);
target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression
), callee.argumentExpression);
ts.setTextRange(target, callee);
}
else {
thisArg = callee.expression;
target = callee;
}
break;
}
default: {
// for `a()` target is `a` and thisArg is `void 0`
thisArg = ts.createVoidZero();
target = parenthesizeForAccess(expression);
break;
}
}
}
return { target: target, thisArg: thisArg };
}n/a
function createCaseBlock(clauses) {
var node = createSynthesizedNode(234 /* CaseBlock */);
node.clauses = createNodeArray(clauses);
return node;
}n/a
function createCaseClause(expression, statements) {
var node = createSynthesizedNode(255 /* CaseClause */);
node.expression = ts.parenthesizeExpressionForList(expression);
node.statements = createNodeArray(statements);
return node;
}n/a
function createCatchClause(variableDeclaration, block) {
var node = createSynthesizedNode(258 /* CatchClause */);
node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration
;
node.block = block;
return node;
}n/a
function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
var node = createSynthesizedNode(228 /* ClassDeclaration */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.name = asName(name);
node.typeParameters = asNodeArray(typeParameters);
node.heritageClauses = asNodeArray(heritageClauses);
node.members = createNodeArray(members);
return node;
}n/a
function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
var node = createSynthesizedNode(198 /* ClassExpression */);
node.decorators = undefined;
node.modifiers = asNodeArray(modifiers);
node.name = asName(name);
node.typeParameters = asNodeArray(typeParameters);
node.heritageClauses = asNodeArray(heritageClauses);
node.members = createNodeArray(members);
return node;
}n/a
function createClassifier() {
var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false);
/// We do not have a full parser support to know when we should parse a regex or not
/// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where
/// we have a series of divide operator. this list allows us to be more accurate by ruling out
/// locations where a regexp cannot exist.
var noRegexTable = [];
noRegexTable[70 /* Identifier */] = true;
noRegexTable[9 /* StringLiteral */] = true;
noRegexTable[8 /* NumericLiteral */] = true;
noRegexTable[11 /* RegularExpressionLiteral */] = true;
noRegexTable[98 /* ThisKeyword */] = true;
noRegexTable[42 /* PlusPlusToken */] = true;
noRegexTable[43 /* MinusMinusToken */] = true;
noRegexTable[19 /* CloseParenToken */] = true;
noRegexTable[21 /* CloseBracketToken */] = true;
noRegexTable[17 /* CloseBraceToken */] = true;
noRegexTable[100 /* TrueKeyword */] = true;
noRegexTable[85 /* FalseKeyword */] = true;
// Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact)
// classification on template strings. Because of the context free nature of templates,
// the only precise way to classify a template portion would be by propagating the stack across
// lines, just as we do with the end-of-line state. However, this is a burden for implementers,
// and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead
// flatten any nesting when the template stack is non-empty and encode it in the end-of-line state.
// Situations in which this fails are
// 1) When template strings are nested across different lines:
// `hello ${ `world
// ` }`
//
// Where on the second line, you will get the closing of a template,
// a closing curly, and a new template.
//
// 2) When substitution expressions have curly braces and the curly brace falls on the next line:
// `hello ${ () => {
// return "world" } } `
//
// Where on the second line, you will get the 'return' keyword,
// a string literal, and a template end consisting of '} } `'.
var templateStack = [];
/** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */
function canFollow(keyword1, keyword2) {
if (ts.isAccessibilityModifier(keyword1)) {
if (keyword2 === 124 /* GetKeyword */ ||
keyword2 === 134 /* SetKeyword */ ||
keyword2 === 122 /* ConstructorKeyword */ ||
keyword2 === 114 /* StaticKeyword */) {
// Allow things like "public get", "public constructor" and "public static".
// These are all legal.
return true;
}
// Any other keyword following "public" is actually an identifier an not a real
// keyword.
return false;
}
// Assume any other keyword combination is legal. This can be refined in the future
// if there are more cases we want the classifier to be better at.
return true;
}
function convertClassifications(classifications, text) {
var entries = [];
var dense = classifications.spans;
var lastEnd = 0;
for (var i = 0; i < dense.length; i += 3) {
var start = dense[i];
var length_4 = dense[i + 1];
var type = dense[i + 2];
// Make a whitespace entry between the last item and this one.
if (lastEnd >= 0) {
var whitespaceLength_1 = start - lastEnd;
if (whitespaceLength_1 > 0) {
entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
}
}
entries.push({ length: length_4, classification: convertClassification(type) });
lastEnd = start + length_4;
}
var whitespaceLength = tex ...n/a
function createComma(left, right) {
return createBinary(left, 25 /* CommaToken */, right);
}n/a
function createCommentWriter(printerOptions, emitPos) {
var extendedDiagnostics = printerOptions.extendedDiagnostics;
var newLine = ts.getNewLineCharacter(printerOptions);
var writer;
var containerPos = -1;
var containerEnd = -1;
var declarationListContainerEnd = -1;
var currentSourceFile;
var currentText;
var currentLineMap;
var detachedCommentsInfo;
var hasWrittenComment = false;
var disabled = printerOptions.removeComments;
return {
reset: reset,
setWriter: setWriter,
setSourceFile: setSourceFile,
emitNodeWithComments: emitNodeWithComments,
emitBodyWithDetachedComments: emitBodyWithDetachedComments,
emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition,
emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition,
};
function emitNodeWithComments(hint, node, emitCallback) {
if (disabled) {
emitCallback(hint, node);
return;
}
if (node) {
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
var emitFlags = ts.getEmitFlags(node);
if ((pos < 0 && end < 0) || (pos === end)) {
// Both pos and end are synthesized, so just emit the node without comments.
if (emitFlags & 2048 /* NoNestedComments */) {
disabled = true;
emitCallback(hint, node);
disabled = false;
}
else {
emitCallback(hint, node);
}
}
else {
if (extendedDiagnostics) {
ts.performance.mark("preEmitNodeWithComment");
}
var isEmittedNode = node.kind !== 296 /* NotEmittedStatement */;
var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
// Emit leading comments if the position is not synthesized and the node
// has not opted out from emitting leading comments.
if (!skipLeadingComments) {
emitLeadingComments(pos, isEmittedNode);
}
// Save current container state on the stack.
var savedContainerPos = containerPos;
var savedContainerEnd = containerEnd;
var savedDeclarationListContainerEnd = declarationListContainerEnd;
if (!skipLeadingComments) {
containerPos = pos;
}
if (!skipTrailingComments) {
containerEnd = end;
// To avoid invalid comment emit in a down-level binding pattern, we
// keep track of the last declaration list container's end
if (node.kind === 226 /* VariableDeclarationList */) {
declarationListContainerEnd = end;
}
}
if (extendedDiagnostics) {
ts.performance.measure("commentTime", "preEmitNodeWithComment");
}
if (emitFlags & 2048 /* NoNestedComments */) {
disabled = true;
emitCallback(hint, node);
disabled = false;
}
else {
emitCallback(hint, node);
}
if (extendedDiagnostics) {
ts.performance.mark("beginEmitNodeWithComment");
}
// Restore previous container state.
containerPos = savedContainerPos;
containerEnd = savedContainerEnd;
declarationListContainerEnd = savedDeclarationListContainerEnd;
// Emit trailing comments if the position is not synthesized and the node
// has not opted out from emitting leading comments and is an emitted node. ...n/a
function createCompilerDiagnostic(message) {
var text = getLocaleSpecificMessage(message);
if (arguments.length > 1) {
text = formatStringFromArgs(text, arguments, 1);
}
return {
file: undefined,
start: undefined,
length: undefined,
messageText: text,
category: message.category,
code: message.code
};
}n/a
function createCompilerDiagnosticForInvalidCustomType(opt) {
var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
}n/a
function createCompilerDiagnosticFromMessageChain(chain) {
return {
file: undefined,
start: undefined,
length: undefined,
code: chain.code,
category: chain.category,
messageText: chain.next ? chain : chain.messageText
};
}n/a
function createCompilerHost(options, setParentNodes) {
var existingDirectories = ts.createMap();
function getCanonicalFileName(fileName) {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical
form.
// otherwise use toLowerCase as a canonical form.
return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
// returned by CScript sys environment
var unsupportedFileEncodingErrorCode = -2147024809;
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
ts.performance.mark("beforeIORead");
text = ts.sys.readFile(fileName, options.charset);
ts.performance.mark("afterIORead");
ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
}
catch (e) {
if (onError) {
onError(e.number === unsupportedFileEncodingErrorCode
? ts.createCompilerDiagnostic(ts.Diagnostics.Unsupported_file_encoding).messageText
: e.message);
}
text = "";
}
return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
}
function directoryExists(directoryPath) {
if (existingDirectories.has(directoryPath)) {
return true;
}
if (ts.sys.directoryExists(directoryPath)) {
existingDirectories.set(directoryPath, true);
return true;
}
return false;
}
function ensureDirectoriesExist(directoryPath) {
if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = ts.getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
ts.sys.createDirectory(directoryPath);
}
}
var outputFingerprints;
function writeFileIfUpdated(fileName, data, writeByteOrderMark) {
if (!outputFingerprints) {
outputFingerprints = ts.createMap();
}
var hash = ts.sys.createHash(data);
var mtimeBefore = ts.sys.getModifiedTime(fileName);
if (mtimeBefore) {
var fingerprint = outputFingerprints.get(fileName);
// If output has not been changed, and the file has no external modification
if (fingerprint &&
fingerprint.byteOrderMark === writeByteOrderMark &&
fingerprint.hash === hash &&
fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
return;
}
}
ts.sys.writeFile(fileName, data, writeByteOrderMark);
var mtimeAfter = ts.sys.getModifiedTime(fileName);
outputFingerprints.set(fileName, {
hash: hash,
byteOrderMark: writeByteOrderMark,
mtime: mtimeAfter
});
}
function writeFile(fileName, data, writeByteOrderMark, onError) {
try {
ts.performance.mark("beforeIOWrite");
ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName)));
if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) {
writeFileIfUpdated(fileName, data, writeByteOrderMark);
}
else {
ts.sys.writeFile(fileName, data, writeByteOrderMark);
}
ts.performance.mark("afterIOWrite");
ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
}
catch (e) {
if (onError) {
onError(e.message);
}
}
}
function getDefaultLibLocation() {
return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath()));
}
var newLine = ts.getNewLineCharacter(options);
var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); });
return {
getSourceFile: getSourceFile,
getDefaultLibLocation: ...n/a
function createComputedPropertyName(expression) {
var node = createSynthesizedNode(143 /* ComputedPropertyName */);
node.expression = expression;
return node;
}n/a
function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) {
var node = createSynthesizedNode(194 /* ConditionalExpression */);
node.condition = ts.parenthesizeForConditionalHead(condition);
node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(54 /* QuestionToken */);
node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue
);
node.colonToken = whenFalse ? colonToken : createToken(55 /* ColonToken */);
node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
return node;
}n/a
function createConstructor(decorators, modifiers, parameters, body) {
var node = createSynthesizedNode(151 /* Constructor */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.typeParameters = undefined;
node.parameters = createNodeArray(parameters);
node.type = undefined;
node.body = body;
return node;
}n/a
function createContinue(label) {
var node = createSynthesizedNode(216 /* ContinueStatement */);
node.label = asName(label);
return node;
}n/a
function createDecorator(expression) {
var node = createSynthesizedNode(146 /* Decorator */);
node.expression = ts.parenthesizeForAccess(expression);
return node;
}n/a
function createDefaultClause(statements) {
var node = createSynthesizedNode(256 /* DefaultClause */);
node.statements = createNodeArray(statements);
return node;
}n/a
function createDelete(expression) {
var node = createSynthesizedNode(187 /* DeleteExpression */);
node.expression = ts.parenthesizePrefixOperand(expression);
return node;
}n/a
function createDiagnosticCollection() {
var nonFileDiagnostics = [];
var fileDiagnostics = ts.createMap();
var diagnosticsModified = false;
var modificationCount = 0;
return {
add: add,
getGlobalDiagnostics: getGlobalDiagnostics,
getDiagnostics: getDiagnostics,
getModificationCount: getModificationCount,
reattachFileDiagnostics: reattachFileDiagnostics
};
function getModificationCount() {
return modificationCount;
}
function reattachFileDiagnostics(newFile) {
ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
}
function add(diagnostic) {
var diagnostics;
if (diagnostic.file) {
diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
if (!diagnostics) {
diagnostics = [];
fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
}
}
else {
diagnostics = nonFileDiagnostics;
}
diagnostics.push(diagnostic);
diagnosticsModified = true;
modificationCount++;
}
function getGlobalDiagnostics() {
sortAndDeduplicate();
return nonFileDiagnostics;
}
function getDiagnostics(fileName) {
sortAndDeduplicate();
if (fileName) {
return fileDiagnostics.get(fileName) || [];
}
var allDiagnostics = [];
function pushDiagnostic(d) {
allDiagnostics.push(d);
}
ts.forEach(nonFileDiagnostics, pushDiagnostic);
fileDiagnostics.forEach(function (diagnostics) {
ts.forEach(diagnostics, pushDiagnostic);
});
return ts.sortAndDeduplicateDiagnostics(allDiagnostics);
}
function sortAndDeduplicate() {
if (!diagnosticsModified) {
return;
}
diagnosticsModified = false;
nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics);
fileDiagnostics.forEach(function (diagnostics, key) {
fileDiagnostics.set(key, ts.sortAndDeduplicateDiagnostics(diagnostics));
});
}
}n/a
function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
var sourceFile = getSourceFileOfNode(node);
return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
}n/a
function createDiagnosticForNodeFromMessageChain(node, messageChain) {
var sourceFile = getSourceFileOfNode(node);
var span = getErrorSpanForNode(sourceFile, node);
return {
file: sourceFile,
start: span.start,
length: span.length,
code: messageChain.code,
category: messageChain.category,
messageText: messageChain.next ? messageChain : messageChain.messageText
};
}n/a
function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) {
var span = getErrorSpanForNode(sourceFile, node);
return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2);
}n/a
function createDo(statement, expression) {
var node = createSynthesizedNode(211 /* DoStatement */);
node.statement = statement;
node.expression = expression;
return node;
}n/a
function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) {
if (currentDirectory === void 0) { currentDirectory = ""; }
// Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have
// for those settings.
var buckets = ts.createMap();
var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames);
function getKeyForCompilationSettings(settings) {
return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs
+ "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify
(settings.paths);
}
function getBucketForCompilationSettings(key, createIfMissing) {
var bucket = buckets.get(key);
if (!bucket && createIfMissing) {
buckets.set(key, bucket = ts.createFileMap());
}
return bucket;
}
function reportStats() {
var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map
(function (name) {
var entries = buckets.get(name);
var sourceFiles = [];
entries.forEachValue(function (key, entry) {
sourceFiles.push({
name: key,
refCount: entry.languageServiceRefCount,
references: entry.owners.slice(0)
});
});
sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; });
return {
bucket: name,
sourceFiles: sourceFiles
};
});
return JSON.stringify(bucketInfoArray, undefined, 2);
}
function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) {
var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
var key = getKeyForCompilationSettings(compilationSettings);
return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
}
function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) {
return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind
);
}
function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) {
var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
var key = getKeyForCompilationSettings(compilationSettings);
return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
}
function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) {
return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind
);
}
function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true);
var entry = bucket.get(path);
if (!entry) {
ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?");
// Have never seen this file with these settings. Create a new source file for it.
var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*
setNodeParents*/ false, scriptKind);
entry = {
sourceFile: sourceFile,
languageServiceRefCount: 0,
owners: []
};
bucket.set(path, entry);
}
else {
// We have an entry for this file. However, it may be for a different version of
// the script snapshot. If so, update it appropriately. Otherwise, we ...n/a
function createElementAccess(expression, index) {
var node = createSynthesizedNode(179 /* ElementAccessExpression */);
node.expression = ts.parenthesizeForAccess(expression);
node.argumentExpression = asExpression(index);
return node;
}n/a
function createEmptyStatement() {
return createSynthesizedNode(208 /* EmptyStatement */);
}n/a
function createEndOfDeclarationMarker(original) {
var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
}n/a
function createEnumDeclaration(decorators, modifiers, name, members) {
var node = createSynthesizedNode(231 /* EnumDeclaration */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.name = asName(name);
node.members = createNodeArray(members);
return node;
}n/a
function createEnumMember(name, initializer) {
var node = createSynthesizedNode(262 /* EnumMember */);
node.name = asName(name);
node.initializer = initializer && ts.parenthesizeExpressionForList(initializer);
return node;
}n/a
function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
var node = createSynthesizedNode(242 /* ExportAssignment */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.isExportEquals = isExportEquals;
node.expression = expression;
return node;
}n/a
function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) {
var node = createSynthesizedNode(243 /* ExportDeclaration */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.exportClause = exportClause;
node.moduleSpecifier = moduleSpecifier;
return node;
}n/a
function createExportDefault(expression) {
return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
}n/a
function createExportSpecifier(name, propertyName) {
var node = createSynthesizedNode(245 /* ExportSpecifier */);
node.name = asName(name);
node.propertyName = asName(propertyName);
return node;
}n/a
function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
var argumentsList = [tagName];
if (props) {
argumentsList.push(props);
}
if (children && children.length > 0) {
if (!props) {
argumentsList.push(ts.createNull());
}
if (children.length > 1) {
for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
var child = children_1[_i];
child.startsOnNewLine = true;
argumentsList.push(child);
}
}
else {
argumentsList.push(children[0]);
}
}
return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement),
/*typeArguments*/ undefined, argumentsList), location);
}n/a
function createExpressionForObjectLiteralElementLike(node, property, receiver) {
switch (property.kind) {
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine);
case 259 /* PropertyAssignment */:
return createExpressionForPropertyAssignment(property, receiver);
case 260 /* ShorthandPropertyAssignment */:
return createExpressionForShorthandPropertyAssignment(property, receiver);
case 150 /* MethodDeclaration */:
return createExpressionForMethodDeclaration(property, receiver);
}
}n/a
function createExpressionForPropertyName(memberName) {
if (ts.isIdentifier(memberName)) {
return ts.createLiteral(memberName);
}
else if (ts.isComputedPropertyName(memberName)) {
return ts.getMutableClone(memberName.expression);
}
else {
return ts.getMutableClone(memberName);
}
}n/a
function createExpressionFromEntityName(node) {
if (ts.isQualifiedName(node)) {
var left = createExpressionFromEntityName(node.left);
var right = ts.getMutableClone(node.right);
return ts.setTextRange(ts.createPropertyAccess(left, right), node);
}
else {
return ts.getMutableClone(node);
}
}n/a
function createExpressionWithTypeArguments(typeArguments, expression) {
var node = createSynthesizedNode(200 /* ExpressionWithTypeArguments */);
node.expression = ts.parenthesizeForAccess(expression);
node.typeArguments = asNodeArray(typeArguments);
return node;
}n/a
function createExternalModuleExport(exportName) {
return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(
exportName)]));
}n/a
function createExternalModuleReference(expression) {
var node = createSynthesizedNode(247 /* ExternalModuleReference */);
node.expression = expression;
return node;
}n/a
function createFalse() {
return createSynthesizedNode(85 /* FalseKeyword */);
}n/a
function createFileDiagnostic(file, start, length, message) {
var end = start + length;
Debug.assert(start >= 0, "start must be non-negative, is " + start);
Debug.assert(length >= 0, "length must be non-negative, is " + length);
if (file) {
Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length
);
Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length);
}
var text = getLocaleSpecificMessage(message);
if (arguments.length > 4) {
text = formatStringFromArgs(text, arguments, 4);
}
return {
file: file,
start: start,
length: length,
messageText: text,
category: message.category,
code: message.code,
};
}n/a
function createFileMap(keyMapper) {
var files = createMap();
return {
get: get,
set: set,
contains: contains,
remove: remove,
forEachValue: forEachValueInMap,
getKeys: getKeys,
clear: clear,
};
function forEachValueInMap(f) {
files.forEach(function (file, key) {
f(key, file);
});
}
function getKeys() {
return arrayFrom(files.keys());
}
// path should already be well-formed so it does not need to be normalized
function get(path) {
return files.get(toKey(path));
}
function set(path, value) {
files.set(toKey(path), value);
}
function contains(path) {
return files.has(toKey(path));
}
function remove(path) {
files.delete(toKey(path));
}
function clear() {
files.clear();
}
function toKey(path) {
return keyMapper ? keyMapper(path) : path;
}
}n/a
function createFor(initializer, condition, incrementor, statement) {
var node = createSynthesizedNode(213 /* ForStatement */);
node.initializer = initializer;
node.condition = condition;
node.incrementor = incrementor;
node.statement = statement;
return node;
}n/a
function createForIn(initializer, expression, statement) {
var node = createSynthesizedNode(214 /* ForInStatement */);
node.initializer = initializer;
node.expression = expression;
node.statement = statement;
return node;
}n/a
function createForOf(initializer, expression, statement) {
var node = createSynthesizedNode(215 /* ForOfStatement */);
node.initializer = initializer;
node.expression = expression;
node.statement = statement;
return node;
}n/a
function createFunctionApply(func, thisArg, argumentsExpression, location) {
return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"),
/*typeArguments*/ undefined, [
thisArg,
argumentsExpression
]), location);
}n/a
function createFunctionCall(func, thisArg, argumentsList, location) {
return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"),
/*typeArguments*/ undefined, [
thisArg
].concat(argumentsList)), location);
}n/a
function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
var node = createSynthesizedNode(227 /* FunctionDeclaration */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.asteriskToken = asteriskToken;
node.name = asName(name);
node.typeParameters = asNodeArray(typeParameters);
node.parameters = createNodeArray(parameters);
node.type = type;
node.body = body;
return node;
}n/a
function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
var node = createSynthesizedNode(185 /* FunctionExpression */);
node.modifiers = asNodeArray(modifiers);
node.asteriskToken = asteriskToken;
node.name = asName(name);
node.typeParameters = asNodeArray(typeParameters);
node.parameters = createNodeArray(parameters);
node.type = type;
node.body = body;
return node;
}n/a
function createGetAccessor(decorators, modifiers, name, parameters, type, body) {
var node = createSynthesizedNode(152 /* GetAccessor */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.name = asName(name);
node.typeParameters = undefined;
node.parameters = createNodeArray(parameters);
node.type = type;
node.body = body;
return node;
}n/a
function createGetCanonicalFileName(useCaseSensitiveFileNames) {
return useCaseSensitiveFileNames
? (function (fileName) { return fileName; })
: (function (fileName) { return fileName.toLowerCase(); });
}n/a
function createHeritageClause(token, types) {
var node = createSynthesizedNode(257 /* HeritageClause */);
node.token = token;
node.types = createNodeArray(types);
return node;
}n/a
function createIdentifier(text) {
var node = createSynthesizedNode(70 /* Identifier */);
node.text = ts.escapeIdentifier(text);
node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */;
node.autoGenerateKind = 0 /* None */;
node.autoGenerateId = 0;
return node;
}n/a
function createIf(expression, thenStatement, elseStatement) {
var node = createSynthesizedNode(210 /* IfStatement */);
node.expression = expression;
node.thenStatement = thenStatement;
node.elseStatement = elseStatement;
return node;
}n/a
function createImportClause(name, namedBindings) {
var node = createSynthesizedNode(238 /* ImportClause */);
node.name = name;
node.namedBindings = namedBindings;
return node;
}n/a
function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
var node = createSynthesizedNode(237 /* ImportDeclaration */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.importClause = importClause;
node.moduleSpecifier = moduleSpecifier;
return node;
}n/a
function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
var node = createSynthesizedNode(236 /* ImportEqualsDeclaration */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.name = asName(name);
node.moduleReference = moduleReference;
return node;
}n/a
function createImportSpecifier(propertyName, name) {
var node = createSynthesizedNode(241 /* ImportSpecifier */);
node.propertyName = propertyName;
node.name = name;
return node;
}n/a
function createJsxAttribute(name, initializer) {
var node = createSynthesizedNode(252 /* JsxAttribute */);
node.name = name;
node.initializer = initializer;
return node;
}n/a
function createJsxClosingElement(tagName) {
var node = createSynthesizedNode(251 /* JsxClosingElement */);
node.tagName = tagName;
return node;
}n/a
function createJsxElement(openingElement, children, closingElement) {
var node = createSynthesizedNode(248 /* JsxElement */);
node.openingElement = openingElement;
node.children = createNodeArray(children);
node.closingElement = closingElement;
return node;
}n/a
function createJsxExpression(expression, dotDotDotToken) {
var node = createSynthesizedNode(254 /* JsxExpression */);
node.dotDotDotToken = dotDotDotToken;
node.expression = expression;
return node;
}n/a
function createJsxOpeningElement(tagName, attributes) {
var node = createSynthesizedNode(250 /* JsxOpeningElement */);
node.tagName = tagName;
node.attributes = createNodeArray(attributes);
return node;
}n/a
function createJsxSelfClosingElement(tagName, attributes) {
var node = createSynthesizedNode(249 /* JsxSelfClosingElement */);
node.tagName = tagName;
node.attributes = createNodeArray(attributes);
return node;
}n/a
function createJsxSpreadAttribute(expression) {
var node = createSynthesizedNode(253 /* JsxSpreadAttribute */);
node.expression = expression;
return node;
}n/a
function createLabel(label, statement) {
var node = createSynthesizedNode(221 /* LabeledStatement */);
node.label = asName(label);
node.statement = statement;
return node;
}n/a
function createLanguageService(host, documentRegistry) {
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames
(), host.getCurrentDirectory()); }
var syntaxTreeCache = new SyntaxTreeCache(host);
var ruleProvider;
var program;
var lastProjectVersion;
var lastTypesRootVersion = 0;
var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames();
var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken());
var currentDirectory = host.getCurrentDirectory();
// Check if the localized messages json is set, otherwise query the host for it
if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) {
ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages();
}
function log(message) {
if (host.log) {
host.log(message);
}
}
var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitivefileNames);
function getValidSourceFile(fileName) {
var sourceFile = program.getSourceFile(fileName);
if (!sourceFile) {
throw new Error("Could not find file: '" + fileName + "'.");
}
return sourceFile;
}
function getRuleProvider(options) {
// Ensure rules are initialized and up to date wrt to formatting options
if (!ruleProvider) {
ruleProvider = new ts.formatting.RulesProvider();
}
ruleProvider.ensureUpToDate(options);
return ruleProvider;
}
function synchronizeHostData() {
// perform fast check if host supports it
if (host.getProjectVersion) {
var hostProjectVersion = host.getProjectVersion();
if (hostProjectVersion) {
if (lastProjectVersion === hostProjectVersion) {
return;
}
lastProjectVersion = hostProjectVersion;
}
}
var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0;
if (lastTypesRootVersion !== typeRootsVersion) {
log("TypeRoots version has changed; provide new program");
program = undefined;
lastTypesRootVersion = typeRootsVersion;
}
// Get a fresh cache of the host information
var hostCache = new HostCache(host, getCanonicalFileName);
// If the program is already up-to-date, we can reuse it
if (programUpToDate()) {
return;
}
// IMPORTANT - It is critical from this moment onward that we do not check
// cancellation tokens. We are about to mutate source files from a previous program
// instance. If we cancel midway through, we may end up in an inconsistent state where
// the program points to old source files that have been invalidated because of
// incremental parsing.
var oldSettings = program && program.getCompilerOptions();
var newSettings = hostCache.compilationSettings();
var shouldCreateNewSourceFiles = oldSettings &&
(oldSettings.target !== newSettings.target ||
oldSettings.module !== newSettings.module ||
oldSettings.moduleResolution !== newSettings.moduleResolution ||
oldSettings.noResolve !== newSettings.noResolve ||
oldSettings.jsx !== newSettings.jsx ||
oldSettings.allowJs !== newSettings.allowJs ||
oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit ||
oldSettings.baseUrl !== newSettings.baseUrl ||
!ts.equalOwnProperties(oldSettings.paths, newSettings.paths));
// Now create a new compiler
var compilerHost = {
getSourceFile: getOrCreateSourceFile,
getSourceFileByPath: getOrCreateSourceFileByPath,
getCancellationToken: function () { return cancellationToken; },
getCanonic ...n/a
function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) {
var text = scriptSnapshot.getText(0, scriptSnapshot.getLength());
var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind);
setSourceFileFields(sourceFile, scriptSnapshot, version);
return sourceFile;
}n/a
function createLessThan(left, right) {
return createBinary(left, 26 /* LessThanToken */, right);
}n/a
function createLiteral(value) {
if (typeof value === "number") {
return createNumericLiteral(value + "");
}
if (typeof value === "boolean") {
return value ? createTrue() : createFalse();
}
if (typeof value === "string") {
return createStringLiteral(value);
}
return createLiteralFromNode(value);
}n/a
function createLogicalAnd(left, right) {
return createBinary(left, 52 /* AmpersandAmpersandToken */, right);
}n/a
function createLogicalNot(operand) {
return createPrefix(50 /* ExclamationToken */, operand);
}n/a
function createLogicalOr(left, right) {
return createBinary(left, 53 /* BarBarToken */, right);
}n/a
function createLoopVariable() {
var name = createIdentifier("");
name.autoGenerateKind = 2 /* Loop */;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
return name;
}n/a
function createMap() {
return new MapCtr();
}n/a
function createMapFromTemplate(template) {
var map = new MapCtr();
// Copies keys/values from template. Note that for..in will not throw if
// template is undefined, and instead will just exit the loop.
for (var key in template)
if (hasOwnProperty.call(template, key)) {
map.set(key, template[key]);
}
return map;
}n/a
function createMathPow(left, right, location) {
return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"),
/*typeArguments*/ undefined, [left, right]), location);
}n/a
function createMemberAccessForPropertyName(target, memberName, location) {
if (ts.isComputedPropertyName(memberName)) {
return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location);
}
else {
var expression = ts.setTextRange(ts.isIdentifier(memberName)
? ts.createPropertyAccess(target, memberName)
: ts.createElementAccess(target, memberName), memberName);
ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
return expression;
}
}n/a
function createMergeDeclarationMarker(original) {
var node = createSynthesizedNode(298 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
}n/a
function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
var node = createSynthesizedNode(150 /* MethodDeclaration */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.asteriskToken = asteriskToken;
node.name = asName(name);
node.typeParameters = asNodeArray(typeParameters);
node.parameters = createNodeArray(parameters);
node.type = type;
node.body = body;
return node;
}n/a
function createModuleBlock(statements) {
var node = createSynthesizedNode(234 /* CaseBlock */);
node.statements = createNodeArray(statements);
return node;
}n/a
function createModuleDeclaration(decorators, modifiers, name, body, flags) {
var node = createSynthesizedNode(232 /* ModuleDeclaration */);
node.flags |= flags;
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.name = name;
node.body = body;
return node;
}n/a
function createModuleResolutionCache(currentDirectory, getCanonicalFileName) {
var directoryToModuleNameMap = ts.createFileMap();
var moduleNameToDirectoryMap = ts.createMap();
return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName
};
function getOrCreateCacheForDirectory(directoryName) {
var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
var perFolderCache = directoryToModuleNameMap.get(path);
if (!perFolderCache) {
perFolderCache = ts.createMap();
directoryToModuleNameMap.set(path, perFolderCache);
}
return perFolderCache;
}
function getOrCreateCacheForModuleName(nonRelativeModuleName) {
if (!moduleHasNonRelativeName(nonRelativeModuleName)) {
return undefined;
}
var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName);
if (!perModuleNameCache) {
perModuleNameCache = createPerModuleNameCache();
moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache);
}
return perModuleNameCache;
}
function createPerModuleNameCache() {
var directoryPathMap = ts.createFileMap();
return { get: get, set: set };
function get(directory) {
return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
}
/**
* At first this function add entry directory -> module resolution result to the table.
* Then it computes the set of parent folders for 'directory' that should have the same module resolution result
* and for every parent folder in set it adds entry: parent -> module resolution. .
* Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
* Set of parent folders that should have the same result will be:
* [
* /a/b/c/d, /a/b/c, /a/b
* ]
* this means that request for module resolution from file in any of these folder will be immediately found in cache.
*/
function set(directory, result) {
var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
// if entry is already in cache do nothing
if (directoryPathMap.contains(path)) {
return;
}
directoryPathMap.set(path, result);
var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName;
// find common prefix between directory and resolved file name
// this common prefix should be the shorted path that has the same resolution
// directory: /a/b/c/d/e
// resolvedFileName: /a/b/foo.d.ts
var commonPrefix = getCommonPrefix(path, resolvedFileName);
var current = path;
while (true) {
var parent = ts.getDirectoryPath(current);
if (parent === current || directoryPathMap.contains(parent)) {
break;
}
directoryPathMap.set(parent, result);
current = parent;
if (current == commonPrefix) {
break;
}
}
}
function getCommonPrefix(directory, resolution) {
if (resolution === undefined) {
return undefined;
}
var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
// find first position where directory and resolution differs
var i = 0;
while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory
.charCodeAt(i)) {
i++;
}
// find last directory separator before position i
var sep = directory.lastIndexOf(ts.directorySeparator, i);
if (sep < 0) {
r ...n/a
function createMultiMap() {
var map = createMap();
map.add = multiMapAdd;
map.remove = multiMapRemove;
return map;
}n/a
function createNamedExports(elements) {
var node = createSynthesizedNode(244 /* NamedExports */);
node.elements = createNodeArray(elements);
return node;
}n/a
function createNamedImports(elements) {
var node = createSynthesizedNode(240 /* NamedImports */);
node.elements = createNodeArray(elements);
return node;
}n/a
function createNamespaceImport(name) {
var node = createSynthesizedNode(239 /* NamespaceImport */);
node.name = name;
return node;
}n/a
function createNew(expression, typeArguments, argumentsArray) {
var node = createSynthesizedNode(181 /* NewExpression */);
node.expression = ts.parenthesizeForNew(expression);
node.typeArguments = asNodeArray(typeArguments);
node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
return node;
}n/a
function createNode(kind, pos, end) {
if (kind === 263 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos,
end);
}
else if (kind === 70 /* Identifier */) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos,
end);
}
else if (kind < 142 /* FirstNode */) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
}
}n/a
function createNodeArray(elements, hasTrailingComma) {
if (elements) {
if (ts.isNodeArray(elements)) {
return elements;
}
}
else {
elements = [];
}
var array = elements;
array.pos = -1;
array.end = -1;
array.hasTrailingComma = hasTrailingComma;
return array;
}n/a
function createNonNullExpression(expression) {
var node = createSynthesizedNode(202 /* NonNullExpression */);
node.expression = ts.parenthesizeForAccess(expression);
return node;
}n/a
function createNotEmittedStatement(original) {
var node = createSynthesizedNode(296 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
}n/a
function createNull() {
return createSynthesizedNode(94 /* NullKeyword */);
}n/a
function createNumericLiteral(value) {
var node = createSynthesizedNode(8 /* NumericLiteral */);
node.text = value;
return node;
}n/a
function createObjectBindingPattern(elements) {
var node = createSynthesizedNode(173 /* ObjectBindingPattern */);
node.elements = createNodeArray(elements);
return node;
}n/a
function createObjectLiteral(properties, multiLine) {
var node = createSynthesizedNode(177 /* ObjectLiteralExpression */);
node.properties = createNodeArray(properties);
if (multiLine) {
node.multiLine = true;
}
return node;
}n/a
function createOmittedExpression() {
return createSynthesizedNode(199 /* OmittedExpression */);
}n/a
function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
var node = createSynthesizedNode(145 /* Parameter */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.dotDotDotToken = dotDotDotToken;
node.name = asName(name);
node.questionToken = questionToken;
node.type = type;
node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined;
return node;
}n/a
function createParen(expression) {
var node = createSynthesizedNode(184 /* ParenthesizedExpression */);
node.expression = expression;
return node;
}n/a
function createPartiallyEmittedExpression(expression, original) {
var node = createSynthesizedNode(297 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
return node;
}n/a
function createPatternMatcher(pattern) {
// We'll often see the same candidate string many times when searching (For example, when
// we see the name of a module that is used everywhere, or the name of an overload). As
// such, we cache the information we compute about the candidate for the life of this
// pattern matcher so we don't have to compute it multiple times.
var stringToWordSpans = ts.createMap();
pattern = pattern.trim();
var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); });
var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid);
return {
getMatches: getMatches,
getMatchesForLastSegmentOfPattern: getMatchesForLastSegmentOfPattern,
patternContainsDots: dotSeparatedSegments.length > 1
};
// Quick checks so we can bail out when asked to match a candidate.
function skipMatch(candidate) {
return invalidPattern || !candidate;
}
function getMatchesForLastSegmentOfPattern(candidate) {
if (skipMatch(candidate)) {
return undefined;
}
return matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments));
}
function getMatches(candidateContainers, candidate) {
if (skipMatch(candidate)) {
return undefined;
}
// First, check that the last part of the dot separated pattern matches the name of the
// candidate. If not, then there's no point in proceeding and doing the more
// expensive work.
var candidateMatch = matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments));
if (!candidateMatch) {
return undefined;
}
candidateContainers = candidateContainers || [];
// -1 because the last part was checked against the name, and only the rest
// of the parts are checked against the container.
if (dotSeparatedSegments.length - 1 > candidateContainers.length) {
// There weren't enough container parts to match against the pattern parts.
// So this definitely doesn't match.
return undefined;
}
// So far so good. Now break up the container for the candidate and check if all
// the dotted parts match up correctly.
var totalMatch = candidateMatch;
for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) {
var segment = dotSeparatedSegments[i];
var containerName = candidateContainers[j];
var containerMatch = matchSegment(containerName, segment);
if (!containerMatch) {
// This container didn't match the pattern piece. So there's no match at all.
return undefined;
}
ts.addRange(totalMatch, containerMatch);
}
// Success, this symbol's full name matched against the dotted name the user was asking
// about.
return totalMatch;
}
function getWordSpans(word) {
var spans = stringToWordSpans.get(word);
if (!spans) {
stringToWordSpans.set(word, spans = breakIntoWordSpans(word));
}
return spans;
}
function matchTextChunk(candidate, chunk, punctuationStripped) {
var index = indexOfIgnoringCase(candidate, chunk.textLowerCase);
if (index === 0) {
if (chunk.text.length === candidate.length) {
// a) Check if the part matches the candidate entirely, in an case insensitive or
// sensitive manner. If it does, return that there was an exact match.
return createPatternMatch(PatternMatchKind.exact, punctuationStripped, /*isCaseSensitive:*/ candidate === chunk.
text);
}
else {
// b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive
// manner. If it does, return that there was a prefix match.
return creat ...n/a
function createPostfix(operand, operator) {
var node = createSynthesizedNode(192 /* PostfixUnaryExpression */);
node.operand = ts.parenthesizePostfixOperand(operand);
node.operator = operator;
return node;
}n/a
function createPostfixIncrement(operand) {
return createPostfix(operand, 42 /* PlusPlusToken */);
}n/a
function createPrefix(operator, operand) {
var node = createSynthesizedNode(191 /* PrefixUnaryExpression */);
node.operator = operator;
node.operand = ts.parenthesizePrefixOperand(operand);
return node;
}n/a
function createPrinter(printerOptions, handlers) {
if (printerOptions === void 0) { printerOptions = {}; }
if (handlers === void 0) { handlers = {}; }
var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken =
handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode
, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, onSubstituteNode = handlers.onSubstituteNode
;
var newLine = ts.getNewLineCharacter(printerOptions);
var languageVersion = ts.getEmitScriptTarget(printerOptions);
var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition);
var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments
, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition
;
var currentSourceFile;
var nodeIdToGeneratedName; // Map of generated names for specific nodes.
var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
var generatedNames; // Set of names generated by the NameGenerator.
var tempFlagsStack; // Stack of enclosing name generation scopes.
var tempFlags; // TempFlags for the current name generation scope.
var writer;
var ownWriter;
reset();
return {
// public API
printNode: printNode,
printFile: printFile,
printBundle: printBundle,
// internal API
writeNode: writeNode,
writeFile: writeFile,
writeBundle: writeBundle
};
function printNode(hint, node, sourceFile) {
switch (hint) {
case 0 /* SourceFile */:
ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
break;
case 2 /* IdentifierName */:
ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
break;
case 1 /* Expression */:
ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
break;
}
switch (node.kind) {
case 263 /* SourceFile */: return printFile(node);
case 264 /* Bundle */: return printBundle(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
}
function printBundle(bundle) {
writeBundle(bundle, beginPrint());
return endPrint();
}
function printFile(sourceFile) {
writeFile(sourceFile, beginPrint());
return endPrint();
}
function writeNode(hint, node, sourceFile, output) {
var previousWriter = writer;
setWriter(output);
print(hint, node, sourceFile);
reset();
writer = previousWriter;
}
function writeBundle(bundle, output) {
var previousWriter = writer;
setWriter(output);
emitHelpersIndirect(bundle);
for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
var sourceFile = _b[_a];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
reset();
writer = previousWriter;
}
function writeFile(sourceFile, output) {
var previousWriter = writer;
setWriter(output);
print(0 /* SourceFile */, sourceFile, sourceFile);
reset();
writer = previousWriter;
}
function beginPrint() {
return ownWriter || (ownWriter = ts.createTextWriter(newLine));
}
function endPrint() {
var text = ownWriter.getText();
ownWriter.reset();
return text;
}
function print(hint, node, sourceFile) {
setSourceFile(sourceFile);
pipelineEmitWithNotification(hint, node);
}
function setSourceFile(sourceFile) {
currentSourceFile = sourceFile;
comments.setSourceFile(sourceFile);
if (onSetSour ...n/a
function createProgram(rootNames, options, host, oldProgram) {
var program;
var files = [];
var commonSourceDirectory;
var diagnosticsProducingTypeChecker;
var noDiagnosticsTypeChecker;
var classifiableNames;
var resolvedTypeReferenceDirectives = ts.createMap();
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
// The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
// This works as imported modules are discovered recursively in a depth first manner, specifically:
// - For each root file, findSourceFile is called.
// - This calls processImportedModules for each module imported in the source file.
// - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
// As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
// The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
var currentNodeModulesDepth = 0;
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
// this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
var modulesWithElidedImports = ts.createMap();
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
var sourceFilesFoundSearchingNodeModules = ts.createMap();
ts.performance.mark("beforeProgram");
host = host || createCompilerHost(options);
var skipDefaultLib = options.noLib;
var programDiagnostics = ts.createDiagnosticCollection();
var currentDirectory = host.getCurrentDirectory();
var supportedExtensions = ts.getSupportedExtensions(options);
// Map storing if there is emit blocking diagnostics for given input
var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName);
var moduleResolutionCache;
var resolveModuleNamesWorker;
if (host.resolveModuleNames) {
resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile
).map(function (resolved) {
// An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName
.
if (!resolved || resolved.extension !== undefined) {
return resolved;
}
var withExtension = ts.clone(resolved);
withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
return withExtension;
}); };
}
else {
moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName
(x); });
var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options,
host, moduleResolutionCache).resolvedModule; };
resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile
, loader_1); };
}
var resolveTypeReferenceDirectiveNamesWorker;
if (host.resolveTypeReferenceDirectives) {
resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives
(typeDirectiveNames, containingFile); };
}
else {
var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options
, host).resolvedTypeReferenceDirective; };
resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache
(typeReferenceDirectiveNames, containingFile, loader_2); };
}
var filesByName = ts.createFileMap();
// stores 'filename -> file association' igno ...n/a
function createProperty(decorators, modifiers, name, questionToken, type, initializer) {
var node = createSynthesizedNode(148 /* PropertyDeclaration */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.name = asName(name);
node.questionToken = questionToken;
node.type = type;
node.initializer = initializer;
return node;
}n/a
function createPropertyAccess(expression, name) {
var node = createSynthesizedNode(178 /* PropertyAccessExpression */);
node.expression = ts.parenthesizeForAccess(expression);
node.name = asName(name);
setEmitFlags(node, 65536 /* NoIndentation */);
return node;
}n/a
function createPropertyAssignment(name, initializer) {
var node = createSynthesizedNode(259 /* PropertyAssignment */);
node.name = asName(name);
node.questionToken = undefined;
node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
return node;
}n/a
function createQualifiedName(left, right) {
var node = createSynthesizedNode(142 /* QualifiedName */);
node.left = left;
node.right = asName(right);
return node;
}n/a
function createRange(pos, end) {
return { pos: pos, end: end };
}n/a
function createReturn(expression) {
var node = createSynthesizedNode(218 /* ReturnStatement */);
node.expression = expression;
return node;
}n/a
function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) {
if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
// Current position (end position of text of current token)
var pos;
// end of text
var end;
// Start position of whitespace before current token
var startPos;
// Start position of text of current token
var tokenPos;
var token;
var tokenValue;
var precedingLineBreak;
var hasExtendedUnicodeEscape;
var tokenIsUnterminated;
setText(text, start, length);
return {
getStartPos: function () { return startPos; },
getTextPos: function () { return pos; },
getToken: function () { return token; },
getTokenPos: function () { return tokenPos; },
getTokenText: function () { return text.substring(tokenPos, pos); },
getTokenValue: function () { return tokenValue; },
hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; },
hasPrecedingLineBreak: function () { return precedingLineBreak; },
isIdentifier: function () { return token === 70 /* Identifier */ || token > 106 /* LastReservedWord */; },
isReservedWord: function () { return token >= 71 /* FirstReservedWord */ && token <= 106 /* LastReservedWord */; },
isUnterminated: function () { return tokenIsUnterminated; },
reScanGreaterToken: reScanGreaterToken,
reScanSlashToken: reScanSlashToken,
reScanTemplateToken: reScanTemplateToken,
scanJsxIdentifier: scanJsxIdentifier,
scanJsxAttributeValue: scanJsxAttributeValue,
reScanJsxToken: reScanJsxToken,
scanJsxToken: scanJsxToken,
scanJSDocToken: scanJSDocToken,
scan: scan,
getText: getText,
setText: setText,
setScriptTarget: setScriptTarget,
setLanguageVariant: setLanguageVariant,
setOnError: setOnError,
setTextPos: setTextPos,
tryScan: tryScan,
lookAhead: lookAhead,
scanRange: scanRange,
};
function error(message, length) {
if (onError) {
onError(message, length || 0);
}
}
function scanNumber() {
var start = pos;
while (isDigit(text.charCodeAt(pos)))
pos++;
if (text.charCodeAt(pos) === 46 /* dot */) {
pos++;
while (isDigit(text.charCodeAt(pos)))
pos++;
}
var end = pos;
if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
pos++;
if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
pos++;
if (isDigit(text.charCodeAt(pos))) {
pos++;
while (isDigit(text.charCodeAt(pos)))
pos++;
end = pos;
}
else {
error(ts.Diagnostics.Digit_expected);
}
}
return "" + +(text.substring(start, end));
}
function scanOctalDigits() {
var start = pos;
while (isOctalDigit(text.charCodeAt(pos))) {
pos++;
}
return +(text.substring(start, pos));
}
/**
* Scans the given number of hexadecimal digits in the text,
* returning -1 if the given number is unavailable.
*/
function scanExactNumberOfHexDigits(count) {
return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false);
}
/**
* Scans as many hexadecimal digits as are available in the text,
* returning -1 if the given number of digits was unavailable.
*/
function scanMinimumNumberOfHexDigits(count) {
return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true);
}
function scanHexDigits(minCount, scanAsManyAsPossible) {
var digits = 0;
var value = 0;
while (digits < minCount || scanAsManyAsPossible) {
var ch = text.charCodeAt(pos);
if (ch >= 48 /* _0 */ && ch <= 57 ...n/a
function createSetAccessor(decorators, modifiers, name, parameters, body) {
var node = createSynthesizedNode(153 /* SetAccessor */);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.name = asName(name);
node.typeParameters = undefined;
node.parameters = createNodeArray(parameters);
node.body = body;
return node;
}n/a
function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
var node = createSynthesizedNode(260 /* ShorthandPropertyAssignment */);
node.name = asName(name);
node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer
) : undefined;
return node;
}n/a
function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
if (setParentNodes === void 0) { setParentNodes = false; }
ts.performance.mark("beforeParse");
var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind
);
ts.performance.mark("afterParse");
ts.performance.measure("Parse", "beforeParse", "afterParse");
return result;
}n/a
function createSourceMapWriter(host, writer) {
var compilerOptions = host.getCompilerOptions();
var extendedDiagnostics = compilerOptions.extendedDiagnostics;
var currentSourceFile;
var currentSourceText;
var sourceMapDir; // The directory in which sourcemap will be
// Current source map file and its index in the sources list
var sourceMapSourceIndex;
// Last recorded and encoded spans
var lastRecordedSourceMapSpan;
var lastEncodedSourceMapSpan;
var lastEncodedNameIndex;
// Source map data
var sourceMapData;
var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap);
return {
initialize: initialize,
reset: reset,
getSourceMapData: function () { return sourceMapData; },
setSourceFile: setSourceFile,
emitPos: emitPos,
emitNodeWithSourceMap: emitNodeWithSourceMap,
emitTokenWithSourceMap: emitTokenWithSourceMap,
getText: getText,
getSourceMappingURL: getSourceMappingURL,
};
/**
* Initialize the SourceMapWriter for a new output file.
*
* @param filePath The path to the generated output file.
* @param sourceMapFilePath The path to the output source map file.
* @param sourceFileOrBundle The input source file or bundle for the program.
*/
function initialize(filePath, sourceMapFilePath, sourceFileOrBundle) {
if (disabled) {
return;
}
if (sourceMapData) {
reset();
}
currentSourceFile = undefined;
currentSourceText = undefined;
// Current source map file and its index in the sources list
sourceMapSourceIndex = -1;
// Last recorded and encoded spans
lastRecordedSourceMapSpan = undefined;
lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan;
lastEncodedNameIndex = 0;
// Initialize source map data
sourceMapData = {
sourceMapFilePath: sourceMapFilePath,
jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) :
undefined,
sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)),
sourceMapSourceRoot: compilerOptions.sourceRoot || "",
sourceMapSources: [],
inputSourceFileNames: [],
sourceMapNames: [],
sourceMapMappings: "",
sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined,
sourceMapDecodedMappings: []
};
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
// relative paths of the sources list in the sourcemap
sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot);
if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot
.length - 1) !== 47 /* slash */) {
sourceMapData.sourceMapSourceRoot += ts.directorySeparator;
}
if (compilerOptions.mapRoot) {
sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot);
if (sourceFileOrBundle.kind === 263 /* SourceFile */) {
// For modules or multiple emit files the mapRoot will have directory structure like the sources
// So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and
mapRoot\lib\b.js.map
sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir));
}
if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) {
// The relative paths are relative to the common directory
sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath
)), // get the relative s ...n/a
function createSpread(expression) {
var node = createSynthesizedNode(197 /* SpreadElement */);
node.expression = ts.parenthesizeExpressionForList(expression);
return node;
}n/a
function createSpreadAssignment(expression) {
var node = createSynthesizedNode(261 /* SpreadAssignment */);
node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined;
return node;
}n/a
function createStatement(expression) {
var node = createSynthesizedNode(209 /* ExpressionStatement */);
node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
return node;
}n/a
function createStrictEquality(left, right) {
return createBinary(left, 33 /* EqualsEqualsEqualsToken */, right);
}n/a
function createStrictInequality(left, right) {
return createBinary(left, 34 /* ExclamationEqualsEqualsToken */, right);
}n/a
function createSubtract(left, right) {
return createBinary(left, 37 /* MinusToken */, right);
}n/a
function createSuper() {
return createSynthesizedNode(96 /* SuperKeyword */);
}n/a
function createSwitch(expression, caseBlock) {
var node = createSynthesizedNode(220 /* SwitchStatement */);
node.expression = ts.parenthesizeExpressionForList(expression);
node.caseBlock = caseBlock;
return node;
}n/a
function createTaggedTemplate(tag, template) {
var node = createSynthesizedNode(182 /* TaggedTemplateExpression */);
node.tag = ts.parenthesizeForAccess(tag);
node.template = template;
return node;
}n/a
function createTempVariable(recordTempVariable) {
var name = createIdentifier("");
name.autoGenerateKind = 1 /* Auto */;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
if (recordTempVariable) {
recordTempVariable(name);
}
return name;
}n/a
function createTemplateExpression(head, templateSpans) {
var node = createSynthesizedNode(195 /* TemplateExpression */);
node.head = head;
node.templateSpans = createNodeArray(templateSpans);
return node;
}n/a
function createTemplateSpan(expression, literal) {
var node = createSynthesizedNode(204 /* TemplateSpan */);
node.expression = expression;
node.literal = literal;
return node;
}n/a
function createTextChangeRange(span, newLength) {
if (newLength < 0) {
throw new Error("newLength < 0");
}
return { span: span, newLength: newLength };
}n/a
function createTextSpan(start, length) {
if (start < 0) {
throw new Error("start < 0");
}
if (length < 0) {
throw new Error("length < 0");
}
return { start: start, length: length };
}n/a
function createTextSpanFromBounds(start, end) {
return createTextSpan(start, end - start);
}n/a
function createTextSpanFromNode(node, sourceFile) {
return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd());
}n/a
function createTextWriter(newLine) {
var output;
var indent;
var lineStart;
var lineCount;
var linePos;
function write(s) {
if (s && s.length) {
if (lineStart) {
output += getIndentString(indent);
lineStart = false;
}
output += s;
}
}
function reset() {
output = "";
indent = 0;
lineStart = true;
lineCount = 0;
linePos = 0;
}
function rawWrite(s) {
if (s !== undefined) {
if (lineStart) {
lineStart = false;
}
output += s;
}
}
function writeLiteral(s) {
if (s && s.length) {
write(s);
var lineStartsOfS = ts.computeLineStarts(s);
if (lineStartsOfS.length > 1) {
lineCount = lineCount + lineStartsOfS.length - 1;
linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS);
}
}
}
function writeLine() {
if (!lineStart) {
output += newLine;
lineCount++;
linePos = output.length;
lineStart = true;
}
}
function writeTextOfNode(text, node) {
write(getTextOfNodeFromSourceText(text, node));
}
reset();
return {
write: write,
rawWrite: rawWrite,
writeTextOfNode: writeTextOfNode,
writeLiteral: writeLiteral,
writeLine: writeLine,
increaseIndent: function () { indent++; },
decreaseIndent: function () { indent--; },
getIndent: function () { return indent; },
getTextPos: function () { return output.length; },
getLine: function () { return lineCount + 1; },
getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; },
getText: function () { return output; },
isAtStartOfLine: function () { return lineStart; },
reset: reset
};
}n/a
function createThis() {
return createSynthesizedNode(98 /* ThisKeyword */);
}n/a
function createThrow(expression) {
var node = createSynthesizedNode(222 /* ThrowStatement */);
node.expression = expression;
return node;
}n/a
function createToken(token) {
return createSynthesizedNode(token);
}n/a
function createTokenRange(pos, token) {
return createRange(pos, pos + ts.tokenToString(token).length);
}n/a
function createTrue() {
return createSynthesizedNode(100 /* TrueKeyword */);
}n/a
function createTry(tryBlock, catchClause, finallyBlock) {
var node = createSynthesizedNode(223 /* TryStatement */);
node.tryBlock = tryBlock;
node.catchClause = catchClause;
node.finallyBlock = finallyBlock;
return node;
}n/a
function createTypeAssertion(type, expression) {
var node = createSynthesizedNode(183 /* TypeAssertionExpression */);
node.type = type;
node.expression = ts.parenthesizePrefixOperand(expression);
return node;
}n/a
function createTypeCheck(value, tag) {
return tag === "undefined"
? ts.createStrictEquality(value, ts.createVoidZero())
: ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag));
}n/a
function createTypeChecker(host, produceDiagnostics) {
// Cancellation that controls whether or not we can cancel in the middle of type checking.
// In general cancelling is *not* safe for the type checker. We might be in the middle of
// computing something, and we will leave our internals in an inconsistent state. Callers
// who set the cancellation token should catch if a cancellation exception occurs, and
// should throw away and create a new TypeChecker.
//
// Currently we only support setting the cancellation token when getting diagnostics. This
// is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
// they no longer need the information (for example, if the user started editing again).
var cancellationToken;
var requestedExternalEmitHelpers;
var externalHelpersModule;
var Symbol = ts.objectAllocator.getSymbolConstructor();
var Type = ts.objectAllocator.getTypeConstructor();
var Signature = ts.objectAllocator.getSignatureConstructor();
var typeCount = 0;
var symbolCount = 0;
var emptyArray = [];
var emptySymbols = ts.createMap();
var compilerOptions = host.getCompilerOptions();
var languageVersion = compilerOptions.target || 0 /* ES3 */;
var modulekind = ts.getEmitModuleKind(compilerOptions);
var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters;
var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports
: modulekind === ts.ModuleKind.System;
var strictNullChecks = compilerOptions.strictNullChecks;
var emitResolver = createResolver();
var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
undefinedSymbol.declarations = [];
var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
var checker = {
getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
getTypeCount: function () { return typeCount; },
isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
getDiagnostics: getDiagnostics,
getGlobalDiagnostics: getGlobalDiagnostics,
getTypeOfSymbolAtLocation: getTypeOfSymbolAtLocation,
getSymbolsOfParameterPropertyDeclaration: getSymbolsOfParameterPropertyDeclaration,
getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
getPropertiesOfType: getPropertiesOfType,
getPropertyOfType: getPropertyOfType,
getIndexInfoOfType: getIndexInfoOfType,
getSignaturesOfType: getSignaturesOfType,
getIndexTypeOfType: getIndexTypeOfType,
getBaseTypes: getBaseTypes,
getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
getWidenedType: getWidenedType,
getTypeFromTypeNode: getTypeFromTypeNode,
getParameterType: getTypeAtPosition,
getReturnTypeOfSignature: getReturnTypeOfSignature,
getNonNullableType: getNonNullableType,
getSymbolsInScope: getSymbolsInScope,
getSymbolAtLocation: getSymbolAtLocation,
getShorthandAssignmentValueSymbol: getShorthandAssignmentValueSymbol,
getExportSpecifierLocalTargetSymbol: getExportSpecifierLocalTargetSymbol,
getTypeAtLocation: getTypeOfNode,
getPropertySymbolOfDestructuringAssignment: getPropertySymbolOfDestructuringAssignment,
signatureToString: signatureToString,
typeToString: typeToString,
getSymbolDisplayBuilder: getSymbolDisplayBuilder,
symbolToString: symbolToString,
getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
getRoo ...n/a
function createTypeOf(expression) {
var node = createSynthesizedNode(188 /* TypeOfExpression */);
node.expression = ts.parenthesizePrefixOperand(expression);
return node;
}n/a
function createUniqueName(text) {
var name = createIdentifier(text);
name.autoGenerateKind = 3 /* Unique */;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
return name;
}n/a
function createVariableDeclaration(name, type, initializer) {
var node = createSynthesizedNode(225 /* VariableDeclaration */);
node.name = asName(name);
node.type = type;
node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
return node;
}n/a
function createVariableDeclarationList(declarations, flags) {
var node = createSynthesizedNode(226 /* VariableDeclarationList */);
node.flags |= flags;
node.declarations = createNodeArray(declarations);
return node;
}n/a
function createVariableStatement(modifiers, declarationList) {
var node = createSynthesizedNode(207 /* VariableStatement */);
node.decorators = undefined;
node.modifiers = asNodeArray(modifiers);
node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
return node;
}n/a
function createVoid(expression) {
var node = createSynthesizedNode(189 /* VoidExpression */);
node.expression = ts.parenthesizePrefixOperand(expression);
return node;
}n/a
function createVoidZero() {
return createVoid(createLiteral(0));
}n/a
function createWhile(expression, statement) {
var node = createSynthesizedNode(212 /* WhileStatement */);
node.expression = expression;
node.statement = statement;
return node;
}n/a
function createWith(expression, statement) {
var node = createSynthesizedNode(219 /* WithStatement */);
node.expression = expression;
node.statement = statement;
return node;
}n/a
function createYield(asteriskTokenOrExpression, expression) {
var node = createSynthesizedNode(196 /* YieldExpression */);
node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 38 /* AsteriskToken */ ? asteriskTokenOrExpression
: undefined;
node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 38 /* AsteriskToken */ ? asteriskTokenOrExpression
: expression;
return node;
}n/a
function declarationNameToString(name) {
return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
}n/a
function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
var end1 = start1 + length1;
var end2 = start2 + length2;
return start2 <= end1 && end2 >= start1;
}n/a
function deduplicate(array, areEqual) {
var result;
if (array) {
result = [];
loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
var item = array_6[_i];
for (var _a = 0, result_1 = result; _a < result_1.length; _a++) {
var res = result_1[_a];
if (areEqual ? areEqual(res, item) : res === item) {
continue loop;
}
}
result.push(item);
}
}
return result;
}n/a
function deduplicateSortedDiagnostics(diagnostics) {
if (diagnostics.length < 2) {
return diagnostics;
}
var newDiagnostics = [diagnostics[0]];
var previousDiagnostic = diagnostics[0];
for (var i = 1; i < diagnostics.length; i++) {
var currentDiagnostic = diagnostics[i];
var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === 0 /* EqualTo */;
if (!isDupe) {
newDiagnostics.push(currentDiagnostic);
previousDiagnostic = currentDiagnostic;
}
}
return newDiagnostics;
}n/a
function directoryProbablyExists(directoryName, host) {
// if host does not support 'directoryExists' assume that directory will exist
return !host.directoryExists || host.directoryExists(directoryName);
}n/a
function displayPart(text, kind) {
return {
text: text,
kind: ts.SymbolDisplayPartKind[kind]
};
}n/a
function displayPartsToString(displayParts) {
if (displayParts) {
return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join("");
}
return "";
}n/a
function disposeEmitNodes(sourceFile) {
// During transformation we may need to annotate a parse tree node with transient
// transformation properties. As parse tree nodes live longer than transformation
// nodes, we need to make sure we reclaim any memory allocated for custom ranges
// from these nodes to ensure we do not hold onto entire subtrees just for position
// information. We also need to reset these nodes to a pre-transformation state
// for incremental parsing scenarios so that we do not impact later emit.
sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
var emitNode = sourceFile && sourceFile.emitNode;
var annotatedNodes = emitNode && emitNode.annotatedNodes;
if (annotatedNodes) {
for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
var node = annotatedNodes_1[_i];
node.emitNode = undefined;
}
}
}n/a
function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
if (comments && comments.length > 0) {
if (leadingSeparator) {
writer.write(" ");
}
var emitInterveningSeparator = false;
for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
var comment = comments_1[_i];
if (emitInterveningSeparator) {
writer.write(" ");
emitInterveningSeparator = false;
}
writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
if (comment.hasTrailingNewLine) {
writer.writeLine();
}
else {
emitInterveningSeparator = true;
}
}
if (emitInterveningSeparator && trailingSeparator) {
writer.write(" ");
}
}
}n/a
function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
var leadingComments;
var currentDetachedCommentInfo;
if (removeComments) {
// removeComments is true, only reserve pinned comment at the top of file
// For example:
// /*! Pinned Comment */
//
// var x = 10;
if (node.pos === 0) {
leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment);
}
}
else {
// removeComments is false, just get detached as normal and bypass the process to filter comment
leadingComments = ts.getLeadingCommentRanges(text, node.pos);
}
if (leadingComments) {
var detachedComments = [];
var lastComment = void 0;
for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
var comment = leadingComments_1[_i];
if (lastComment) {
var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
if (commentLine >= lastCommentLine + 2) {
// There was a blank line between the last comment and this comment. This
// comment is not part of the copyright comments. Return what we have so
// far.
break;
}
}
detachedComments.push(comment);
lastComment = comment;
}
if (detachedComments.length) {
// All comments look like they could have been part of the copyright header. Make
// sure there is at least one blank line between it and the node. If not, it's not
// a copyright header.
var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end);
var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
if (nodeLine >= lastCommentLine + 2) {
// Valid detachedComments
emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine
, writeComment);
currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end
};
}
}
}
return currentDetachedCommentInfo;
function isPinnedComment(comment) {
return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
text.charCodeAt(comment.pos + 2) === 33 /* exclamation */;
}
}n/a
function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) {
var compilerOptions = host.getCompilerOptions();
var moduleKind = ts.getEmitModuleKind(compilerOptions);
var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
var emitterDiagnostics = ts.createDiagnosticCollection();
var newLine = host.getNewLine();
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(compilerOptions);
var writer = ts.createTextWriter(newLine);
var sourceMap = ts.createSourceMapWriter(host, writer);
var currentSourceFile;
var bundledHelpers;
var isOwnFileEmit;
var emitSkipped = false;
var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile);
// Transform the source files
var transform = ts.transformFiles(resolver, host, sourceFiles, transformers);
// Create a printer to print the nodes
var printer = createPrinter(compilerOptions, {
// resolver hooks
hasGlobalName: resolver.hasGlobalName,
// transform hooks
onEmitNode: transform.emitNodeWithNotification,
onSubstituteNode: transform.emitNodeWithSubstitution,
// sourcemap hooks
onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap,
onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap,
onEmitSourceMapOfPosition: sourceMap.emitPos,
// emitter hooks
onEmitHelpers: emitHelpers,
onSetSourceFile: setSourceFile,
});
// Emit each output file
ts.performance.mark("beforePrint");
ts.forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles);
ts.performance.measure("printTime", "beforePrint");
// Clean up emit nodes on parse tree
for (var _a = 0, sourceFiles_2 = sourceFiles; _a < sourceFiles_2.length; _a++) {
var sourceFile = sourceFiles_2[_a];
ts.disposeEmitNodes(sourceFile);
}
return {
emitSkipped: emitSkipped,
diagnostics: emitterDiagnostics.getDiagnostics(),
emittedFiles: emittedFilesList,
sourceMaps: sourceMapDataList
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath;
// Make sure not to write js file and source map file if any of them cannot be written
if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) {
if (!emitOnlyDtsFiles) {
printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle);
}
}
else {
emitSkipped = true;
}
if (declarationFilePath) {
emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFileOrBundle(sourceFileOrBundle), host
, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped;
}
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
emittedFilesList.push(jsFilePath);
}
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
if (declarationFilePath) {
emittedFilesList.push(declarationFilePath);
}
}
}
function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) {
var bundle = sourceFileOrBundle.kind === 264 /* Bundle */ ? sourceFileOrBundle : undefined;
var sourceFile = sourceFileOrBundle.kind === 263 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle);
if (bundle) {
bundledHelpers = ts.createMap();
isOwnFileEmit = false;
printer.writeBundle(bundle, writer);
}
else {
isOwnFileEmit = true;
printer.writeF ...n/a
function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
// If the leading comments start on different line than the start of node, write new line
if (pos !== commentPos &&
getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
writer.writeLine();
}
}n/a
function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
}n/a
function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
// If the leading comments start on different line than the start of node, write new line
if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
writer.writeLine();
}
}n/a
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}n/a
function ensureScriptKind(fileName, scriptKind) {
// Using scriptKind as a condition handles both:
// - 'scriptKind' is unspecified and thus it is `undefined`
// - 'scriptKind' is set and it is `Unknown` (0)
// If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
// to get the ScriptKind from the file name. If it cannot be resolved
// from the file name then the default 'TS' script kind is returned.
return (scriptKind || getScriptKindFromFileName(fileName)) || 3 /* TS */;
}n/a
function ensureTrailingDirectorySeparator(path) {
if (path.charAt(path.length - 1) !== ts.directorySeparator) {
return path + ts.directorySeparator;
}
return path;
}n/a
function ensureUseStrict(statements) {
var foundUseStrict = false;
for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
var statement = statements_1[_i];
if (ts.isPrologueDirective(statement)) {
if (isUseStrictPrologue(statement)) {
foundUseStrict = true;
break;
}
}
else {
break;
}
}
if (!foundUseStrict) {
return ts.setTextRange(ts.createNodeArray([
startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
].concat(statements)), statements);
}
return statements;
}n/a
function entityNameToString(name) {
switch (name.kind) {
case 70 /* Identifier */:
return getFullWidth(name) === 0 ? unescapeIdentifier(name.text) : getTextOfNode(name);
case 142 /* QualifiedName */:
return entityNameToString(name.left) + "." + entityNameToString(name.right);
case 178 /* PropertyAccessExpression */:
return entityNameToString(name.expression) + "." + entityNameToString(name.name);
}
}n/a
function equalOwnProperties(left, right, equalityComparer) {
if (left === right)
return true;
if (!left || !right)
return false;
for (var key in left)
if (hasOwnProperty.call(left, key)) {
if (!hasOwnProperty.call(right, key) === undefined)
return false;
if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key])
return false;
}
for (var key in right)
if (hasOwnProperty.call(right, key)) {
if (!hasOwnProperty.call(left, key))
return false;
}
return true;
}n/a
function escapeIdentifier(identifier) {
return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" +
identifier : identifier;
}n/a
function escapeNonAsciiCharacters(s) {
// Replace non-ASCII characters with '\uNNNN' escapes if any exist.
// Otherwise just return the original string.
return nonAsciiCharacters.test(s) ?
s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) :
s;
}n/a
function escapeString(s) {
return s.replace(escapedCharsRegExp, getReplacement);
}n/a
function every(array, callback) {
if (array) {
for (var i = 0; i < array.length; i++) {
if (!callback(array[i], i)) {
return false;
}
}
}
return true;
}n/a
function exportAssignmentIsAlias(node) {
return isEntityNameExpression(node.expression);
}n/a
function extend(first, second) {
var result = {};
for (var id in second)
if (hasOwnProperty.call(second, id)) {
result[id] = second[id];
}
for (var id in first)
if (hasOwnProperty.call(first, id)) {
result[id] = first[id];
}
return result;
}n/a
function extensionFromPath(path) {
var ext = tryGetExtensionFromPath(path);
if (ext !== undefined) {
return ext;
}
Debug.fail("File " + path + " has unknown extension.");
}n/a
function extensionIsTypeScript(ext) {
return ext <= ts.Extension.LastTypeScriptExtension;
}n/a
function fileExtensionIs(path, extension) {
return path.length > extension.length && endsWith(path, extension);
}n/a
function fileExtensionIsAny(path, extensions) {
for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
var extension = extensions_1[_i];
if (fileExtensionIs(path, extension)) {
return true;
}
}
return false;
}n/a
function filter(array, f) {
if (array) {
var len = array.length;
var i = 0;
while (i < len && f(array[i]))
i++;
if (i < len) {
var result = array.slice(0, i);
i++;
while (i < len) {
var item = array[i];
if (f(item)) {
result.push(item);
}
i++;
}
return result;
}
}
return array;
}n/a
function filterMutate(array, f) {
var outIndex = 0;
for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
var item = array_3[_i];
if (f(item)) {
array[outIndex] = item;
outIndex++;
}
}
array.length = outIndex;
}n/a
function find(array, predicate) {
for (var i = 0; i < array.length; i++) {
var value = array[i];
if (predicate(value, i)) {
return value;
}
}
return undefined;
}n/a
function findBestPatternMatch(values, getPattern, candidate) {
var matchedValue = undefined;
// use length of prefix as betterness criteria
var longestMatchPrefixLength = -1;
for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
var v = values_1[_i];
var pattern = getPattern(v);
if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
longestMatchPrefixLength = pattern.prefix.length;
matchedValue = v;
}
}
return matchedValue;
}n/a
function findChildOfKind(n, kind, sourceFile) {
return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; });
}n/a
function findConfigFile(searchPath, fileExists, configName) {
if (configName === void 0) { configName = "tsconfig.json"; }
while (true) {
var fileName = ts.combinePaths(searchPath, configName);
if (fileExists(fileName)) {
return fileName;
}
var parentPath = ts.getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
}
searchPath = parentPath;
}
return undefined;
}n/a
function findContainingList(node) {
// The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will
// be parented by the container of the SyntaxList, not the SyntaxList itself.
// In order to find the list item index, we first need to locate SyntaxList itself and then search
// for the position of the relevant node (or comma).
var syntaxList = ts.forEach(node.parent.getChildren(), function (c) {
// find syntax list that covers the span of the node
if (c.kind === 295 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) {
return c;
}
});
// Either we didn't find an appropriate list, or the list must contain us.
ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node));
return syntaxList;
}n/a
function findIndex(array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i], i)) {
return i;
}
}
return -1;
}n/a
function findListItemInfo(node) {
var list = findContainingList(node);
// It is possible at this point for syntaxList to be undefined, either if
// node.parent had no list child, or if none of its list children contained
// the span of node. If this happens, return undefined. The caller should
// handle this case.
if (!list) {
return undefined;
}
var children = list.getChildren();
var listItemIndex = ts.indexOf(children, node);
return {
listItemIndex: listItemIndex,
list: list
};
}n/a
function findMap(array, callback) {
for (var i = 0; i < array.length; i++) {
var result = callback(array[i], i);
if (result) {
return result;
}
}
Debug.fail();
}n/a
function findNextToken(previousToken, parent) {
return find(parent);
function find(n) {
if (isToken(n) && n.pos === previousToken.end) {
// this is token that starts at the end of previous token - return it
return n;
}
var children = n.getChildren();
for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
var child = children_2[_i];
var shouldDiveInChildNode =
// previous token is enclosed somewhere in the child
(child.pos <= previousToken.pos && child.end > previousToken.end) ||
// previous token ends exactly at the beginning of child
(child.pos === previousToken.end);
if (shouldDiveInChildNode && nodeHasTokens(child)) {
return find(child);
}
}
return undefined;
}
}n/a
function findPrecedingToken(position, sourceFile, startNode) {
return find(startNode || sourceFile);
function findRightmostToken(n) {
if (isToken(n)) {
return n;
}
var children = n.getChildren();
var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
return candidate && findRightmostToken(candidate);
}
function find(n) {
if (isToken(n)) {
return n;
}
var children = n.getChildren();
for (var i = 0; i < children.length; i++) {
var child = children[i];
// condition 'position < child.end' checks if child node end after the position
// in the example below this condition will be false for 'aaaa' and 'bbbb' and true for 'ccc'
// aaaa___bbbb___$__ccc
// after we found child node with end after the position we check if start of the node is after the position.
// if yes - then position is in the trivia and we need to look into the previous child to find the token in question
.
// if no - position is in the node itself so we should recurse in it.
// NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia).
// if this is the case - then we should assume that token in question is located in previous child.
if (position < child.end && (nodeHasTokens(child) || child.kind === 10 /* JsxText */)) {
var start = child.getStart(sourceFile);
var lookInPreviousChild = (start >= position) ||
(child.kind === 10 /* JsxText */ && start === child.end); // whitespace only JsxText
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i);
return candidate && findRightmostToken(candidate);
}
else {
// candidate should be in this node
return find(child);
}
}
}
ts.Debug.assert(startNode !== undefined || n.kind === 263 /* SourceFile */);
// Here we know that none of child token nodes embrace the position,
// the only known case is when position is at the end of the file.
// Try to find the rightmost token in the file without filtering.
// Namely we are skipping the check: 'position < node.end'
if (children.length) {
var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
return candidate && findRightmostToken(candidate);
}
}
/// finds last node that is considered as candidate for search (isCandidate(node) === true) starting from 'exclusiveStartPosition
'
function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) {
for (var i = exclusiveStartPosition - 1; i >= 0; i--) {
if (nodeHasTokens(children[i])) {
return children[i];
}
}
}
}n/a
function findTokenOnLeftOfPosition(file, position) {
// Ideally, getTokenAtPosition should return a token. However, it is currently
// broken, so we do a check to make sure the result was indeed a token.
var tokenAtPosition = getTokenAtPosition(file, position);
if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {
return tokenAtPosition;
}
return findPrecedingToken(position, file);
}n/a
function firstOrUndefined(array) {
return array && array.length > 0
? array[0]
: undefined;
}n/a
function flatMap(array, mapfn) {
var result;
if (array) {
result = [];
for (var i = 0; i < array.length; i++) {
var v = mapfn(array[i], i);
if (v) {
if (isArray(v)) {
addRange(result, v);
}
else {
result.push(v);
}
}
}
}
return result;
}n/a
function flatten(array) {
var result;
if (array) {
result = [];
for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
var v = array_4[_i];
if (v) {
if (isArray(v)) {
addRange(result, v);
}
else {
result.push(v);
}
}
}
}
return result;
}n/a
function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
var location = node;
var value;
if (ts.isDestructuringAssignment(node)) {
value = node.right;
while (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) {
if (ts.isDestructuringAssignment(value)) {
location = node = value;
value = node.right;
}
else {
return value;
}
}
}
var expressions;
var flattenContext = {
context: context,
level: level,
hoistTempVariables: true,
emitExpression: emitExpression,
emitBindingOrAssignment: emitBindingOrAssignment,
createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern,
createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern,
createArrayBindingOrAssignmentElement: makeAssignmentElement,
visitor: visitor
};
if (value) {
value = ts.visitNode(value, visitor, ts.isExpression);
if (needsValue) {
// If the right-hand value of the destructuring assignment needs to be preserved (as
// is the case when the destructuring assignment is part of a larger expression),
// then we need to cache the right-hand value.
//
// The source map location for the assignment should point to the entire binary
// expression.
value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
}
else if (ts.nodeIsSynthesized(node)) {
// Generally, the source map location for a destructuring assignment is the root
// expression.
//
// However, if the root expression is synthesized (as in the case
// of the initializer when transforming a ForOfStatement), then the source map
// location should point to the right-hand value of the expression.
location = value;
}
}
flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node
));
if (value && needsValue) {
if (!ts.some(expressions)) {
return value;
}
expressions.push(value);
}
return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression();
function emitExpression(expression) {
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */);
ts.aggregateTransformFlags(expression);
expressions = ts.append(expressions, expression);
}
function emitBindingOrAssignment(target, value, location, original) {
ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
var expression = createAssignmentCallback
? createAssignmentCallback(target, value, location)
: ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
expression.original = original;
emitExpression(expression);
}
}n/a
function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
var pendingExpressions;
var pendingDeclarations = [];
var declarations = [];
var flattenContext = {
context: context,
level: level,
hoistTempVariables: hoistTempVariables,
emitExpression: emitExpression,
emitBindingOrAssignment: emitBindingOrAssignment,
createArrayBindingOrAssignmentPattern: makeArrayBindingPattern,
createObjectBindingOrAssignmentPattern: makeObjectBindingPattern,
createArrayBindingOrAssignmentElement: makeBindingElement,
visitor: visitor
};
flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
if (pendingExpressions) {
var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
if (hoistTempVariables) {
var value = ts.inlineExpressions(pendingExpressions);
pendingExpressions = undefined;
emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
}
else {
context.hoistVariableDeclaration(temp);
var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations);
pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration
.value));
ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
pendingDeclaration.value = temp;
}
}
for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location
= _a.location, original = _a.original;
var variable = ts.createVariableDeclaration(name,
/*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
variable.original = original;
ts.setTextRange(variable, location);
if (ts.isIdentifier(name)) {
ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */);
}
ts.aggregateTransformFlags(variable);
declarations.push(variable);
}
return declarations;
function emitExpression(value) {
pendingExpressions = ts.append(pendingExpressions, value);
}
function emitBindingOrAssignment(target, value, location, original) {
ts.Debug.assertNode(target, ts.isBindingName);
if (pendingExpressions) {
value = ts.inlineExpressions(ts.append(pendingExpressions, value));
pendingExpressions = undefined;
}
pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original
: original });
}
}n/a
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
}
else {
var diagnosticChain = messageText;
var result = "";
var indent = 0;
while (diagnosticChain) {
if (indent) {
result += newLine;
for (var i = 0; i < indent; i++) {
result += " ";
}
}
result += diagnosticChain.messageText;
indent++;
diagnosticChain = diagnosticChain.next;
}
return result;
}
}n/a
function forEach(array, callback) {
if (array) {
for (var i = 0; i < array.length; i++) {
var result = callback(array[i], i);
if (result) {
return result;
}
}
}
return undefined;
}n/a
function forEachChild(node, cbNode, cbNodeArray) {
if (!node) {
return;
}
// The visitXXX functions could be written as local functions that close over the cbNode and cbNodeArray
// callback parameters, but that causes a closure allocation for each invocation with noticeable effects
// on performance.
var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode;
var cbNodes = cbNodeArray || cbNode;
switch (node.kind) {
case 142 /* QualifiedName */:
return visitNode(cbNode, node.left) ||
visitNode(cbNode, node.right);
case 144 /* TypeParameter */:
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.constraint) ||
visitNode(cbNode, node.expression);
case 260 /* ShorthandPropertyAssignment */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.equalsToken) ||
visitNode(cbNode, node.objectAssignmentInitializer);
case 261 /* SpreadAssignment */:
return visitNode(cbNode, node.expression);
case 145 /* Parameter */:
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
case 259 /* PropertyAssignment */:
case 225 /* VariableDeclaration */:
case 175 /* BindingElement */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.propertyName) ||
visitNode(cbNode, node.dotDotDotToken) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.type) ||
visitNode(cbNode, node.initializer);
case 159 /* FunctionType */:
case 160 /* ConstructorType */:
case 154 /* CallSignature */:
case 155 /* ConstructSignature */:
case 156 /* IndexSignature */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNodes(cbNodes, node.typeParameters) ||
visitNodes(cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 151 /* Constructor */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 185 /* FunctionExpression */:
case 227 /* FunctionDeclaration */:
case 186 /* ArrowFunction */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.asteriskToken) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.questionToken) ||
visitNodes(cbNodes, node.typeParameters) ||
visitNodes(cbNodes, node.parameters) ||
visitNode(cbNode, node.type) ||
visitNode(cbNode, node.equalsGreaterThanToken) ||
visitNode(cbNode, node.body);
case 158 /* TypeReference */:
return visitNode(cbNode, node.typeName) ||
visitNodes(cbNodes, node.typeArguments);
case 157 /* TypePredicate */:
return visitNode(cbNode, node.parameterName) ||
visitNode(cbNode, node.type);
case 161 /* TypeQuery */:
return visitNode(cbNode, node.exprName);
case 162 /* TypeLiteral */:
return visitNodes(cbNodes, node.members);
case 163 /* ArrayType */:
return visitNode(cbNode, node.elementType);
case 164 /* TupleType */:
return visitNodes(cbNodes, node.elementTypes);
case 165 /* UnionType */:
case 166 /* IntersectionType */:
return visitNodes(cbNodes, node.types);
c ...n/a
function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile
);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
if (sourceFiles.length) {
var jsFilePath = options.outFile || options.out;
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined;
action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts
.createBundle(sourceFiles), emitOnlyDtsFiles);
}
}
else {
for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
var sourceFile = sourceFiles_1[_i];
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options));
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath
(sourceFile, host) : undefined;
action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile
, emitOnlyDtsFiles);
}
}
}n/a
function forEachEntry(map, callback) {
var iterator = map.entries();
for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done
, _b) {
var key = pair[0], value = pair[1];
var result = callback(value, key);
if (result) {
return result;
}
}
return undefined;
var _b;
}n/a
function forEachKey(map, callback) {
var iterator = map.keys();
for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done,
_b) {
var result = callback(key);
if (result) {
return result;
}
}
return undefined;
var _b;
}n/a
function forEachLeadingCommentRange(text, pos, cb, state) {
return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
}n/a
function forEachReturnStatement(body, visitor) {
return traverse(body);
function traverse(node) {
switch (node.kind) {
case 218 /* ReturnStatement */:
return visitor(node);
case 234 /* CaseBlock */:
case 206 /* Block */:
case 210 /* IfStatement */:
case 211 /* DoStatement */:
case 212 /* WhileStatement */:
case 213 /* ForStatement */:
case 214 /* ForInStatement */:
case 215 /* ForOfStatement */:
case 219 /* WithStatement */:
case 220 /* SwitchStatement */:
case 255 /* CaseClause */:
case 256 /* DefaultClause */:
case 221 /* LabeledStatement */:
case 223 /* TryStatement */:
case 258 /* CatchClause */:
return ts.forEachChild(node, traverse);
}
}
}n/a
function forEachTrailingCommentRange(text, pos, cb, state) {
return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
}n/a
function forEachYieldExpression(body, visitor) {
return traverse(body);
function traverse(node) {
switch (node.kind) {
case 196 /* YieldExpression */:
visitor(node);
var operand = node.expression;
if (operand) {
traverse(operand);
}
case 231 /* EnumDeclaration */:
case 229 /* InterfaceDeclaration */:
case 232 /* ModuleDeclaration */:
case 230 /* TypeAliasDeclaration */:
case 228 /* ClassDeclaration */:
case 198 /* ClassExpression */:
// These are not allowed inside a generator now, but eventually they may be allowed
// as local types. Regardless, any yield statements contained within them should be
// skipped in this traversal.
return;
default:
if (isFunctionLike(node)) {
var name = node.name;
if (name && name.kind === 143 /* ComputedPropertyName */) {
// Note that we will not include methods/accessors of a class because they would require
// first descending into the class. This is by design.
traverse(name.expression);
return;
}
}
else if (!isPartOfTypeNode(node)) {
// This is the general case, which should include mostly expressions and statements.
// Also includes NodeArrays.
ts.forEachChild(node, traverse);
}
}
}
}n/a
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character
;
var fileName = diagnostic.file.fileName;
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host
.getCanonicalFileName(fileName); });
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine
()) + host.getNewLine();
}
return output;
}n/a
function formatMessage(_dummy, message) {
var text = getLocaleSpecificMessage(message);
if (arguments.length > 2) {
text = formatStringFromArgs(text, arguments, 2);
}
return text;
}n/a
function formatStringFromArgs(text, args, baseIndex) {
baseIndex = baseIndex || 0;
return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; });
}n/a
function formatSyntaxKind(kind) {
var syntaxKindEnum = ts.SyntaxKind;
if (syntaxKindEnum) {
var cached = syntaxKindCache[kind];
if (cached !== undefined) {
return cached;
}
for (var name in syntaxKindEnum) {
if (syntaxKindEnum[name] === kind) {
var result = kind + " (" + name + ")";
syntaxKindCache[kind] = result;
return result;
}
}
}
else {
return kind.toString();
}
}n/a
function FormattingContext(sourceFile, formattingRequestKind) {
this.sourceFile = sourceFile;
this.formattingRequestKind = formattingRequestKind;
}n/a
function Rule(Descriptor, Operation, Flag) {
if (Flag === void 0) { Flag = 0 /* None */; }
this.Descriptor = Descriptor;
this.Operation = Operation;
this.Flag = Flag;
}n/a
function RuleDescriptor(LeftTokenRange, RightTokenRange) {
this.LeftTokenRange = LeftTokenRange;
this.RightTokenRange = RightTokenRange;
}n/a
function RuleOperation(Context, Action) {
this.Context = Context;
this.Action = Action;
}n/a
function RuleOperationContext() {
var funcs = [];
for (var _i = 0; _i < arguments.length; _i++) {
funcs[_i] = arguments[_i];
}
this.customContextChecks = funcs;
}n/a
function Rules() {
///
/// Common Rules
///
// Leave comments alone
this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting
.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1 /* Ignore */));
this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2 /* SingleLineCommentTrivia */, formatting
.Shared.TokenRange.Any), formatting.RuleOperation.create1(1 /* Ignore */));
// Space after keyword but not before ; or : or ?
this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /*
SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /*
Delete */));
this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* ColonToken
*/), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext
), 8 /* Delete */));
this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /*
QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules
.IsNotBinaryOpContext), 8 /* Delete */));
this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* ColonToken */, formatting.Shared.TokenRange
.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext
), 2 /* Space */));
this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken
*/, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext
, Rules.IsConditionalOperatorContext), 2 /* Space */));
this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken */, formatting.Shared
.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /*
Delete */));
this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* SemicolonToken */, formatting.Shared.
TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /*
Space */));
// Space after }.
this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared
.TokenRange.FromRange(0 /* FirstToken */, 141 /* LastToken */, [19 /* CloseParenToken */])), formatting.RuleOperation.create2(new
formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */));
// Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace
rule not applied
this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 81 /* ElseKeyword
*/), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 105 /*
WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /*
Space */));
this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared
.TokenRange.FromTokens([21 /* CloseBracketToken */, 25 /* CommaToken */, 24 /* SemicolonToken */])), formatting.RuleOperation.create2
(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
// No space for dot
this.NoSpaceBeforeDot = ne ...n/a
function RulesBucket() {
this.rules = [];
}n/a
function RulesBucketConstructionState() {
//// The Rules list contains all the inserted rules into a rulebucket in the following order:
//// 1- Ignore rules with specific token combination
//// 2- Ignore rules with any token combination
//// 3- Context rules with specific token combination
//// 4- Context rules with any token combination
//// 5- Non-context rules with specific token combination
//// 6- Non-context rules with any token combination
////
//// The member rulesInsertionIndexBitmap is used to describe the number of rules
//// in each sub-bucket (above) hence can be used to know the index of where to insert
//// the next rule. It's a bitmap which contains 6 different sections each is given 5 bits.
////
//// Example:
//// In order to insert a rule to the end of sub-bucket (3), we get the index by adding
//// the values in the bitmap segments 3rd, 2nd, and 1st.
this.rulesInsertionIndexBitmap = 0;
}n/a
function RulesMap() {
this.map = [];
this.mapRowLength = 0;
}n/a
function RulesProvider() {
this.globalRules = new formatting.Rules();
}n/a
function generateTSConfig(options, fileNames) {
var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
var configurations = {
compilerOptions: serializeCompilerOptions(compilerOptions)
};
if (fileNames && fileNames.length) {
// only set the files property if we have at least one file
configurations.files = fileNames;
}
return configurations;
function getCustomTypeMapOfCommandLineOption(optionDefinition) {
if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") {
// this is of a type CommandLineOptionOfPrimitiveType
return undefined;
}
else if (optionDefinition.type === "list") {
return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
}
else {
return optionDefinition.type;
}
}
function getNameOfCompilerOptionValue(value, customTypeMap) {
// There is a typeMap associated with this command-line option so use it to map value back to its name
return ts.forEachEntry(customTypeMap, function (mapValue, key) {
if (mapValue === value) {
return key;
}
});
}
function serializeCompilerOptions(options) {
var result = {};
var optionsNameMap = getOptionNameMap().optionNameMap;
for (var name in options) {
if (ts.hasProperty(options, name)) {
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
switch (name) {
case "init":
case "watch":
case "version":
case "help":
case "project":
break;
default:
var value = options[name];
var optionDefinition = optionsNameMap.get(name.toLowerCase());
if (optionDefinition) {
var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition);
if (!customTypeMap) {
// There is no map associated with this compiler option then use the value as-is
// This is the case if the value is expect to be string, number, boolean or list of string
result[name] = value;
}
else {
if (optionDefinition.type === "list") {
var convertedValue = [];
for (var _i = 0, _a = value; _i < _a.length; _i++) {
var element = _a[_i];
convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap));
}
result[name] = convertedValue;
}
else {
// There is a typeMap associated with this command-line option so use it to map value back to
its name
result[name] = getNameOfCompilerOptionValue(value, customTypeMap);
}
}
}
break;
}
}
}
return result;
}
}n/a
function getAllAccessorDeclarations(declarations, accessor) {
var firstAccessor;
var secondAccessor;
var getAccessor;
var setAccessor;
if (hasDynamicName(accessor)) {
firstAccessor = accessor;
if (accessor.kind === 152 /* GetAccessor */) {
getAccessor = accessor;
}
else if (accessor.kind === 153 /* SetAccessor */) {
setAccessor = accessor;
}
else {
ts.Debug.fail("Accessor has wrong kind");
}
}
else {
ts.forEach(declarations, function (member) {
if ((member.kind === 152 /* GetAccessor */ || member.kind === 153 /* SetAccessor */)
&& hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
var memberName = getPropertyNameForPropertyNameNode(member.name);
var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
if (memberName === accessorName) {
if (!firstAccessor) {
firstAccessor = member;
}
else if (!secondAccessor) {
secondAccessor = member;
}
if (member.kind === 152 /* GetAccessor */ && !getAccessor) {
getAccessor = member;
}
if (member.kind === 153 /* SetAccessor */ && !setAccessor) {
setAccessor = member;
}
}
}
});
}
return {
firstAccessor: firstAccessor,
secondAccessor: secondAccessor,
getAccessor: getAccessor,
setAccessor: setAccessor
};
}n/a
function getAncestor(node, kind) {
while (node) {
if (node.kind === kind) {
return node;
}
node = node.parent;
}
return undefined;
}n/a
function getAssignmentTargetKind(node) {
var parent = node.parent;
while (true) {
switch (parent.kind) {
case 193 /* BinaryExpression */:
var binaryOperator = parent.operatorToken.kind;
return isAssignmentOperator(binaryOperator) && parent.left === node ?
binaryOperator === 57 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
0 /* None */;
case 191 /* PrefixUnaryExpression */:
case 192 /* PostfixUnaryExpression */:
var unaryOperator = parent.operator;
return unaryOperator === 42 /* PlusPlusToken */ || unaryOperator === 43 /* MinusMinusToken */ ? 2 /* Compound */ :
0 /* None */;
case 214 /* ForInStatement */:
case 215 /* ForOfStatement */:
return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
case 184 /* ParenthesizedExpression */:
case 176 /* ArrayLiteralExpression */:
case 197 /* SpreadElement */:
node = parent;
break;
case 260 /* ShorthandPropertyAssignment */:
if (parent.name !== node) {
return 0 /* None */;
}
node = parent.parent;
break;
case 259 /* PropertyAssignment */:
if (parent.name === node) {
return 0 /* None */;
}
node = parent.parent;
break;
default:
return 0 /* None */;
}
parent = node.parent;
}
}n/a
function getAutomaticTypeDirectiveNames(options, host) {
// Use explicit type list from tsconfig.json
if (options.types) {
return options.types;
}
// Walk the primary type lookup locations
var result = [];
if (host.directoryExists && host.getDirectories) {
var typeRoots = getEffectiveTypeRoots(options, host);
if (typeRoots) {
for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
var root = typeRoots_1[_i];
if (host.directoryExists(root)) {
for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
var typeDirectivePath = _b[_a];
var normalized = ts.normalizePath(typeDirectivePath);
var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized));
// tslint:disable-next-line:no-null-keyword
var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings ===
null;
if (!isNotNeededPackage) {
// Return just the type directive names
result.push(ts.getBaseFileName(normalized));
}
}
}
}
}
}
return result;
}n/a
function getBaseFileName(path) {
if (path === undefined) {
return undefined;
}
var i = path.lastIndexOf(ts.directorySeparator);
return i < 0 ? path : path.substring(i + 1);
}n/a
function getClassExtendsHeritageClauseElement(node) {
var heritageClause = getHeritageClause(node.heritageClauses, 84 /* ExtendsKeyword */);
return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
}n/a
function getClassImplementsHeritageClauseElements(node) {
var heritageClause = getHeritageClause(node.heritageClauses, 107 /* ImplementsKeyword */);
return heritageClause ? heritageClause.types : undefined;
}n/a
function getCombinedModifierFlags(node) {
node = walkUpBindingElementsAndPatterns(node);
var flags = ts.getModifierFlags(node);
if (node.kind === 225 /* VariableDeclaration */) {
node = node.parent;
}
if (node && node.kind === 226 /* VariableDeclarationList */) {
flags |= ts.getModifierFlags(node);
node = node.parent;
}
if (node && node.kind === 207 /* VariableStatement */) {
flags |= ts.getModifierFlags(node);
}
return flags;
}n/a
function getCombinedNodeFlags(node) {
node = walkUpBindingElementsAndPatterns(node);
var flags = node.flags;
if (node.kind === 225 /* VariableDeclaration */) {
node = node.parent;
}
if (node && node.kind === 226 /* VariableDeclarationList */) {
flags |= node.flags;
node = node.parent;
}
if (node && node.kind === 207 /* VariableStatement */) {
flags |= node.flags;
}
return flags;
}n/a
function getCommentRange(node) {
var emitNode = node.emitNode;
return (emitNode && emitNode.commentRange) || node;
}n/a
function getCommentsFromJSDoc(node) {
return ts.map(getJSDocs(node), function (doc) { return doc.comment; });
}n/a
function getConstantValue(node) {
var emitNode = node.emitNode;
return emitNode && emitNode.constantValue;
}n/a
function getContainerNode(node) {
while (true) {
node = node.parent;
if (!node) {
return undefined;
}
switch (node.kind) {
case 263 /* SourceFile */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 228 /* ClassDeclaration */:
case 229 /* InterfaceDeclaration */:
case 231 /* EnumDeclaration */:
case 232 /* ModuleDeclaration */:
return node;
}
}
}n/a
function getContainingClass(node) {
while (true) {
node = node.parent;
if (!node || isClassLike(node)) {
return node;
}
}
}n/a
function getContainingFunction(node) {
while (true) {
node = node.parent;
if (!node || isFunctionLike(node)) {
return node;
}
}
}n/a
function getDeclarationDiagnostics(host, resolver, targetSourceFile) {
var declarationDiagnostics = ts.createDiagnosticCollection();
ts.forEachEmittedFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile);
return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);
function getDeclarationDiagnosticsFromFile(_a, sourceFileOrBundle) {
var declarationFilePath = _a.declarationFilePath;
emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, /*emitOnlyDtsFiles*/ false
);
}
}n/a
function getDeclarationEmitOutputFilePath(sourceFile, host) {
var options = host.getCompilerOptions();
var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
var path = outputDir
? getSourceFilePathInNewDir(sourceFile, host, outputDir)
: sourceFile.fileName;
return ts.removeFileExtension(path) + ".d.ts";
}n/a
function getDeclarationName(node, allowComments, allowSourceMaps) {
return getName(node, allowComments, allowSourceMaps);
}n/a
function getDeclarationOfKind(symbol, kind) {
var declarations = symbol.declarations;
if (declarations) {
for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
var declaration = declarations_1[_i];
if (declaration.kind === kind) {
return declaration;
}
}
}
return undefined;
}n/a
function getDeclaredName(typeChecker, symbol, location) {
// If this is an export or import specifier it could have been renamed using the 'as' syntax.
// If so we want to search for whatever is under the cursor.
if (isImportOrExportSpecifierName(location)) {
return location.getText();
}
else if (ts.isStringOrNumericLiteral(location) &&
location.parent.kind === 143 /* ComputedPropertyName */) {
return location.text;
}
// Try to get the local symbol if we're dealing with an 'export default'
// since that symbol has the "true" name.
var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol);
var name = typeChecker.symbolToString(localExportDefaultSymbol || symbol);
return name;
}n/a
function getDefaultCompilerOptions() {
// Always default to "ScriptTarget.ES5" for the language service
return {
target: 1 /* ES5 */,
jsx: 1 /* Preserve */
};
}n/a
function getDefaultLibFileName(options) {
switch (options.target) {
case 5 /* ESNext */:
case 4 /* ES2017 */:
return "lib.es2017.d.ts";
case 3 /* ES2016 */:
return "lib.es2016.d.ts";
case 2 /* ES2015 */:
return "lib.es6.d.ts";
default:
return "lib.d.ts";
}
}n/a
function getDefaultLibFilePath(options) {
// Check __dirname is defined and that we are on a node.js system.
if (typeof __dirname !== "undefined") {
return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options);
}
throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. ");
}n/a
function getDirectoryPath(path) {
return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator)));
}n/a
function getEffectiveTypeRoots(options, host) {
if (options.typeRoots) {
return options.typeRoots;
}
var currentDirectory;
if (options.configFilePath) {
currentDirectory = ts.getDirectoryPath(options.configFilePath);
}
else if (host.getCurrentDirectory) {
currentDirectory = host.getCurrentDirectory();
}
if (currentDirectory !== undefined) {
return getDefaultTypeRoots(currentDirectory, host);
}
}n/a
function getElementsOfBindingOrAssignmentPattern(name) {
switch (name.kind) {
case 173 /* ObjectBindingPattern */:
case 174 /* ArrayBindingPattern */:
case 176 /* ArrayLiteralExpression */:
// `a` in `{a}`
// `a` in `[a]`
return name.elements;
case 177 /* ObjectLiteralExpression */:
// `a` in `{a}`
return name.properties;
}
}n/a
function getEmitFlags(node) {
var emitNode = node.emitNode;
return emitNode && emitNode.flags;
}n/a
function getEmitHelpers(node) {
var emitNode = node.emitNode;
return emitNode && emitNode.helpers;
}n/a
function getEmitModuleKind(compilerOptions) {
return typeof compilerOptions.module === "number" ?
compilerOptions.module :
getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
}n/a
function getEmitModuleResolutionKind(compilerOptions) {
var moduleResolution = compilerOptions.moduleResolution;
if (moduleResolution === undefined) {
moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind
.Classic;
}
return moduleResolution;
}n/a
function getEmitScriptTarget(compilerOptions) {
return compilerOptions.target || 0 /* ES3 */;
}n/a
function getEnclosingBlockScopeContainer(node) {
var current = node.parent;
while (current) {
if (isBlockScope(current, current.parent)) {
return current;
}
current = current.parent;
}
}n/a
function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
var result = [];
processNode(sourceFile);
return { spans: result, endOfLineState: 0 /* None */ };
function pushClassification(start, length, type) {
result.push(start);
result.push(length);
result.push(type);
}
function classifySymbol(symbol, meaningAtPosition) {
var flags = symbol.getFlags();
if ((flags & 788448 /* Classifiable */) === 0 /* None */) {
return;
}
if (flags & 32 /* Class */) {
return 11 /* className */;
}
else if (flags & 384 /* Enum */) {
return 12 /* enumName */;
}
else if (flags & 524288 /* TypeAlias */) {
return 16 /* typeAliasName */;
}
else if (meaningAtPosition & 2 /* Type */) {
if (flags & 64 /* Interface */) {
return 13 /* interfaceName */;
}
else if (flags & 262144 /* TypeParameter */) {
return 15 /* typeParameterName */;
}
}
else if (flags & 1536 /* Module */) {
// Only classify a module as such if
// - It appears in a namespace context.
// - There exists a module declaration which actually impacts the value side.
if (meaningAtPosition & 4 /* Namespace */ ||
(meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol))) {
return 14 /* moduleName */;
}
}
return undefined;
/**
* Returns true if there exists a module that introduces entities on the value side.
*/
function hasValueSideModule(symbol) {
return ts.forEach(symbol.declarations, function (declaration) {
return declaration.kind === 232 /* ModuleDeclaration */ &&
ts.getModuleInstanceState(declaration) === 1 /* Instantiated */;
});
}
}
function processNode(node) {
// Only walk into nodes that intersect the requested span.
if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) {
var kind = node.kind;
checkForClassificationCancellation(cancellationToken, kind);
if (kind === 70 /* Identifier */ && !ts.nodeIsMissing(node)) {
var identifier = node;
// Only bother calling into the typechecker if this is an identifier that
// could possibly resolve to a type name. This makes classification run
// in a third of the time it would normally take.
if (classifiableNames.get(identifier.text)) {
var symbol = typeChecker.getSymbolAtLocation(node);
if (symbol) {
var type = classifySymbol(symbol, ts.getMeaningFromLocation(node));
if (type) {
pushClassification(node.getStart(), node.getWidth(), type);
}
}
}
}
ts.forEachChild(node, processNode);
}
}
}n/a
function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) {
var spanStart = span.start;
var spanLength = span.length;
// Make a scanner we can get trivia from.
var triviaScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
var mergeConflictScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text
);
var result = [];
processElement(sourceFile);
return { spans: result, endOfLineState: 0 /* None */ };
function pushClassification(start, length, type) {
result.push(start);
result.push(length);
result.push(type);
}
function classifyLeadingTriviaAndGetTokenStart(token) {
triviaScanner.setTextPos(token.pos);
while (true) {
var start = triviaScanner.getTextPos();
// only bother scanning if we have something that could be trivia.
if (!ts.couldStartTrivia(sourceFile.text, start)) {
return start;
}
var kind = triviaScanner.scan();
var end = triviaScanner.getTextPos();
var width = end - start;
// The moment we get something that isn't trivia, then stop processing.
if (!ts.isTrivia(kind)) {
return start;
}
// Don't bother with newlines/whitespace.
if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) {
continue;
}
// Only bother with the trivia if it at least intersects the span of interest.
if (ts.isComment(kind)) {
classifyComment(token, kind, start, width);
// Classifying a comment might cause us to reuse the trivia scanner
// (because of jsdoc comments). So after we classify the comment make
// sure we set the scanner position back to where it needs to be.
triviaScanner.setTextPos(end);
continue;
}
if (kind === 7 /* ConflictMarkerTrivia */) {
var text = sourceFile.text;
var ch = text.charCodeAt(start);
// for the <<<<<<< and >>>>>>> markers, we just add them in as comments
// in the classification stream.
if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
pushClassification(start, width, 1 /* comment */);
continue;
}
// for the ======== add a comment for the first line, and then lex all
// subsequent lines up until the end of the conflict marker.
ts.Debug.assert(ch === 61 /* equals */);
classifyDisabledMergeCode(text, start, end);
}
}
}
function classifyComment(token, kind, start, width) {
if (kind === 3 /* MultiLineCommentTrivia */) {
// See if this is a doc comment. If so, we'll classify certain portions of it
// specially.
var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width);
if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) {
docCommentAndDiagnostics.jsDoc.parent = token;
classifyJSDocComment(docCommentAndDiagnostics.jsDoc);
return;
}
}
// Simple comment. Just add as is.
pushCommentRange(start, width);
}
function pushCommentRange(start, width) {
pushClassification(start, width, 1 /* comment */);
}
function classifyJSDocComment(docComment) {
var pos = docComment.pos;
if (docComment.tags) {
for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) {
var tag = _a[_i];
// As we walk through each tag, classify the portion of text from the end of
// the last tag (or the start of the entire doc comment) as 'comment'.
i ...n/a
function getEndLinePosition(line, sourceFile) {
ts.Debug.assert(line >= 0);
var lineStarts = ts.getLineStarts(sourceFile);
var lineIndex = line;
var sourceText = sourceFile.text;
if (lineIndex + 1 === lineStarts.length) {
// last line - return EOF
return sourceText.length - 1;
}
else {
// current line start
var start = lineStarts[lineIndex];
// take the start position of the next line - 1 = it should be some line break
var pos = lineStarts[lineIndex + 1] - 1;
ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
// walk backwards skipping line breaks, stop the the beginning of current line.
// i.e:
// <some text>
// $ <- end of line for this position should match the start position
while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
pos--;
}
return pos;
}
}n/a
function getEntityNameFromTypeNode(node) {
switch (node.kind) {
case 158 /* TypeReference */:
case 275 /* JSDocTypeReference */:
return node.typeName;
case 200 /* ExpressionWithTypeArguments */:
return isEntityNameExpression(node.expression)
? node.expression
: undefined;
case 70 /* Identifier */:
case 142 /* QualifiedName */:
return node;
}
return undefined;
}n/a
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
case 263 /* SourceFile */:
var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
if (pos_1 === sourceFile.text.length) {
// file is empty - return span for the beginning of the file
return ts.createTextSpan(0, 0);
}
return getSpanOfTokenAtPosition(sourceFile, pos_1);
// This list is a work in progress. Add missing node kinds to improve their error
// spans.
case 225 /* VariableDeclaration */:
case 175 /* BindingElement */:
case 228 /* ClassDeclaration */:
case 198 /* ClassExpression */:
case 229 /* InterfaceDeclaration */:
case 232 /* ModuleDeclaration */:
case 231 /* EnumDeclaration */:
case 262 /* EnumMember */:
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
case 150 /* MethodDeclaration */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 230 /* TypeAliasDeclaration */:
errorNode = node.name;
break;
case 186 /* ArrowFunction */:
return getErrorSpanForArrowFunction(sourceFile, node);
}
if (errorNode === undefined) {
// If we don't have a better node, then just set the error on the first token of
// construct.
return getSpanOfTokenAtPosition(sourceFile, node.pos);
}
var pos = nodeIsMissing(errorNode)
? errorNode.pos
: ts.skipTrivia(sourceFile.text, errorNode.pos);
return ts.createTextSpanFromBounds(pos, errorNode.end);
}n/a
function getExportName(node, allowComments, allowSourceMaps) {
return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
}n/a
function getExpressionAssociativity(expression) {
var operator = getOperator(expression);
var hasArguments = expression.kind === 181 /* NewExpression */ && expression.arguments !== undefined;
return getOperatorAssociativity(expression.kind, operator, hasArguments);
}n/a
function getExpressionPrecedence(expression) {
var operator = getOperator(expression);
var hasArguments = expression.kind === 181 /* NewExpression */ && expression.arguments !== undefined;
return getOperatorPrecedence(expression.kind, operator, hasArguments);
}n/a
function getExtensionPriority(path, supportedExtensions) {
for (var i = supportedExtensions.length - 1; i >= 0; i--) {
if (fileExtensionIs(path, supportedExtensions[i])) {
return adjustExtensionPriority(i, supportedExtensions);
}
}
// If its not in the list of supported extensions, this is likely a
// TypeScript file with a non-ts extension
return 0 /* Highest */;
}n/a
function getExternalHelpersModuleName(node) {
var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
var emitNode = parseNode && parseNode.emitNode;
return emitNode && emitNode.externalHelpersModuleName;
}n/a
function getExternalModuleImportEqualsDeclarationExpression(node) {
ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
return node.moduleReference.expression;
}n/a
function getExternalModuleName(node) {
if (node.kind === 237 /* ImportDeclaration */) {
return node.moduleSpecifier;
}
if (node.kind === 236 /* ImportEqualsDeclaration */) {
var reference = node.moduleReference;
if (reference.kind === 247 /* ExternalModuleReference */) {
return reference.expression;
}
}
if (node.kind === 243 /* ExportDeclaration */) {
return node.moduleSpecifier;
}
if (node.kind === 232 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) {
return node.name;
}
}n/a
function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
var file = resolver.getExternalModuleFileFromDeclaration(declaration);
if (!file || isDeclarationFile(file)) {
return undefined;
}
return getResolvedExternalModuleName(host, file);
}n/a
function getExternalModuleNameFromPath(host, fileName) {
var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false
);
return ts.removeFileExtension(relativePath);
}n/a
function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) {
var moduleName = ts.getExternalModuleName(importNode);
if (moduleName.kind === 9 /* StringLiteral */) {
return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
|| tryRenameExternalModule(moduleName, sourceFile)
|| ts.getSynthesizedClone(moduleName);
}
return undefined;
}n/a
function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
if (ns && ts.hasModifier(node, 1 /* Export */)) {
return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
}
return getExportName(node, allowComments, allowSourceMaps);
}n/a
function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
path = normalizePath(path);
currentDirectory = normalizePath(currentDirectory);
var absolutePath = combinePaths(currentDirectory, path);
return {
includeFilePatterns: map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return
"^" + pattern + "$"; }),
includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
};
}n/a
function getFileReferenceFromReferencePath(comment, commentRange) {
var simpleReferenceRegEx = /^\/\/\/\s*<reference\s+/gim;
var isNoDefaultLibRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/gim;
if (simpleReferenceRegEx.test(comment)) {
if (isNoDefaultLibRegEx.test(comment)) {
return {
isNoDefaultLib: true
};
}
else {
var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment);
var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment);
if (refMatchResult || refLibResult) {
var start = commentRange.pos;
var end = commentRange.end;
return {
fileReference: {
pos: start,
end: end,
fileName: (refMatchResult || refLibResult)[3]
},
isNoDefaultLib: false,
isTypeReferenceDirective: !!refLibResult
};
}
return {
diagnosticMessage: ts.Diagnostics.Invalid_reference_directive_syntax,
isNoDefaultLib: false
};
}
}
return undefined;
}n/a
function getFirstConstructorWithBody(node) {
return ts.forEach(node.members, function (member) {
if (member.kind === 151 /* Constructor */ && nodeIsPresent(member.body)) {
return member;
}
});
}n/a
function getFullWidth(node) {
return node.end - node.pos;
}n/a
function getGeneratedNameForNode(node) {
var name = createIdentifier("");
name.autoGenerateKind = 4 /* Node */;
name.autoGenerateId = nextAutoGenerateId;
name.original = node;
nextAutoGenerateId++;
return name;
}n/a
function getHelperName(name) {
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}n/a
function getHeritageClause(clauses, kind) {
if (clauses) {
for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
var clause = clauses_1[_i];
if (clause.token === kind) {
return clause;
}
}
}
return undefined;
}n/a
function getImmediatelyInvokedFunctionExpression(func) {
if (func.kind === 185 /* FunctionExpression */ || func.kind === 186 /* ArrowFunction */) {
var prev = func;
var parent = func.parent;
while (parent.kind === 184 /* ParenthesizedExpression */) {
prev = parent;
parent = parent.parent;
}
if (parent.kind === 180 /* CallExpression */ && parent.expression === prev) {
return parent;
}
}
}n/a
function getIndentSize() {
return indentStrings[1].length;
}n/a
function getIndentString(level) {
if (indentStrings[level] === undefined) {
indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
}
return indentStrings[level];
}n/a
function getInitializedVariables(node) {
return ts.filter(node.declarations, isInitializedVariable);
}n/a
function getInitializerOfBindingOrAssignmentElement(bindingElement) {
if (ts.isDeclarationBindingElement(bindingElement)) {
// `1` in `let { a = 1 } = ...`
// `1` in `let { a: b = 1 } = ...`
// `1` in `let { a: {b} = 1 } = ...`
// `1` in `let { a: [b] = 1 } = ...`
// `1` in `let [a = 1] = ...`
// `1` in `let [{a} = 1] = ...`
// `1` in `let [[a] = 1] = ...`
return bindingElement.initializer;
}
if (ts.isPropertyAssignment(bindingElement)) {
// `1` in `({ a: b = 1 } = ...)`
// `1` in `({ a: {b} = 1 } = ...)`
// `1` in `({ a: [b] = 1 } = ...)`
return ts.isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true)
? bindingElement.initializer.right
: undefined;
}
if (ts.isShorthandPropertyAssignment(bindingElement)) {
// `1` in `({ a = 1 } = ...)`
return bindingElement.objectAssignmentInitializer;
}
if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
// `1` in `[a = 1] = ...`
// `1` in `[{a} = 1] = ...`
// `1` in `[[a] = 1] = ...`
return bindingElement.right;
}
if (ts.isSpreadExpression(bindingElement)) {
// Recovery consistent with existing emit.
return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
}
}n/a
function getInterfaceBaseTypeNodes(node) {
var heritageClause = getHeritageClause(node.heritageClauses, 84 /* ExtendsKeyword */);
return heritageClause ? heritageClause.types : undefined;
}n/a
function getInvokedExpression(node) {
if (node.kind === 182 /* TaggedTemplateExpression */) {
return node.tag;
}
// Will either be a CallExpression, NewExpression, or Decorator.
return node.expression;
}n/a
function getJSDocAugmentsTag(node) {
return getFirstJSDocTag(node, 283 /* JSDocAugmentsTag */);
}n/a
function getJSDocCommentRanges(node, text) {
var commentRanges = (node.kind === 145 /* Parameter */ ||
node.kind === 144 /* TypeParameter */ ||
node.kind === 185 /* FunctionExpression */ ||
node.kind === 186 /* ArrowFunction */) ?
ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
getLeadingCommentRangesOfNodeFromText(node, text);
// True if the comment starts with '/**' but not if it is '/**/'
return ts.filter(commentRanges, function (comment) {
return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
});
}n/a
function getJSDocParameterTags(param) {
if (!isParameter(param)) {
return undefined;
}
var func = param.parent;
var tags = getJSDocTags(func, 284 /* JSDocParameterTag */);
if (!param.name) {
// this is an anonymous jsdoc param from a `function(type1, type2): type3` specification
var i = func.parameters.indexOf(param);
var paramTags = ts.filter(tags, function (tag) { return tag.kind === 284 /* JSDocParameterTag */; });
if (paramTags && 0 <= i && i < paramTags.length) {
return [paramTags[i]];
}
}
else if (param.name.kind === 70 /* Identifier */) {
var name_1 = param.name.text;
return ts.filter(tags, function (tag) { return tag.kind === 284 /* JSDocParameterTag */ && tag.parameterName.text === name_1
; });
}
else {
// TODO: it's a destructured parameter, so it should look up an "object type" series of multiple lines
// But multi-line object types aren't supported yet either
return undefined;
}
}n/a
function getJSDocReturnTag(node) {
return getFirstJSDocTag(node, 285 /* JSDocReturnTag */);
}n/a
function getJSDocTemplateTag(node) {
return getFirstJSDocTag(node, 287 /* JSDocTemplateTag */);
}n/a
function getJSDocType(node) {
var tag = getFirstJSDocTag(node, 286 /* JSDocTypeTag */);
if (!tag && node.kind === 145 /* Parameter */) {
var paramTags = getJSDocParameterTags(node);
if (paramTags) {
tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; });
}
}
return tag && tag.typeExpression && tag.typeExpression.type;
}n/a
function getJsDocTagAtPosition(sourceFile, position) {
var node = ts.getTokenAtPosition(sourceFile, position);
if (isToken(node)) {
switch (node.kind) {
case 103 /* VarKeyword */:
case 109 /* LetKeyword */:
case 75 /* ConstKeyword */:
// if the current token is var, let or const, skip the VariableDeclarationList
node = node.parent === undefined ? undefined : node.parent.parent;
break;
default:
node = node.parent;
break;
}
}
if (node) {
if (node.jsDoc) {
for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
var jsDoc = _a[_i];
if (jsDoc.tags) {
for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) {
var tag = _c[_b];
if (tag.pos <= position && position <= tag.end) {
return tag;
}
}
}
}
}
}
return undefined;
}n/a
function getLeadingCommentRanges(text, pos) {
return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined);
}n/a
function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
}n/a
function getLeadingCommentRangesOfNodeFromText(node, text) {
return ts.getLeadingCommentRanges(text, node.pos);
}n/a
function getLineAndCharacterOfPosition(sourceFile, position) {
return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
}n/a
function getLineOfLocalPosition(currentSourceFile, pos) {
return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line;
}n/a
function getLineOfLocalPositionFromLineMap(lineMap, pos) {
return ts.computeLineAndCharacterOfPosition(lineMap, pos).line;
}n/a
function getLineStartPositionForPosition(position, sourceFile) {
var lineStarts = sourceFile.getLineStarts();
var line = sourceFile.getLineAndCharacterOfPosition(position).line;
return lineStarts[line];
}n/a
function getLineStarts(sourceFile) {
return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
}n/a
function getLiteralText(node, sourceFile, languageVersion) {
// Any template literal or string literal with an extended escape
// (e.g. "\u{0067}") will need to be downleveled as a escaped string literal.
if (languageVersion < 2 /* ES2015 */ && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
return getQuotedEscapedLiteralText('"', node.text, '"');
}
// If we don't need to downlevel and we can reach the original source text using
// the node's parent reference, then simply get the text as it was originally written.
if (!nodeIsSynthesized(node) && node.parent) {
var text = getSourceTextOfNodeFromSourceFile(sourceFile, node);
if (languageVersion < 2 /* ES2015 */ && isBinaryOrOctalIntegerLiteral(node, text)) {
return node.text;
}
return text;
}
// If we can't reach the original source text, use the canonical form if it's a number,
// or an escaped quoted form of the original text if it's string-like.
switch (node.kind) {
case 9 /* StringLiteral */:
return getQuotedEscapedLiteralText('"', node.text, '"');
case 12 /* NoSubstitutionTemplateLiteral */:
return getQuotedEscapedLiteralText("`", node.text, "`");
case 13 /* TemplateHead */:
return getQuotedEscapedLiteralText("`", node.text, "${");
case 14 /* TemplateMiddle */:
return getQuotedEscapedLiteralText("}", node.text, "${");
case 15 /* TemplateTail */:
return getQuotedEscapedLiteralText("}", node.text, "`");
case 8 /* NumericLiteral */:
return node.text;
}
ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
}n/a
function getLocalName(node, allowComments, allowSourceMaps) {
return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
}n/a
function getLocalNameForExternalImport(node, sourceFile) {
var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !ts.isDefaultImport(node)) {
var name = namespaceDeclaration.name;
return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration
.name));
}
if (node.kind === 237 /* ImportDeclaration */ && node.importClause) {
return ts.getGeneratedNameForNode(node);
}
if (node.kind === 243 /* ExportDeclaration */ && node.moduleSpecifier) {
return ts.getGeneratedNameForNode(node);
}
return undefined;
}n/a
function getLocalSymbolForExportDefault(symbol) {
return isExportDefaultSymbol(symbol) ? symbol.valueDeclaration.localSymbol : undefined;
}n/a
function getLocaleSpecificMessage(message) {
return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
}n/a
function getMeaningFromDeclaration(node) {
switch (node.kind) {
case 145 /* Parameter */:
case 225 /* VariableDeclaration */:
case 175 /* BindingElement */:
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
case 259 /* PropertyAssignment */:
case 260 /* ShorthandPropertyAssignment */:
case 262 /* EnumMember */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 151 /* Constructor */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
case 186 /* ArrowFunction */:
case 258 /* CatchClause */:
return 1 /* Value */;
case 144 /* TypeParameter */:
case 229 /* InterfaceDeclaration */:
case 230 /* TypeAliasDeclaration */:
case 162 /* TypeLiteral */:
return 2 /* Type */;
case 228 /* ClassDeclaration */:
case 231 /* EnumDeclaration */:
return 1 /* Value */ | 2 /* Type */;
case 232 /* ModuleDeclaration */:
if (ts.isAmbientModule(node)) {
return 4 /* Namespace */ | 1 /* Value */;
}
else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) {
return 4 /* Namespace */ | 1 /* Value */;
}
else {
return 4 /* Namespace */;
}
case 240 /* NamedImports */:
case 241 /* ImportSpecifier */:
case 236 /* ImportEqualsDeclaration */:
case 237 /* ImportDeclaration */:
case 242 /* ExportAssignment */:
case 243 /* ExportDeclaration */:
return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */;
// An external module can be a Value
case 263 /* SourceFile */:
return 4 /* Namespace */ | 1 /* Value */;
}
return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */;
}n/a
function getMeaningFromLocation(node) {
if (node.kind === 263 /* SourceFile */) {
return 1 /* Value */;
}
else if (node.parent.kind === 242 /* ExportAssignment */) {
return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */;
}
else if (isInRightSideOfImport(node)) {
return getMeaningFromRightHandSideOfImportEquals(node);
}
else if (ts.isDeclarationName(node)) {
return getMeaningFromDeclaration(node.parent);
}
else if (isTypeReference(node)) {
return 2 /* Type */;
}
else if (isNamespaceReference(node)) {
return 4 /* Namespace */;
}
else {
return 1 /* Value */;
}
}n/a
function getModifierFlags(node) {
if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
}
var flags = 0 /* None */;
if (node.modifiers) {
for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
var modifier = _a[_i];
flags |= modifierToFlag(modifier.kind);
}
}
if (node.flags & 4 /* NestedNamespace */ || (node.kind === 70 /* Identifier */ && node.isInJSDocNamespace)) {
flags |= 1 /* Export */;
}
node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
return flags;
}n/a
function getModuleInstanceState(node) {
// A module is uninstantiated if it contains only
// 1. interface declarations, type alias declarations
if (node.kind === 229 /* InterfaceDeclaration */ || node.kind === 230 /* TypeAliasDeclaration */) {
return 0 /* NonInstantiated */;
}
else if (ts.isConstEnumDeclaration(node)) {
return 2 /* ConstEnumOnly */;
}
else if ((node.kind === 237 /* ImportDeclaration */ || node.kind === 236 /* ImportEqualsDeclaration */) && !(ts.hasModifier(
node, 1 /* Export */))) {
return 0 /* NonInstantiated */;
}
else if (node.kind === 233 /* ModuleBlock */) {
var state_1 = 0 /* NonInstantiated */;
ts.forEachChild(node, function (n) {
switch (getModuleInstanceState(n)) {
case 0 /* NonInstantiated */:
// child is non-instantiated - continue searching
return false;
case 2 /* ConstEnumOnly */:
// child is const enum only - record state and continue searching
state_1 = 2 /* ConstEnumOnly */;
return false;
case 1 /* Instantiated */:
// child is instantiated - record state and stop
state_1 = 1 /* Instantiated */;
return true;
}
});
return state_1;
}
else if (node.kind === 232 /* ModuleDeclaration */) {
var body = node.body;
return body ? getModuleInstanceState(body) : 1 /* Instantiated */;
}
else if (node.kind === 70 /* Identifier */ && node.isInJSDocNamespace) {
return 0 /* NonInstantiated */;
}
else {
return 1 /* Instantiated */;
}
}n/a
function getMutableClone(node) {
var clone = getSynthesizedClone(node);
clone.pos = node.pos;
clone.end = node.end;
clone.parent = node.parent;
return clone;
}n/a
function getNameTable(sourceFile) {
if (!sourceFile.nameTable) {
initializeNameTable(sourceFile);
}
return sourceFile.nameTable;
}n/a
function getNamespaceDeclarationNode(node) {
if (node.kind === 236 /* ImportEqualsDeclaration */) {
return node;
}
var importClause = node.importClause;
if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 239 /* NamespaceImport */) {
return importClause.namedBindings;
}
}n/a
function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name));
ts.setTextRange(qualifiedName, name);
var emitFlags;
if (!allowSourceMaps)
emitFlags |= 48 /* NoSourceMap */;
if (!allowComments)
emitFlags |= 1536 /* NoComments */;
if (emitFlags)
ts.setEmitFlags(qualifiedName, emitFlags);
return qualifiedName;
}n/a
function getNewLineCharacter(options) {
if (options.newLine === 0 /* CarriageReturnLineFeed */) {
return carriageReturnLineFeed;
}
else if (options.newLine === 1 /* LineFeed */) {
return lineFeed;
}
else if (ts.sys) {
return ts.sys.newLine;
}
return carriageReturnLineFeed;
}n/a
function getNewLineOrDefaultFromHost(host) {
return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed;
}n/a
function getNewTargetContainer(node) {
var container = getThisContainer(node, /*includeArrowFunctions*/ false);
if (container) {
switch (container.kind) {
case 151 /* Constructor */:
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
return container;
}
}
return undefined;
}n/a
function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
return 2 /* DeclarationAndJavaScriptFiles */;
}
else {
return supportedExtensions.length;
}
}n/a
function getNodeId(node) {
if (!node.id) {
node.id = nextNodeId;
nextNodeId++;
}
return node.id;
}n/a
function getNodeKind(node) {
switch (node.kind) {
case 263 /* SourceFile */:
return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement;
case 232 /* ModuleDeclaration */:
return ts.ScriptElementKind.moduleElement;
case 228 /* ClassDeclaration */:
case 198 /* ClassExpression */:
return ts.ScriptElementKind.classElement;
case 229 /* InterfaceDeclaration */: return ts.ScriptElementKind.interfaceElement;
case 230 /* TypeAliasDeclaration */: return ts.ScriptElementKind.typeElement;
case 231 /* EnumDeclaration */: return ts.ScriptElementKind.enumElement;
case 225 /* VariableDeclaration */:
return getKindOfVariableDeclaration(node);
case 175 /* BindingElement */:
return getKindOfVariableDeclaration(ts.getRootDeclaration(node));
case 186 /* ArrowFunction */:
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
return ts.ScriptElementKind.functionElement;
case 152 /* GetAccessor */: return ts.ScriptElementKind.memberGetAccessorElement;
case 153 /* SetAccessor */: return ts.ScriptElementKind.memberSetAccessorElement;
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
return ts.ScriptElementKind.memberFunctionElement;
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
return ts.ScriptElementKind.memberVariableElement;
case 156 /* IndexSignature */: return ts.ScriptElementKind.indexSignatureElement;
case 155 /* ConstructSignature */: return ts.ScriptElementKind.constructSignatureElement;
case 154 /* CallSignature */: return ts.ScriptElementKind.callSignatureElement;
case 151 /* Constructor */: return ts.ScriptElementKind.constructorImplementationElement;
case 144 /* TypeParameter */: return ts.ScriptElementKind.typeParameterElement;
case 262 /* EnumMember */: return ts.ScriptElementKind.enumMemberElement;
case 145 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? ts.ScriptElementKind.memberVariableElement
: ts.ScriptElementKind.parameterElement;
case 236 /* ImportEqualsDeclaration */:
case 241 /* ImportSpecifier */:
case 238 /* ImportClause */:
case 245 /* ExportSpecifier */:
case 239 /* NamespaceImport */:
return ts.ScriptElementKind.alias;
case 288 /* JSDocTypedefTag */:
return ts.ScriptElementKind.typeElement;
default:
return ts.ScriptElementKind.unknown;
}
function getKindOfVariableDeclaration(v) {
return ts.isConst(v)
? ts.ScriptElementKind.constElement
: ts.isLet(v)
? ts.ScriptElementKind.letElement
: ts.ScriptElementKind.variableElement;
}
}n/a
function getNodeMajorVersion() {
if (typeof process === "undefined") {
return undefined;
}
var version = process.version;
if (!version) {
return undefined;
}
var dot = version.indexOf(".");
if (dot === -1) {
return undefined;
}
return parseInt(version.substring(1, dot));
}n/a
function getNodeModifiers(node) {
var flags = ts.getCombinedModifierFlags(node);
var result = [];
if (flags & 8 /* Private */)
result.push(ts.ScriptElementKindModifier.privateMemberModifier);
if (flags & 16 /* Protected */)
result.push(ts.ScriptElementKindModifier.protectedMemberModifier);
if (flags & 4 /* Public */)
result.push(ts.ScriptElementKindModifier.publicMemberModifier);
if (flags & 32 /* Static */)
result.push(ts.ScriptElementKindModifier.staticModifier);
if (flags & 128 /* Abstract */)
result.push(ts.ScriptElementKindModifier.abstractModifier);
if (flags & 1 /* Export */)
result.push(ts.ScriptElementKindModifier.exportedModifier);
if (ts.isInAmbientContext(node))
result.push(ts.ScriptElementKindModifier.ambientModifier);
return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none;
}n/a
function getNonDecoratorTokenPosOfNode(node, sourceFile) {
if (nodeIsMissing(node) || !node.decorators) {
return getTokenPosOfNode(node, sourceFile);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
}n/a
function getNormalizedAbsolutePath(fileName, currentDirectory) {
return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}n/a
function getNormalizedPathComponents(path, currentDirectory) {
path = normalizeSlashes(path);
var rootLength = getRootLength(path);
if (rootLength === 0) {
// If the path is not rooted it is relative to current directory
path = combinePaths(normalizeSlashes(currentDirectory), path);
rootLength = getRootLength(path);
}
return normalizedPathComponents(path, rootLength);
}n/a
function getNormalizedPathFromPathComponents(pathComponents) {
if (pathComponents && pathComponents.length) {
return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator);
}
}n/a
function getNumericLiteralFlags(text, hint) {
if (text.length > 1) {
switch (text.charCodeAt(1)) {
case 98 /* b */:
case 66 /* B */:
return 2 /* Binary */;
case 111 /* o */:
case 79 /* O */:
return 4 /* Octal */;
case 120 /* x */:
case 88 /* X */:
return 1 /* Hexadecimal */;
}
if (hint & 8 /* Scientific */) {
for (var i = text.length - 1; i >= 0; i--) {
switch (text.charCodeAt(i)) {
case 101 /* e */:
case 69 /* E */:
return 8 /* Scientific */;
}
}
}
}
return 0 /* None */;
}n/a
function getOpenBraceEnd(constructor, sourceFile) {
// First token is the open curly, this is where we want to put the 'super' call.
return constructor.body.getFirstToken(sourceFile).getEnd();
}n/a
function getOperator(expression) {
if (expression.kind === 193 /* BinaryExpression */) {
return expression.operatorToken.kind;
}
else if (expression.kind === 191 /* PrefixUnaryExpression */ || expression.kind === 192 /* PostfixUnaryExpression */) {
return expression.operator;
}
else {
return expression.kind;
}
}n/a
function getOperatorAssociativity(kind, operator, hasArguments) {
switch (kind) {
case 181 /* NewExpression */:
return hasArguments ? 0 /* Left */ : 1 /* Right */;
case 191 /* PrefixUnaryExpression */:
case 188 /* TypeOfExpression */:
case 189 /* VoidExpression */:
case 187 /* DeleteExpression */:
case 190 /* AwaitExpression */:
case 194 /* ConditionalExpression */:
case 196 /* YieldExpression */:
return 1 /* Right */;
case 193 /* BinaryExpression */:
switch (operator) {
case 39 /* AsteriskAsteriskToken */:
case 57 /* EqualsToken */:
case 58 /* PlusEqualsToken */:
case 59 /* MinusEqualsToken */:
case 61 /* AsteriskAsteriskEqualsToken */:
case 60 /* AsteriskEqualsToken */:
case 62 /* SlashEqualsToken */:
case 63 /* PercentEqualsToken */:
case 64 /* LessThanLessThanEqualsToken */:
case 65 /* GreaterThanGreaterThanEqualsToken */:
case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
case 67 /* AmpersandEqualsToken */:
case 69 /* CaretEqualsToken */:
case 68 /* BarEqualsToken */:
return 1 /* Right */;
}
}
return 0 /* Left */;
}n/a
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
case 98 /* ThisKeyword */:
case 96 /* SuperKeyword */:
case 70 /* Identifier */:
case 94 /* NullKeyword */:
case 100 /* TrueKeyword */:
case 85 /* FalseKeyword */:
case 8 /* NumericLiteral */:
case 9 /* StringLiteral */:
case 176 /* ArrayLiteralExpression */:
case 177 /* ObjectLiteralExpression */:
case 185 /* FunctionExpression */:
case 186 /* ArrowFunction */:
case 198 /* ClassExpression */:
case 248 /* JsxElement */:
case 249 /* JsxSelfClosingElement */:
case 11 /* RegularExpressionLiteral */:
case 12 /* NoSubstitutionTemplateLiteral */:
case 195 /* TemplateExpression */:
case 184 /* ParenthesizedExpression */:
case 199 /* OmittedExpression */:
return 19;
case 182 /* TaggedTemplateExpression */:
case 178 /* PropertyAccessExpression */:
case 179 /* ElementAccessExpression */:
return 18;
case 181 /* NewExpression */:
return hasArguments ? 18 : 17;
case 180 /* CallExpression */:
return 17;
case 192 /* PostfixUnaryExpression */:
return 16;
case 191 /* PrefixUnaryExpression */:
case 188 /* TypeOfExpression */:
case 189 /* VoidExpression */:
case 187 /* DeleteExpression */:
case 190 /* AwaitExpression */:
return 15;
case 193 /* BinaryExpression */:
switch (operatorKind) {
case 50 /* ExclamationToken */:
case 51 /* TildeToken */:
return 15;
case 39 /* AsteriskAsteriskToken */:
case 38 /* AsteriskToken */:
case 40 /* SlashToken */:
case 41 /* PercentToken */:
return 14;
case 36 /* PlusToken */:
case 37 /* MinusToken */:
return 13;
case 44 /* LessThanLessThanToken */:
case 45 /* GreaterThanGreaterThanToken */:
case 46 /* GreaterThanGreaterThanGreaterThanToken */:
return 12;
case 26 /* LessThanToken */:
case 29 /* LessThanEqualsToken */:
case 28 /* GreaterThanToken */:
case 30 /* GreaterThanEqualsToken */:
case 91 /* InKeyword */:
case 92 /* InstanceOfKeyword */:
return 11;
case 31 /* EqualsEqualsToken */:
case 33 /* EqualsEqualsEqualsToken */:
case 32 /* ExclamationEqualsToken */:
case 34 /* ExclamationEqualsEqualsToken */:
return 10;
case 47 /* AmpersandToken */:
return 9;
case 49 /* CaretToken */:
return 8;
case 48 /* BarToken */:
return 7;
case 52 /* AmpersandAmpersandToken */:
return 6;
case 53 /* BarBarToken */:
return 5;
case 57 /* EqualsToken */:
case 58 /* PlusEqualsToken */:
case 59 /* MinusEqualsToken */:
case 61 /* AsteriskAsteriskEqualsToken */:
case 60 /* AsteriskEqualsToken */:
case 62 /* SlashEqualsToken */:
case 63 /* PercentEqualsToken */:
case 64 /* LessThanLessThanEqualsToken */:
case 65 /* GreaterThanGreaterThanEqualsToken */:
case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
case 67 /* AmpersandEqualsToken */:
case 69 /* CaretEqualsToken */:
case 68 /* BarEqualsToken */:
return 3;
case 25 /* CommaToken */:
return 0;
default:
return -1;
} ...n/a
function getOptionNameMap() {
if (optionNameMapCache) {
return optionNameMapCache;
}
var optionNameMap = ts.createMap();
var shortOptionNames = ts.createMap();
ts.forEach(ts.optionDeclarations, function (option) {
optionNameMap.set(option.name.toLowerCase(), option);
if (option.shortName) {
shortOptionNames.set(option.shortName, option.name);
}
});
optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames };
return optionNameMapCache;
}n/a
function getOrCreateEmitNode(node) {
if (!node.emitNode) {
if (ts.isParseTreeNode(node)) {
// To avoid holding onto transformation artifacts, we keep track of any
// parse tree node we are annotating. This allows us to clean them up after
// all transformations have completed.
if (node.kind === 263 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
var sourceFile = ts.getSourceFileOfNode(node);
getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
}
node.emitNode = {};
}
return node.emitNode;
}n/a
function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions) {
if (compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) {
var externalHelpersModuleName = getExternalHelpersModuleName(node);
if (externalHelpersModuleName) {
return externalHelpersModuleName;
}
var helpers = ts.getEmitHelpers(node);
if (helpers) {
for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
var helper = helpers_2[_i];
if (!helper.scoped) {
var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
var emitNode = ts.getOrCreateEmitNode(parseNode);
return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText
));
}
}
}
}
}n/a
function getOriginalNode(node, nodeTest) {
if (node) {
while (node.original !== undefined) {
node = node.original;
}
}
return !nodeTest || nodeTest(node) ? node : undefined;
}n/a
function getOriginalNodeId(node) {
node = ts.getOriginalNode(node);
return node ? ts.getNodeId(node) : 0;
}n/a
function getOriginalSourceFileOrBundle(sourceFileOrBundle) {
if (sourceFileOrBundle.kind === 264 /* Bundle */) {
return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, getOriginalSourceFile));
}
return getOriginalSourceFile(sourceFileOrBundle);
}n/a
function getOriginalSourceFiles(sourceFiles) {
return ts.sameMap(sourceFiles, getOriginalSourceFile);
}n/a
function getOwnEmitOutputFilePath(sourceFile, host, extension) {
var compilerOptions = host.getCompilerOptions();
var emitOutputFilePathWithoutExtension;
if (compilerOptions.outDir) {
emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.
outDir));
}
else {
emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName);
}
return emitOutputFilePathWithoutExtension + extension;
}n/a
function getOwnKeys(map) {
var keys = [];
for (var key in map)
if (hasOwnProperty.call(map, key)) {
keys.push(key);
}
return keys;
}n/a
function getParseTreeNode(node, nodeTest) {
if (isParseTreeNode(node)) {
return node;
}
node = getOriginalNode(node);
if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
return node;
}
return undefined;
}n/a
function getPositionOfLineAndCharacter(sourceFile, line, character) {
return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character);
}n/a
function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken
), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (program.getCompilerOptions().declaration) {
diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken));
}
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}n/a
function getProperty(map, key) {
return hasOwnProperty.call(map, key) ? map[key] : undefined;
}n/a
function getPropertyNameForKnownSymbolName(symbolName) {
return "__@" + symbolName;
}n/a
function getPropertyNameForPropertyNameNode(name) {
if (name.kind === 70 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */ || name
.kind === 145 /* Parameter */) {
return name.text;
}
if (name.kind === 143 /* ComputedPropertyName */) {
var nameExpression = name.expression;
if (isWellKnownSymbolSyntactically(nameExpression)) {
var rightHandSideName = nameExpression.name.text;
return getPropertyNameForKnownSymbolName(rightHandSideName);
}
else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) {
return nameExpression.text;
}
}
return undefined;
}n/a
function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
switch (bindingElement.kind) {
case 175 /* BindingElement */:
// `a` in `let { a: b } = ...`
// `[a]` in `let { [a]: b } = ...`
// `"a"` in `let { "a": b } = ...`
// `1` in `let { 1: b } = ...`
if (bindingElement.propertyName) {
var propertyName = bindingElement.propertyName;
return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression)
? propertyName.expression
: propertyName;
}
break;
case 259 /* PropertyAssignment */:
// `a` in `({ a: b } = ...)`
// `[a]` in `({ [a]: b } = ...)`
// `"a"` in `({ "a": b } = ...)`
// `1` in `({ 1: b } = ...)`
if (bindingElement.name) {
var propertyName = bindingElement.name;
return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression)
? propertyName.expression
: propertyName;
}
break;
case 261 /* SpreadAssignment */:
// `a` in `({ ...a } = ...)`
return bindingElement.name;
}
var target = getTargetOfBindingOrAssignmentElement(bindingElement);
if (target && ts.isPropertyName(target)) {
return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression)
? target.expression
: target;
}
ts.Debug.fail("Invalid property name for binding element.");
}n/a
function getRangeEnd(range) {
return range ? range.end : -1;
}n/a
function getRangePos(range) {
return range ? range.pos : -1;
}n/a
function getRegularExpressionForWildcard(specs, basePath, usage) {
var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
if (!patterns || !patterns.length) {
return undefined;
}
var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
// If excluding, match "foo/bar/baz...", but if including, only allow "foo".
var terminator = usage === "exclude" ? "($|/)" : "$";
return "^(" + pattern + ")" + terminator;
}n/a
function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl ) {
var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory);
var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory);
if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") {
// If the directory path given was of type test/cases/ then we really need components of directory to be only till its name
// that is ["test", "cases", ""] needs to be actually ["test", "cases"]
directoryComponents.length--;
}
// Find the component that differs
var joinStartIndex;
for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex
++) {
if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) {
break;
}
}
// Get the relative path
if (joinStartIndex) {
var relativePath = "";
var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length);
for (; joinStartIndex < directoryComponents.length; joinStartIndex++) {
if (directoryComponents[joinStartIndex] !== "") {
relativePath = relativePath + ".." + ts.directorySeparator;
}
}
return relativePath + relativePathComponents.join(ts.directorySeparator);
}
// Cant find the relative path, get the absolute path
var absolutePath = getNormalizedPathFromPathComponents(pathComponents);
if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) {
absolutePath = "file:///" + absolutePath;
}
return absolutePath;
}n/a
function getResolutionDiagnostic(options, _a) {
var extension = _a.extension;
switch (extension) {
case ts.Extension.Ts:
case ts.Extension.Dts:
// These are always allowed.
return undefined;
case ts.Extension.Tsx:
return needJsx();
case ts.Extension.Jsx:
return needJsx() || needAllowJs();
case ts.Extension.Js:
return needAllowJs();
}
function needJsx() {
return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
}
function needAllowJs() {
return options.allowJs ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set;
}
}n/a
function getResolvedExternalModuleName(host, file) {
return file.moduleName || getExternalModuleNameFromPath(host, file.fileName);
}n/a
function getResolvedModule(sourceFile, moduleNameText) {
return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules.get(moduleNameText) : undefined;
}n/a
function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
switch (bindingElement.kind) {
case 145 /* Parameter */:
case 175 /* BindingElement */:
// `...` in `let [...a] = ...`
return bindingElement.dotDotDotToken;
case 197 /* SpreadElement */:
case 261 /* SpreadAssignment */:
// `...` in `[...a] = ...`
return bindingElement;
}
return undefined;
}n/a
function getRestParameterElementType(node) {
if (node && node.kind === 163 /* ArrayType */) {
return node.elementType;
}
else if (node && node.kind === 158 /* TypeReference */) {
return ts.singleOrUndefined(node.typeArguments);
}
else {
return undefined;
}
}n/a
function getRootDeclaration(node) {
while (node.kind === 175 /* BindingElement */) {
node = node.parent.parent;
}
return node;
}n/a
function getRootLength(path) {
if (path.charCodeAt(0) === 47 /* slash */) {
if (path.charCodeAt(1) !== 47 /* slash */)
return 1;
var p1 = path.indexOf("/", 2);
if (p1 < 0)
return 2;
var p2 = path.indexOf("/", p1 + 1);
if (p2 < 0)
return p1 + 1;
return p2 + 1;
}
if (path.charCodeAt(1) === 58 /* colon */) {
if (path.charCodeAt(2) === 47 /* slash */)
return 3;
return 2;
}
// Per RFC 1738 'file' URI schema has the shape file://<host>/<path>
// if <host> is omitted then it is assumed that host value is 'localhost',
// however slash after the omitted <host> is not removed.
// file:///folder1/file1 - this is a correct URI
// file://folder2/file2 - this is an incorrect URI
if (path.lastIndexOf("file:///", 0) === 0) {
return "file:///".length;
}
var idx = path.indexOf("://");
if (idx !== -1) {
return idx + "://".length;
}
return 0;
}n/a
function getScriptKind(fileName, host) {
// First check to see if the script kind was specified by the host. Chances are the host
// may override the default script kind for the file extension.
var scriptKind;
if (host && host.getScriptKind) {
scriptKind = host.getScriptKind(fileName);
}
if (!scriptKind) {
scriptKind = ts.getScriptKindFromFileName(fileName);
}
return ts.ensureScriptKind(fileName, scriptKind);
}n/a
function getScriptKindFromFileName(fileName) {
var ext = fileName.substr(fileName.lastIndexOf("."));
switch (ext.toLowerCase()) {
case ".js":
return 1 /* JS */;
case ".jsx":
return 2 /* JSX */;
case ".ts":
return 3 /* TS */;
case ".tsx":
return 4 /* TSX */;
default:
return 0 /* Unknown */;
}
}n/a
function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
return convertClassifications(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames
, span));
}n/a
function getSetAccessorTypeAnnotationNode(accessor) {
if (accessor && accessor.parameters.length > 0) {
var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
return accessor.parameters[hasThis ? 1 : 0].type;
}
}n/a
function getShebang(text) {
return shebangTriviaRegex.test(text)
? shebangTriviaRegex.exec(text)[0]
: undefined;
}n/a
function getSingleLineStringWriter() {
if (stringWriters.length === 0) {
var str_1 = "";
var writeText = function (text) { return str_1 += text; };
return {
string: function () { return str_1; },
writeKeyword: writeText,
writeOperator: writeText,
writePunctuation: writeText,
writeSpace: writeText,
writeStringLiteral: writeText,
writeParameter: writeText,
writeProperty: writeText,
writeSymbol: writeText,
// Completely ignore indentation for string writers. And map newlines to
// a single space.
writeLine: function () { return str_1 += " "; },
increaseIndent: ts.noop,
decreaseIndent: ts.noop,
clear: function () { return str_1 = ""; },
trackSymbol: ts.noop,
reportInaccessibleThisError: ts.noop,
reportIllegalExtends: ts.noop
};
}
return stringWriters.pop();
}n/a
function getSourceFileOfNode(node) {
while (node && node.kind !== 263 /* SourceFile */) {
node = node.parent;
}
return node;
}n/a
function getSourceFilePathInNewDir(sourceFile, host, newDirPath) {
var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory());
var commonSourceDirectory = host.getCommonSourceDirectory();
var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory
)) === 0;
sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath
;
return ts.combinePaths(newDirPath, sourceFilePath);
}n/a
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
if (options.outFile || options.out) {
var moduleKind = ts.getEmitModuleKind(options);
var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
// Can emit only sources that are not declaration file and are either non module code or module with --module or --target
es6 specified
return ts.filter(host.getSourceFiles(), function (sourceFile) {
return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary
);
});
}
else {
var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary
); });
}
}n/a
function getSourceMapRange(node) {
var emitNode = node.emitNode;
return (emitNode && emitNode.sourceMapRange) || node;
}n/a
function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
if (nodeIsMissing(node)) {
return "";
}
var text = sourceFile.text;
return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end);
}n/a
function getSpanOfTokenAtPosition(sourceFile, pos) {
var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*
onError:*/ undefined, pos);
scanner.scan();
var start = scanner.getTokenPos();
return ts.createTextSpanFromBounds(start, scanner.getTextPos());
}n/a
function getSpecialPropertyAssignmentKind(expression) {
if (!isInJavaScriptFile(expression)) {
return 0 /* None */;
}
if (expression.kind !== 193 /* BinaryExpression */) {
return 0 /* None */;
}
var expr = expression;
if (expr.operatorToken.kind !== 57 /* EqualsToken */ || expr.left.kind !== 178 /* PropertyAccessExpression */) {
return 0 /* None */;
}
var lhs = expr.left;
if (lhs.expression.kind === 70 /* Identifier */) {
var lhsId = lhs.expression;
if (lhsId.text === "exports") {
// exports.name = expr
return 1 /* ExportsProperty */;
}
else if (lhsId.text === "module" && lhs.name.text === "exports") {
// module.exports = expr
return 2 /* ModuleExports */;
}
}
else if (lhs.expression.kind === 98 /* ThisKeyword */) {
return 4 /* ThisProperty */;
}
else if (lhs.expression.kind === 178 /* PropertyAccessExpression */) {
// chained dot, e.g. x.y.z = expr; this var is the 'x.y' part
var innerPropertyAccess = lhs.expression;
if (innerPropertyAccess.expression.kind === 70 /* Identifier */) {
// module.exports.name = expr
var innerPropertyAccessIdentifier = innerPropertyAccess.expression;
if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") {
return 1 /* ExportsProperty */;
}
if (innerPropertyAccess.name.text === "prototype") {
return 3 /* PrototypeProperty */;
}
}
}
return 0 /* None */;
}n/a
function getStartPosOfNode(node) {
return node.pos;
}n/a
function getStartPositionOfLine(line, sourceFile) {
ts.Debug.assert(line >= 0);
return ts.getLineStarts(sourceFile)[line];
}n/a
function getStartPositionOfRange(range, sourceFile) {
return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
}n/a
function getStringLiteralTypeForNode(node, typeChecker) {
var searchNode = node.parent.kind === 172 /* LiteralType */ ? node.parent : node;
var type = typeChecker.getTypeAtLocation(searchNode);
if (type && type.flags & 32 /* StringLiteral */) {
return type;
}
return undefined;
}n/a
function getSuperContainer(node, stopOnFunctions) {
while (true) {
node = node.parent;
if (!node) {
return node;
}
switch (node.kind) {
case 143 /* ComputedPropertyName */:
node = node.parent;
break;
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
case 186 /* ArrowFunction */:
if (!stopOnFunctions) {
continue;
}
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 151 /* Constructor */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
return node;
case 146 /* Decorator */:
// Decorators are always applied outside of the body of a class or method.
if (node.parent.kind === 145 /* Parameter */ && isClassElement(node.parent.parent)) {
// If the decorator's parent is a Parameter, we resolve the this container from
// the grandparent class declaration.
node = node.parent.parent;
}
else if (isClassElement(node.parent)) {
// If the decorator's parent is a class element, we resolve the 'this' container
// from the parent class declaration.
node = node.parent;
}
break;
}
}
}n/a
function getSupportedCodeFixes() {
return ts.codefix.getSupportedErrorCodes();
}n/a
function getSupportedExtensions(options, extraFileExtensions) {
var needAllExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) {
return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
var extensions = allSupportedExtensions.slice(0);
for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) {
var extInfo = extraFileExtensions_1[_i];
if (extensions.indexOf(extInfo.extension) === -1) {
extensions.push(extInfo.extension);
}
}
return extensions;
}n/a
function getSymbolId(symbol) {
if (!symbol.id) {
symbol.id = nextSymbolId;
nextSymbolId++;
}
return symbol.id;
}n/a
function getSyntacticClassifications(cancellationToken, sourceFile, span) {
return convertClassifications(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span));
}n/a
function getSynthesizedClone(node) {
// We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
// the original node. We also need to exclude specific properties and only include own-
// properties (to skip members already defined on the shared prototype).
var clone = createSynthesizedNode(node.kind);
clone.flags |= node.flags;
setOriginalNode(clone, node);
for (var key in node) {
if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
continue;
}
clone[key] = node[key];
}
return clone;
}n/a
function getTargetLabel(referenceNode, labelName) {
while (referenceNode) {
if (referenceNode.kind === 221 /* LabeledStatement */ && referenceNode.label.text === labelName) {
return referenceNode.label;
}
referenceNode = referenceNode.parent;
}
return undefined;
}n/a
function getTargetOfBindingOrAssignmentElement(bindingElement) {
if (ts.isDeclarationBindingElement(bindingElement)) {
// `a` in `let { a } = ...`
// `a` in `let { a = 1 } = ...`
// `b` in `let { a: b } = ...`
// `b` in `let { a: b = 1 } = ...`
// `a` in `let { ...a } = ...`
// `{b}` in `let { a: {b} } = ...`
// `{b}` in `let { a: {b} = 1 } = ...`
// `[b]` in `let { a: [b] } = ...`
// `[b]` in `let { a: [b] = 1 } = ...`
// `a` in `let [a] = ...`
// `a` in `let [a = 1] = ...`
// `a` in `let [...a] = ...`
// `{a}` in `let [{a}] = ...`
// `{a}` in `let [{a} = 1] = ...`
// `[a]` in `let [[a]] = ...`
// `[a]` in `let [[a] = 1] = ...`
return bindingElement.name;
}
if (ts.isObjectLiteralElementLike(bindingElement)) {
switch (bindingElement.kind) {
case 259 /* PropertyAssignment */:
// `b` in `({ a: b } = ...)`
// `b` in `({ a: b = 1 } = ...)`
// `{b}` in `({ a: {b} } = ...)`
// `{b}` in `({ a: {b} = 1 } = ...)`
// `[b]` in `({ a: [b] } = ...)`
// `[b]` in `({ a: [b] = 1 } = ...)`
// `b.c` in `({ a: b.c } = ...)`
// `b.c` in `({ a: b.c = 1 } = ...)`
// `b[0]` in `({ a: b[0] } = ...)`
// `b[0]` in `({ a: b[0] = 1 } = ...)`
return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
case 260 /* ShorthandPropertyAssignment */:
// `a` in `({ a } = ...)`
// `a` in `({ a = 1 } = ...)`
return bindingElement.name;
case 261 /* SpreadAssignment */:
// `a` in `({ ...a } = ...)`
return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
}
// no target
return undefined;
}
if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
// `a` in `[a = 1] = ...`
// `{a}` in `[{a} = 1] = ...`
// `[a]` in `[[a] = 1] = ...`
// `a.b` in `[a.b = 1] = ...`
// `a[0]` in `[a[0] = 1] = ...`
return getTargetOfBindingOrAssignmentElement(bindingElement.left);
}
if (ts.isSpreadExpression(bindingElement)) {
// `a` in `[...a] = ...`
return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
}
// `a` in `[a] = ...`
// `{a}` in `[{a}] = ...`
// `[a]` in `[[a]] = ...`
// `a.b` in `[a.b] = ...`
// `a[0]` in `[a[0]] = ...`
return bindingElement;
}n/a
function getTextOfNode(node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
}n/a
function getTextOfNodeFromSourceText(sourceText, node) {
if (nodeIsMissing(node)) {
return "";
}
return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end);
}n/a
function getTextOfPropertyName(name) {
switch (name.kind) {
case 70 /* Identifier */:
return name.text;
case 9 /* StringLiteral */:
case 8 /* NumericLiteral */:
return name.text;
case 143 /* ComputedPropertyName */:
if (isStringOrNumericLiteral(name.expression)) {
return name.expression.text;
}
}
return undefined;
}n/a
function getThisContainer(node, includeArrowFunctions) {
while (true) {
node = node.parent;
if (!node) {
return undefined;
}
switch (node.kind) {
case 143 /* ComputedPropertyName */:
// If the grandparent node is an object literal (as opposed to a class),
// then the computed property is not a 'this' container.
// A computed property name in a class needs to be a this container
// so that we can error on it.
if (isClassLike(node.parent.parent)) {
return node;
}
// If this is a computed property, then the parent should not
// make it a this container. The parent might be a property
// in an object literal, like a method or accessor. But in order for
// such a parent to be a this container, the reference must be in
// the *body* of the container.
node = node.parent;
break;
case 146 /* Decorator */:
// Decorators are always applied outside of the body of a class or method.
if (node.parent.kind === 145 /* Parameter */ && isClassElement(node.parent.parent)) {
// If the decorator's parent is a Parameter, we resolve the this container from
// the grandparent class declaration.
node = node.parent.parent;
}
else if (isClassElement(node.parent)) {
// If the decorator's parent is a class element, we resolve the 'this' container
// from the parent class declaration.
node = node.parent;
}
break;
case 186 /* ArrowFunction */:
if (!includeArrowFunctions) {
continue;
}
// Fall through
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
case 232 /* ModuleDeclaration */:
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 151 /* Constructor */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 154 /* CallSignature */:
case 155 /* ConstructSignature */:
case 156 /* IndexSignature */:
case 231 /* EnumDeclaration */:
case 263 /* SourceFile */:
return node;
}
}
}n/a
function getThisParameter(signature) {
if (signature.parameters.length) {
var thisParameter = signature.parameters[0];
if (parameterIsThisKeyword(thisParameter)) {
return thisParameter;
}
}
}n/a
function getTokenAtPosition(sourceFile, position, includeJsDocComment) {
if (includeJsDocComment === void 0) { includeJsDocComment = false; }
return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined
, includeJsDocComment);
}n/a
function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
// With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
// want to skip trivia because this will launch us forward to the next token.
if (nodeIsMissing(node)) {
return node.pos;
}
if (isJSDocNode(node)) {
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments
*/ true);
}
if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) {
return getTokenPosOfNode(node.jsDoc[0]);
}
// For a syntax list, it is possible that one of its children has JSDocComment nodes, while
// the syntax list itself considers them as normal trivia. Therefore if we simply skip
// trivia for the list, we may have skipped the JSDocComment as well. So we should process its
// first child to determine the actual position of its first token.
if (node.kind === 295 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
}n/a
function getTokenSourceMapRange(node, token) {
var emitNode = node.emitNode;
var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
return tokenSourceMapRanges && tokenSourceMapRanges[token];
}n/a
function getTouchingPropertyName(sourceFile, position, includeJsDocComment) {
if (includeJsDocComment === void 0) { includeJsDocComment = false; }
return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment);
}n/a
function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) {
if (includeJsDocComment === void 0) { includeJsDocComment = false; }
return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment
);
}n/a
function getTouchingWord(sourceFile, position, includeJsDocComment) {
if (includeJsDocComment === void 0) { includeJsDocComment = false; }
return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment);
}n/a
function getTrailingCommentRanges(text, pos) {
return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined);
}n/a
function getTransformFlagsSubtreeExclusions(kind) {
if (kind >= 157 /* FirstTypeNode */ && kind <= 172 /* LastTypeNode */) {
return -3 /* TypeExcludes */;
}
switch (kind) {
case 180 /* CallExpression */:
case 181 /* NewExpression */:
case 176 /* ArrayLiteralExpression */:
return 537396545 /* ArrayLiteralOrCallOrNewExcludes */;
case 232 /* ModuleDeclaration */:
return 574674241 /* ModuleExcludes */;
case 145 /* Parameter */:
return 536872257 /* ParameterExcludes */;
case 186 /* ArrowFunction */:
return 601249089 /* ArrowFunctionExcludes */;
case 185 /* FunctionExpression */:
case 227 /* FunctionDeclaration */:
return 601281857 /* FunctionExcludes */;
case 226 /* VariableDeclarationList */:
return 546309441 /* VariableDeclarationListExcludes */;
case 228 /* ClassDeclaration */:
case 198 /* ClassExpression */:
return 539358529 /* ClassExcludes */;
case 151 /* Constructor */:
return 601015617 /* ConstructorExcludes */;
case 150 /* MethodDeclaration */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
return 601015617 /* MethodOrAccessorExcludes */;
case 118 /* AnyKeyword */:
case 132 /* NumberKeyword */:
case 129 /* NeverKeyword */:
case 135 /* StringKeyword */:
case 133 /* ObjectKeyword */:
case 121 /* BooleanKeyword */:
case 136 /* SymbolKeyword */:
case 104 /* VoidKeyword */:
case 144 /* TypeParameter */:
case 147 /* PropertySignature */:
case 149 /* MethodSignature */:
case 154 /* CallSignature */:
case 155 /* ConstructSignature */:
case 156 /* IndexSignature */:
case 229 /* InterfaceDeclaration */:
case 230 /* TypeAliasDeclaration */:
return -3 /* TypeExcludes */;
case 177 /* ObjectLiteralExpression */:
return 540087617 /* ObjectLiteralExcludes */;
case 258 /* CatchClause */:
return 537920833 /* CatchClauseExcludes */;
case 173 /* ObjectBindingPattern */:
case 174 /* ArrayBindingPattern */:
return 537396545 /* BindingPatternExcludes */;
default:
return 536872257 /* NodeExcludes */;
}
}n/a
function getTransformers(compilerOptions) {
var jsx = compilerOptions.jsx;
var languageVersion = ts.getEmitScriptTarget(compilerOptions);
var moduleKind = ts.getEmitModuleKind(compilerOptions);
var transformers = [];
transformers.push(ts.transformTypeScript);
if (jsx === 2 /* React */) {
transformers.push(ts.transformJsx);
}
if (languageVersion < 5 /* ESNext */) {
transformers.push(ts.transformESNext);
}
if (languageVersion < 4 /* ES2017 */) {
transformers.push(ts.transformES2017);
}
if (languageVersion < 3 /* ES2016 */) {
transformers.push(ts.transformES2016);
}
if (languageVersion < 2 /* ES2015 */) {
transformers.push(ts.transformES2015);
transformers.push(ts.transformGenerators);
}
transformers.push(getModuleTransformer(moduleKind));
// The ES5 transformer is last so that it can substitute expressions like `exports.default`
// for ES3.
if (languageVersion < 1 /* ES5 */) {
transformers.push(ts.transformES5);
}
return transformers;
}n/a
function getTypeArgumentOrTypeParameterList(node) {
if (node.kind === 158 /* TypeReference */ || node.kind === 180 /* CallExpression */) {
return node.typeArguments;
}
if (ts.isFunctionLike(node) || node.kind === 228 /* ClassDeclaration */ || node.kind === 229 /* InterfaceDeclaration */) {
return node.typeParameters;
}
return undefined;
}n/a
function getTypeParameterOwner(d) {
if (d && d.kind === 144 /* TypeParameter */) {
for (var current = d; current; current = current.parent) {
if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 229 /* InterfaceDeclaration */) {
return current;
}
}
}
}n/a
function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
if (names.length !== newResolutions.length) {
return false;
}
for (var i = 0; i < names.length; i++) {
var newResolution = newResolutions[i];
var oldResolution = oldResolutions && oldResolutions.get(names[i]);
var changed = oldResolution
? !newResolution || !comparer(oldResolution, newResolution)
: newResolution;
if (changed) {
return true;
}
}
return false;
}n/a
function hasChildOfKind(n, kind, sourceFile) {
return !!findChildOfKind(n, kind, sourceFile);
}n/a
function hasDeclaredRestParameter(s) {
return isDeclaredRestParam(ts.lastOrUndefined(s.parameters));
}n/a
function hasDocComment(sourceFile, position) {
var token = getTokenAtPosition(sourceFile, position);
// First, we have to see if this position actually landed in a comment.
var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos);
return ts.forEach(commentRanges, jsDocPrefix);
function jsDocPrefix(c) {
var text = sourceFile.text;
return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*";
}
}n/a
function hasDynamicName(declaration) {
return declaration.name && isDynamicName(declaration.name);
}n/a
function hasExtension(fileName) {
return getBaseFileName(fileName).indexOf(".") >= 0;
}n/a
function hasJSDocParameterTags(node) {
var parameterTags = getJSDocTags(node, 284 /* JSDocParameterTag */);
return parameterTags && parameterTags.length > 0;
}n/a
function hasJavaScriptFileExtension(fileName) {
return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
}n/a
function hasModifier(node, flags) {
return (getModifierFlags(node) & flags) !== 0;
}n/a
function hasModifiers(node) {
return getModifierFlags(node) !== 0 /* None */;
}n/a
function hasProperty(map, key) {
return hasOwnProperty.call(map, key);
}n/a
function hasQuestionToken(node) {
if (node) {
switch (node.kind) {
case 145 /* Parameter */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 260 /* ShorthandPropertyAssignment */:
case 259 /* PropertyAssignment */:
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
return node.questionToken !== undefined;
}
}
return false;
}n/a
function hasResolvedModule(sourceFile, moduleNameText) {
return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText));
}n/a
function hasRestParameter(s) {
return isRestParameter(ts.lastOrUndefined(s.parameters));
}n/a
function hasTrailingDirectorySeparator(path) {
var lastCharacter = path.charAt(path.length - 1);
return lastCharacter === "/" || lastCharacter === "\\";
}n/a
function hasTypeScriptFileExtension(fileName) {
return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
}n/a
function hasZeroOrOneAsteriskCharacter(str) {
var seenAsterisk = false;
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) === 42 /* asterisk */) {
if (!seenAsterisk) {
seenAsterisk = true;
}
else {
// have already seen asterisk
return false;
}
}
}
return true;
}n/a
function identifierIsThisKeyword(id) {
return id.originalKeywordKind === 98 /* ThisKeyword */;
}n/a
function indexOf(array, value) {
if (array) {
for (var i = 0; i < array.length; i++) {
if (array[i] === value) {
return i;
}
}
}
return -1;
}n/a
function indexOfAnyCharCode(text, charCodes, start) {
for (var i = start || 0; i < text.length; i++) {
if (contains(charCodes, text.charCodeAt(i))) {
return i;
}
}
return -1;
}n/a
function inlineExpressions(expressions) {
return ts.reduceLeft(expressions, ts.createComma);
}n/a
function introducesArgumentsExoticObject(node) {
switch (node.kind) {
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 151 /* Constructor */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
return true;
}
return false;
}n/a
function isAccessibilityModifier(kind) {
switch (kind) {
case 113 /* PublicKeyword */:
case 111 /* PrivateKeyword */:
case 112 /* ProtectedKeyword */:
return true;
}
return false;
}n/a
function isAccessor(node) {
return node && (node.kind === 152 /* GetAccessor */ || node.kind === 153 /* SetAccessor */);
}n/a
function isAliasSymbolDeclaration(node) {
return node.kind === 236 /* ImportEqualsDeclaration */ ||
node.kind === 235 /* NamespaceExportDeclaration */ ||
node.kind === 238 /* ImportClause */ && !!node.name ||
node.kind === 239 /* NamespaceImport */ ||
node.kind === 241 /* ImportSpecifier */ ||
node.kind === 245 /* ExportSpecifier */ ||
node.kind === 242 /* ExportAssignment */ && exportAssignmentIsAlias(node);
}n/a
function isAmbientModule(node) {
return node && node.kind === 232 /* ModuleDeclaration */ &&
(node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node));
}n/a
function isArray(value) {
return Array.isArray ? Array.isArray(value) : value instanceof Array;
}n/a
function isArrayBindingElement(node) {
var kind = node.kind;
return kind === 175 /* BindingElement */
|| kind === 199 /* OmittedExpression */;
}n/a
function isArrayBindingOrAssignmentPattern(node) {
switch (node.kind) {
case 174 /* ArrayBindingPattern */:
case 176 /* ArrayLiteralExpression */:
return true;
}
return false;
}n/a
function isArrayBindingPattern(node) {
return node.kind === 174 /* ArrayBindingPattern */;
}n/a
function isArrayLiteralExpression(node) {
return node.kind === 176 /* ArrayLiteralExpression */;
}n/a
function isArrayLiteralOrObjectLiteralDestructuringPattern(node) {
if (node.kind === 176 /* ArrayLiteralExpression */ ||
node.kind === 177 /* ObjectLiteralExpression */) {
// [a,b,c] from:
// [a, b, c] = someExpression;
if (node.parent.kind === 193 /* BinaryExpression */ &&
node.parent.left === node &&
node.parent.operatorToken.kind === 57 /* EqualsToken */) {
return true;
}
// [a, b, c] from:
// for([a, b, c] of expression)
if (node.parent.kind === 215 /* ForOfStatement */ &&
node.parent.initializer === node) {
return true;
}
// [a, b, c] of
// [x, [a, b, c] ] = someExpression
// or
// {x, a: {a, b, c} } = someExpression
if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 259 /* PropertyAssignment */ ? node.parent.parent
: node.parent)) {
return true;
}
}
return false;
}n/a
function isAssertionExpression(node) {
var kind = node.kind;
return kind === 183 /* TypeAssertionExpression */
|| kind === 201 /* AsExpression */;
}n/a
function isAssignmentExpression(node, excludeCompoundAssignment) {
return isBinaryExpression(node)
&& (excludeCompoundAssignment
? node.operatorToken.kind === 57 /* EqualsToken */
: isAssignmentOperator(node.operatorToken.kind))
&& isLeftHandSideExpression(node.left);
}n/a
function isAssignmentOperator(token) {
return token >= 57 /* FirstAssignment */ && token <= 69 /* LastAssignment */;
}n/a
function isAssignmentPattern(node) {
var kind = node.kind;
return kind === 176 /* ArrayLiteralExpression */
|| kind === 177 /* ObjectLiteralExpression */;
}n/a
function isAssignmentTarget(node) {
return getAssignmentTargetKind(node) !== 0 /* None */;
}n/a
function isAsyncFunctionLike(node) {
return isFunctionLike(node) && hasModifier(node, 256 /* Async */) && !isAccessor(node);
}n/a
function isBinaryExpression(node) {
return node.kind === 193 /* BinaryExpression */;
}n/a
function isBinaryOrOctalIntegerLiteral(node, text) {
return node.kind === 8 /* NumericLiteral */
&& (getNumericLiteralFlags(text, /*hint*/ 6 /* BinaryOrOctal */) & 6 /* BinaryOrOctal */) !== 0;
}n/a
function isBindingElement(node) {
return node.kind === 175 /* BindingElement */;
}n/a
function isBindingName(node) {
var kind = node.kind;
return kind === 70 /* Identifier */
|| kind === 173 /* ObjectBindingPattern */
|| kind === 174 /* ArrayBindingPattern */;
}n/a
function isBindingOrAssignmentPattern(node) {
return isObjectBindingOrAssignmentPattern(node)
|| isArrayBindingOrAssignmentPattern(node);
}n/a
function isBindingPattern(node) {
if (node) {
var kind = node.kind;
return kind === 174 /* ArrayBindingPattern */
|| kind === 173 /* ObjectBindingPattern */;
}
return false;
}n/a
function isBlock(node) {
return node.kind === 206 /* Block */;
}n/a
function isBlockOrCatchScoped(declaration) {
return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
isCatchClauseVariableDeclarationOrBindingElement(declaration);
}n/a
function isBlockScope(node, parentNode) {
switch (node.kind) {
case 263 /* SourceFile */:
case 234 /* CaseBlock */:
case 258 /* CatchClause */:
case 232 /* ModuleDeclaration */:
case 213 /* ForStatement */:
case 214 /* ForInStatement */:
case 215 /* ForOfStatement */:
case 151 /* Constructor */:
case 150 /* MethodDeclaration */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
case 186 /* ArrowFunction */:
return true;
case 206 /* Block */:
// function block is not considered block-scope container
// see comment in binder.ts: bind(...), case for SyntaxKind.Block
return parentNode && !isFunctionLike(parentNode);
}
return false;
}n/a
function isBlockScopedContainerTopLevel(node) {
return node.kind === 263 /* SourceFile */ ||
node.kind === 232 /* ModuleDeclaration */ ||
isFunctionLike(node);
}n/a
function isCallExpression(node) {
return node.kind === 180 /* CallExpression */;
}n/a
function isCallExpressionTarget(node) {
return isCallOrNewExpressionTarget(node, 180 /* CallExpression */);
}n/a
function isCallLikeExpression(node) {
switch (node.kind) {
case 180 /* CallExpression */:
case 181 /* NewExpression */:
case 182 /* TaggedTemplateExpression */:
case 146 /* Decorator */:
return true;
default:
return false;
}
}n/a
function isCaseBlock(node) {
return node.kind === 234 /* CaseBlock */;
}n/a
function isCaseOrDefaultClause(node) {
var kind = node.kind;
return kind === 255 /* CaseClause */
|| kind === 256 /* DefaultClause */;
}n/a
function isCatchClause(node) {
return node.kind === 258 /* CatchClause */;
}n/a
function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
var node = getRootDeclaration(declaration);
return node.kind === 225 /* VariableDeclaration */ && node.parent.kind === 258 /* CatchClause */;
}n/a
function isChildOfNodeWithKind(node, kind) {
while (node) {
if (node.kind === kind) {
return true;
}
node = node.parent;
}
return false;
}n/a
function isClassElement(node) {
var kind = node.kind;
return kind === 151 /* Constructor */
|| kind === 148 /* PropertyDeclaration */
|| kind === 150 /* MethodDeclaration */
|| kind === 152 /* GetAccessor */
|| kind === 153 /* SetAccessor */
|| kind === 156 /* IndexSignature */
|| kind === 205 /* SemicolonClassElement */;
}n/a
function isClassLike(node) {
return node && (node.kind === 228 /* ClassDeclaration */ || node.kind === 198 /* ClassExpression */);
}n/a
function isCollapsedRange(range) {
return range.pos === range.end;
}n/a
function isComment(kind) {
return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */;
}n/a
function isCompletedNode(n, sourceFile) {
if (ts.nodeIsMissing(n)) {
return false;
}
switch (n.kind) {
case 228 /* ClassDeclaration */:
case 229 /* InterfaceDeclaration */:
case 231 /* EnumDeclaration */:
case 177 /* ObjectLiteralExpression */:
case 173 /* ObjectBindingPattern */:
case 162 /* TypeLiteral */:
case 206 /* Block */:
case 233 /* ModuleBlock */:
case 234 /* CaseBlock */:
case 240 /* NamedImports */:
case 244 /* NamedExports */:
return nodeEndsWith(n, 17 /* CloseBraceToken */, sourceFile);
case 258 /* CatchClause */:
return isCompletedNode(n.block, sourceFile);
case 181 /* NewExpression */:
if (!n.arguments) {
return true;
}
// fall through
case 180 /* CallExpression */:
case 184 /* ParenthesizedExpression */:
case 167 /* ParenthesizedType */:
return nodeEndsWith(n, 19 /* CloseParenToken */, sourceFile);
case 159 /* FunctionType */:
case 160 /* ConstructorType */:
return isCompletedNode(n.type, sourceFile);
case 151 /* Constructor */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 155 /* ConstructSignature */:
case 154 /* CallSignature */:
case 186 /* ArrowFunction */:
if (n.body) {
return isCompletedNode(n.body, sourceFile);
}
if (n.type) {
return isCompletedNode(n.type, sourceFile);
}
// Even though type parameters can be unclosed, we can get away with
// having at least a closing paren.
return hasChildOfKind(n, 19 /* CloseParenToken */, sourceFile);
case 232 /* ModuleDeclaration */:
return n.body && isCompletedNode(n.body, sourceFile);
case 210 /* IfStatement */:
if (n.elseStatement) {
return isCompletedNode(n.elseStatement, sourceFile);
}
return isCompletedNode(n.thenStatement, sourceFile);
case 209 /* ExpressionStatement */:
return isCompletedNode(n.expression, sourceFile) ||
hasChildOfKind(n, 24 /* SemicolonToken */);
case 176 /* ArrayLiteralExpression */:
case 174 /* ArrayBindingPattern */:
case 179 /* ElementAccessExpression */:
case 143 /* ComputedPropertyName */:
case 164 /* TupleType */:
return nodeEndsWith(n, 21 /* CloseBracketToken */, sourceFile);
case 156 /* IndexSignature */:
if (n.type) {
return isCompletedNode(n.type, sourceFile);
}
return hasChildOfKind(n, 21 /* CloseBracketToken */, sourceFile);
case 255 /* CaseClause */:
case 256 /* DefaultClause */:
// there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non
-completed
return false;
case 213 /* ForStatement */:
case 214 /* ForInStatement */:
case 215 /* ForOfStatement */:
case 212 /* WhileStatement */:
return isCompletedNode(n.statement, sourceFile);
case 211 /* DoStatement */:
// rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')';
var hasWhileKeyword = findChildOfKind(n, 105 /* WhileKeyword */, sourceFile);
if (hasWhileKeyword) {
return nodeEndsWith(n, 19 /* CloseParenToken */, sourceFile);
}
return isCompletedNode(n.statement, sourceFile);
case 161 /* TypeQuery */:
return isCompletedNode(n.exprName, sourceFile);
case 188 /* TypeOfExpression */:
case 187 /* DeleteExpression */:
case 189 /* Vo ...n/a
function isComputedPropertyName(node) {
return node.kind === 143 /* ComputedPropertyName */;
}n/a
function isConciseBody(node) {
return isBlock(node)
|| isExpression(node);
}n/a
function isConditionalExpression(node) {
return node.kind === 194 /* ConditionalExpression */;
}n/a
function isConst(node) {
return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */)
|| !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
}n/a
function isConstEnumDeclaration(node) {
return node.kind === 231 /* EnumDeclaration */ && isConst(node);
}n/a
function isDeclaration(node) {
return isDeclarationKind(node.kind);
}n/a
function isDeclarationBindingElement(bindingElement) {
switch (bindingElement.kind) {
case 225 /* VariableDeclaration */:
case 145 /* Parameter */:
case 175 /* BindingElement */:
return true;
}
return false;
}n/a
function isDeclarationFile(file) {
return file.isDeclarationFile;
}n/a
function isDeclarationName(name) {
if (name.kind !== 70 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) {
return false;
}
var parent = name.parent;
if (parent.kind === 241 /* ImportSpecifier */ || parent.kind === 245 /* ExportSpecifier */) {
if (parent.propertyName) {
return true;
}
}
if (isDeclaration(parent)) {
return parent.name === name;
}
return false;
}n/a
function isDeclarationNameOfEnumOrNamespace(node) {
var parseNode = ts.getParseTreeNode(node);
if (parseNode) {
switch (parseNode.parent.kind) {
case 231 /* EnumDeclaration */:
case 232 /* ModuleDeclaration */:
return parseNode === parseNode.parent.name;
}
}
return false;
}n/a
function isDeclarationOfFunctionExpression(s) {
if (s.valueDeclaration && s.valueDeclaration.kind === 225 /* VariableDeclaration */) {
var declaration = s.valueDeclaration;
return declaration.initializer && declaration.initializer.kind === 185 /* FunctionExpression */;
}
return false;
}n/a
function isDeclarationStatement(node) {
return isDeclarationStatementKind(node.kind);
}n/a
function isDeclaredRestParam(node) {
return node && node.dotDotDotToken !== undefined;
}n/a
function isDecorator(node) {
return node.kind === 146 /* Decorator */;
}n/a
function isDefaultImport(node) {
return node.kind === 237 /* ImportDeclaration */
&& node.importClause
&& !!node.importClause.name;
}n/a
function isDefined(value) {
return value !== undefined;
}n/a
function isDeleteTarget(node) {
if (node.kind !== 178 /* PropertyAccessExpression */ && node.kind !== 179 /* ElementAccessExpression */) {
return false;
}
node = node.parent;
while (node && node.kind === 184 /* ParenthesizedExpression */) {
node = node.parent;
}
return node && node.kind === 187 /* DeleteExpression */;
}n/a
function isDestructuringAssignment(node) {
if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
var kind = node.left.kind;
return kind === 177 /* ObjectLiteralExpression */
|| kind === 176 /* ArrayLiteralExpression */;
}
return false;
}n/a
function isDynamicName(name) {
return name.kind === 143 /* ComputedPropertyName */ &&
!isStringOrNumericLiteral(name.expression) &&
!isWellKnownSymbolSyntactically(name.expression);
}n/a
function isESSymbolIdentifier(node) {
return node.kind === 70 /* Identifier */ && node.text === "Symbol";
}n/a
function isEffectiveExternalModule(node, compilerOptions) {
return ts.isExternalModule(node) || compilerOptions.isolatedModules;
}n/a
function isElementAccessExpression(node) {
return node.kind === 179 /* ElementAccessExpression */;
}n/a
function isEmptyObjectLiteralOrArrayLiteral(expression) {
var kind = expression.kind;
if (kind === 177 /* ObjectLiteralExpression */) {
return expression.properties.length === 0;
}
if (kind === 176 /* ArrayLiteralExpression */) {
return expression.elements.length === 0;
}
return false;
}n/a
function isEntityName(node) {
var kind = node.kind;
return kind === 142 /* QualifiedName */
|| kind === 70 /* Identifier */;
}n/a
function isEntityNameExpression(node) {
return node.kind === 70 /* Identifier */ ||
node.kind === 178 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression);
}n/a
function isEnumMember(node) {
return node.kind === 262 /* EnumMember */;
}n/a
function isExportDefaultSymbol(symbol) {
return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */);
}n/a
function isExportName(node) {
return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
}n/a
function isExportSpecifier(node) {
return node.kind === 245 /* ExportSpecifier */;
}n/a
function isExpression(node) {
return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
}n/a
function isExpressionOfExternalModuleImportEqualsDeclaration(node) {
return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) &&
ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node;
}n/a
function isExpressionWithTypeArguments(node) {
return node.kind === 200 /* ExpressionWithTypeArguments */;
}n/a
function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
}n/a
function isExternalModule(file) {
return file.externalModuleIndicator !== undefined;
}n/a
function isExternalModuleAugmentation(node) {
// external module augmentation is a ambient module declaration that is either:
// - defined in the top level scope and source file is an external module
// - defined inside ambient module declaration located in the top level scope and source file not an external module
if (!node || !isAmbientModule(node)) {
return false;
}
switch (node.parent.kind) {
case 263 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 233 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
}
return false;
}n/a
function isExternalModuleImportEqualsDeclaration(node) {
return node.kind === 236 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 247 /* ExternalModuleReference */;
}n/a
function isExternalModuleNameRelative(moduleName) {
// TypeScript 1.0 spec (April 2014): 11.2.1
// An external module name is "relative" if the first term is "." or "..".
return /^\.\.?($|[\\/])/.test(moduleName);
}n/a
function isExternalOrCommonJsModule(file) {
return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
}n/a
function isFirstDeclarationOfKind(node, kind) {
return node.symbol && getDeclarationOfKind(node.symbol, kind) === node;
}n/a
function isFirstDeclarationOfSymbolParameter(symbol) {
return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 145 /* Parameter */;
}n/a
function isForInitializer(node) {
return isVariableDeclarationList(node)
|| isExpression(node);
}n/a
function isFunctionBlock(node) {
return node && node.kind === 206 /* Block */ && isFunctionLike(node.parent);
}n/a
function isFunctionBody(node) {
return isBlock(node);
}n/a
function isFunctionLike(node) {
return node && isFunctionLikeKind(node.kind);
}n/a
function isFunctionLikeKind(kind) {
switch (kind) {
case 151 /* Constructor */:
case 185 /* FunctionExpression */:
case 227 /* FunctionDeclaration */:
case 186 /* ArrowFunction */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 154 /* CallSignature */:
case 155 /* ConstructSignature */:
case 156 /* IndexSignature */:
case 159 /* FunctionType */:
case 160 /* ConstructorType */:
return true;
}
return false;
}n/a
function isGeneratedIdentifier(node) {
// Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`.
return isIdentifier(node) && node.autoGenerateKind > 0 /* None */;
}n/a
function isGlobalScopeAugmentation(module) {
return !!(module.flags & 512 /* GlobalAugmentation */);
}n/a
function isHeritageClause(node) {
return node.kind === 257 /* HeritageClause */;
}n/a
function isIdentifier(node) {
return node.kind === 70 /* Identifier */;
}n/a
function isIdentifierName(node) {
var parent = node.parent;
switch (parent.kind) {
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 262 /* EnumMember */:
case 259 /* PropertyAssignment */:
case 178 /* PropertyAccessExpression */:
// Name in member declaration or property name in property access
return parent.name === node;
case 142 /* QualifiedName */:
// Name on right hand side of dot in a type query
if (parent.right === node) {
while (parent.kind === 142 /* QualifiedName */) {
parent = parent.parent;
}
return parent.kind === 161 /* TypeQuery */;
}
return false;
case 175 /* BindingElement */:
case 241 /* ImportSpecifier */:
// Property name in binding element or import specifier
return parent.propertyName === node;
case 245 /* ExportSpecifier */:
// Any name in an export specifier
return true;
}
return false;
}n/a
function isIdentifierPart(ch, languageVersion) {
return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
}n/a
function isIdentifierStart(ch, languageVersion) {
return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
ch === 36 /* $ */ || ch === 95 /* _ */ ||
ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
}n/a
function isIdentifierText(name, languageVersion) {
if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) {
return false;
}
for (var i = 1; i < name.length; i++) {
if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) {
return false;
}
}
return true;
}n/a
function isIdentifierTypePredicate(predicate) {
return predicate && predicate.kind === 1 /* Identifier */;
}n/a
function isImplicitGlob(lastPathComponent) {
return !/[.*?]/.test(lastPathComponent);
}n/a
function isImportClause(node) {
return node.kind === 238 /* ImportClause */;
}n/a
function isImportEqualsDeclaration(node) {
return node.kind === 236 /* ImportEqualsDeclaration */;
}n/a
function isImportOrExportSpecifierName(location) {
return location.parent &&
(location.parent.kind === 241 /* ImportSpecifier */ || location.parent.kind === 245 /* ExportSpecifier */) &&
location.parent.propertyName === location;
}n/a
function isImportSpecifier(node) {
return node.kind === 241 /* ImportSpecifier */;
}n/a
function isInAmbientContext(node) {
while (node) {
if (hasModifier(node, 2 /* Ambient */) || (node.kind === 263 /* SourceFile */ && node.isDeclarationFile)) {
return true;
}
node = node.parent;
}
return false;
}n/a
function isInComment(sourceFile, position) {
return isInCommentHelper(sourceFile, position, /*predicate*/ undefined);
}n/a
function isInCommentHelper(sourceFile, position, predicate) {
var token = getTokenAtPosition(sourceFile, position);
if (token && position <= token.getStart(sourceFile)) {
var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos);
// The end marker of a single-line comment does not include the newline character.
// In the following case, we are inside a comment (^ denotes the cursor position):
//
// // asdf ^\n
//
// But for multi-line comments, we don't want to be inside the comment in the following case:
//
// /* asdf */^
//
// Internally, we represent the end of the comment at the newline and closing '/', respectively.
return predicate ?
ts.forEach(commentRanges, function (c) { return c.pos < position &&
(c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) &&
predicate(c); }) :
ts.forEach(commentRanges, function (c) { return c.pos < position &&
(c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); });
}
return false;
}n/a
function isInJavaScriptFile(node) {
return node && !!(node.flags & 65536 /* JavaScriptFile */);
}n/a
function isInNonReferenceComment(sourceFile, position) {
return isInCommentHelper(sourceFile, position, isNonReferenceComment);
function isNonReferenceComment(c) {
var commentText = sourceFile.text.substring(c.pos, c.end);
return !tripleSlashDirectivePrefixRegex.test(commentText);
}
}n/a
function isInReferenceComment(sourceFile, position) {
return isInCommentHelper(sourceFile, position, isReferenceComment);
function isReferenceComment(c) {
var commentText = sourceFile.text.substring(c.pos, c.end);
return tripleSlashDirectivePrefixRegex.test(commentText);
}
}n/a
function isInString(sourceFile, position) {
var previousToken = findPrecedingToken(position, sourceFile);
if (previousToken && previousToken.kind === 9 /* StringLiteral */) {
var start = previousToken.getStart();
var end = previousToken.getEnd();
// To be "in" one of these literals, the position has to be:
// 1. entirely within the token text.
// 2. at the end position of an unterminated token.
// 3. at the end of a regular expression (due to trailing flags like '/foo/g').
if (start < position && position < end) {
return true;
}
if (position === end) {
return !!previousToken.isUnterminated;
}
}
return false;
}n/a
function isInTemplateString(sourceFile, position) {
var token = getTokenAtPosition(sourceFile, position);
return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile);
}n/a
function isInsideComment(sourceFile, token, position) {
// The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment
return position <= token.getStart(sourceFile) &&
(isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) ||
isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart())));
function isInsideCommentRange(comments) {
return ts.forEach(comments, function (comment) {
// either we are 1. completely inside the comment, or 2. at the end of the comment
if (comment.pos < position && position < comment.end) {
return true;
}
else if (position === comment.end) {
var text = sourceFile.text;
var width = comment.end - comment.pos;
// is single line comment or just /*
if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) {
return true;
}
else {
// is unterminated multi-line comment
return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ &&
text.charCodeAt(comment.end - 2) === 42 /* asterisk */);
}
}
return false;
});
}
}n/a
function isInsideJsxElementOrAttribute(sourceFile, position) {
var token = getTokenAtPosition(sourceFile, position);
if (!token) {
return false;
}
if (token.kind === 10 /* JsxText */) {
return true;
}
// <div>Hello |</div>
if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 10 /* JsxText */) {
return true;
}
// <div> { | </div> or <div a={| </div>
if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 254 /* JsxExpression */) {
return true;
}
// <div> {
// |
// } < /div>
if (token && token.kind === 17 /* CloseBraceToken */ && token.parent.kind === 254 /* JsxExpression */) {
return true;
}
// <div>|</div>
if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 251 /* JsxClosingElement */) {
return true;
}
return false;
}n/a
function isInsideTemplateLiteral(node, position) {
return ts.isTemplateLiteralKind(node.kind)
&& (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd());
}n/a
function isInstantiatedModule(node, preserveConstEnums) {
var moduleState = ts.getModuleInstanceState(node);
return moduleState === 1 /* Instantiated */ ||
(preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
}n/a
function isInternalModuleImportEqualsDeclaration(node) {
return node.kind === 236 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 247 /* ExternalModuleReference */;
}n/a
function isIntrinsicJsxName(name) {
var ch = name.substr(0, 1);
return ch.toLowerCase() === ch;
}n/a
function isIterationStatement(node, lookInLabeledStatements) {
switch (node.kind) {
case 213 /* ForStatement */:
case 214 /* ForInStatement */:
case 215 /* ForOfStatement */:
case 211 /* DoStatement */:
case 212 /* WhileStatement */:
return true;
case 221 /* LabeledStatement */:
return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
}
return false;
}n/a
function isJSDocConstructSignature(node) {
return node.kind === 277 /* JSDocFunctionType */ &&
node.parameters.length > 0 &&
node.parameters[0].type.kind === 279 /* JSDocConstructorType */;
}n/a
function isJSDocNamespaceBody(node) {
var kind = node.kind;
return kind === 70 /* Identifier */
|| kind === 232 /* ModuleDeclaration */;
}n/a
function isJSDocNode(node) {
return node.kind >= 265 /* FirstJSDocNode */ && node.kind <= 294 /* LastJSDocNode */;
}n/a
function isJSDocTag(node) {
return node.kind >= 281 /* FirstJSDocTagNode */ && node.kind <= 294 /* LastJSDocTagNode */;
}n/a
function isJSXTagName(node) {
var parent = node.parent;
if (parent.kind === 250 /* JsxOpeningElement */ ||
parent.kind === 249 /* JsxSelfClosingElement */ ||
parent.kind === 251 /* JsxClosingElement */) {
return parent.tagName === node;
}
return false;
}n/a
function isJsxAttribute(node) {
return node.kind === 252 /* JsxAttribute */;
}n/a
function isJsxAttributeLike(node) {
var kind = node.kind;
return kind === 252 /* JsxAttribute */
|| kind === 253 /* JsxSpreadAttribute */;
}n/a
function isJsxChild(node) {
var kind = node.kind;
return kind === 248 /* JsxElement */
|| kind === 254 /* JsxExpression */
|| kind === 249 /* JsxSelfClosingElement */
|| kind === 10 /* JsxText */;
}n/a
function isJsxClosingElement(node) {
return node.kind === 251 /* JsxClosingElement */;
}n/a
function isJsxOpeningElement(node) {
return node.kind === 250 /* JsxOpeningElement */;
}n/a
function isJsxSpreadAttribute(node) {
return node.kind === 253 /* JsxSpreadAttribute */;
}n/a
function isJsxTagNameExpression(node) {
var kind = node.kind;
return kind === 98 /* ThisKeyword */
|| kind === 70 /* Identifier */
|| kind === 178 /* PropertyAccessExpression */;
}n/a
function isJumpStatementTarget(node) {
return node.kind === 70 /* Identifier */ &&
(node.parent.kind === 217 /* BreakStatement */ || node.parent.kind === 216 /* ContinueStatement */) &&
node.parent.label === node;
}n/a
function isKeyword(token) {
return 71 /* FirstKeyword */ <= token && token <= 141 /* LastKeyword */;
}n/a
function isLabelName(node) {
return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}n/a
function isLeftHandSideExpression(node) {
return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
}n/a
function isLet(node) {
return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
}n/a
function isLineBreak(ch) {
// ES5 7.3:
// The ECMAScript line terminator characters are listed in Table 3.
// Table 3: Line Terminator Characters
// Code Unit Value Name Formal Name
// \u000A Line Feed <LF>
// \u000D Carriage Return <CR>
// \u2028 Line separator <LS>
// \u2029 Paragraph separator <PS>
// Only the characters in Table 3 are treated as line terminators. Other new line or line
// breaking characters are treated as white space but not as line terminators.
return ch === 10 /* lineFeed */ ||
ch === 13 /* carriageReturn */ ||
ch === 8232 /* lineSeparator */ ||
ch === 8233 /* paragraphSeparator */;
}n/a
function isLiteralComputedPropertyDeclarationName(node) {
return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) &&
node.parent.kind === 143 /* ComputedPropertyName */ &&
isDeclaration(node.parent.parent);
}n/a
function isLiteralExpression(node) {
return isLiteralKind(node.kind);
}n/a
function isLiteralKind(kind) {
return 8 /* FirstLiteralToken */ <= kind && kind <= 12 /* LastLiteralToken */;
}n/a
function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) {
if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) {
switch (node.parent.kind) {
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
case 259 /* PropertyAssignment */:
case 262 /* EnumMember */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 232 /* ModuleDeclaration */:
return node.parent.name === node;
case 179 /* ElementAccessExpression */:
return node.parent.argumentExpression === node;
case 143 /* ComputedPropertyName */:
return true;
}
}
return false;
}n/a
function isLocalName(node) {
return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
}n/a
function isLogicalOperator(token) {
return token === 53 /* BarBarToken */
|| token === 52 /* AmpersandAmpersandToken */
|| token === 50 /* ExclamationToken */;
}n/a
function isMergedWithClass(node) {
if (node.symbol) {
for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (declaration.kind === 228 /* ClassDeclaration */ && declaration !== node) {
return true;
}
}
}
return false;
}n/a
function isMethodDeclaration(node) {
return node.kind === 150 /* MethodDeclaration */;
}n/a
function isModifier(node) {
return isModifierKind(node.kind);
}n/a
function isModifierKind(token) {
switch (token) {
case 116 /* AbstractKeyword */:
case 119 /* AsyncKeyword */:
case 75 /* ConstKeyword */:
case 123 /* DeclareKeyword */:
case 78 /* DefaultKeyword */:
case 83 /* ExportKeyword */:
case 113 /* PublicKeyword */:
case 111 /* PrivateKeyword */:
case 112 /* ProtectedKeyword */:
case 130 /* ReadonlyKeyword */:
case 114 /* StaticKeyword */:
return true;
}
return false;
}n/a
function isModuleBody(node) {
var kind = node.kind;
return kind === 233 /* ModuleBlock */
|| kind === 232 /* ModuleDeclaration */
|| kind === 70 /* Identifier */;
}n/a
function isModuleName(node) {
var kind = node.kind;
return kind === 70 /* Identifier */
|| kind === 9 /* StringLiteral */;
}n/a
function isModuleOrEnumDeclaration(node) {
return node.kind === 232 /* ModuleDeclaration */ || node.kind === 231 /* EnumDeclaration */;
}n/a
function isModuleReference(node) {
var kind = node.kind;
return kind === 247 /* ExternalModuleReference */
|| kind === 142 /* QualifiedName */
|| kind === 70 /* Identifier */;
}n/a
function isNameOfFunctionDeclaration(node) {
return node.kind === 70 /* Identifier */ &&
ts.isFunctionLike(node.parent) && node.parent.name === node;
}n/a
function isNameOfModuleDeclaration(node) {
return node.parent.kind === 232 /* ModuleDeclaration */ && node.parent.name === node;
}n/a
function isNamedExports(node) {
return node.kind === 244 /* NamedExports */;
}n/a
function isNamedImportBindings(node) {
var kind = node.kind;
return kind === 240 /* NamedImports */
|| kind === 239 /* NamespaceImport */;
}n/a
function isNamespaceBody(node) {
var kind = node.kind;
return kind === 233 /* ModuleBlock */
|| kind === 232 /* ModuleDeclaration */;
}n/a
function isNewExpressionTarget(node) {
return isCallOrNewExpressionTarget(node, 181 /* NewExpression */);
}n/a
function isNoSubstitutionTemplateLiteral(node) {
return node.kind === 12 /* NoSubstitutionTemplateLiteral */;
}n/a
function isNodeArray(array) {
return array.hasOwnProperty("pos")
&& array.hasOwnProperty("end");
}n/a
function isNodeDescendantOf(node, ancestor) {
while (node) {
if (node === ancestor)
return true;
node = node.parent;
}
return false;
}n/a
function isNotEmittedOrPartiallyEmittedNode(node) {
return isNotEmittedStatement(node)
|| isPartiallyEmittedExpression(node);
}n/a
function isNotEmittedStatement(node) {
return node.kind === 296 /* NotEmittedStatement */;
}n/a
function isObjectBindingOrAssignmentPattern(node) {
switch (node.kind) {
case 173 /* ObjectBindingPattern */:
case 177 /* ObjectLiteralExpression */:
return true;
}
return false;
}n/a
function isObjectBindingPattern(node) {
return node.kind === 173 /* ObjectBindingPattern */;
}n/a
function isObjectLiteralElementLike(node) {
var kind = node.kind;
return kind === 259 /* PropertyAssignment */
|| kind === 260 /* ShorthandPropertyAssignment */
|| kind === 261 /* SpreadAssignment */
|| kind === 150 /* MethodDeclaration */
|| kind === 152 /* GetAccessor */
|| kind === 153 /* SetAccessor */
|| kind === 246 /* MissingDeclaration */;
}n/a
function isObjectLiteralExpression(node) {
return node.kind === 177 /* ObjectLiteralExpression */;
}n/a
function isObjectLiteralMethod(node) {
return node && node.kind === 150 /* MethodDeclaration */ && node.parent.kind === 177 /* ObjectLiteralExpression */;
}n/a
function isObjectLiteralOrClassExpressionMethod(node) {
return node.kind === 150 /* MethodDeclaration */ &&
(node.parent.kind === 177 /* ObjectLiteralExpression */ ||
node.parent.kind === 198 /* ClassExpression */);
}n/a
function isOctalDigit(ch) {
return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
}n/a
function isOmittedExpression(node) {
return node.kind === 199 /* OmittedExpression */;
}n/a
function isParameter(node) {
return node.kind === 145 /* Parameter */;
}n/a
function isParameterDeclaration(node) {
var root = getRootDeclaration(node);
return root.kind === 145 /* Parameter */;
}n/a
function isParameterPropertyDeclaration(node) {
return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 151 /* Constructor */ && ts.isClassLike
(node.parent.parent);
}n/a
function isParseTreeNode(node) {
return (node.flags & 8 /* Synthesized */) === 0;
}n/a
function isPartOfExpression(node) {
switch (node.kind) {
case 98 /* ThisKeyword */:
case 96 /* SuperKeyword */:
case 94 /* NullKeyword */:
case 100 /* TrueKeyword */:
case 85 /* FalseKeyword */:
case 11 /* RegularExpressionLiteral */:
case 176 /* ArrayLiteralExpression */:
case 177 /* ObjectLiteralExpression */:
case 178 /* PropertyAccessExpression */:
case 179 /* ElementAccessExpression */:
case 180 /* CallExpression */:
case 181 /* NewExpression */:
case 182 /* TaggedTemplateExpression */:
case 201 /* AsExpression */:
case 183 /* TypeAssertionExpression */:
case 202 /* NonNullExpression */:
case 184 /* ParenthesizedExpression */:
case 185 /* FunctionExpression */:
case 198 /* ClassExpression */:
case 186 /* ArrowFunction */:
case 189 /* VoidExpression */:
case 187 /* DeleteExpression */:
case 188 /* TypeOfExpression */:
case 191 /* PrefixUnaryExpression */:
case 192 /* PostfixUnaryExpression */:
case 193 /* BinaryExpression */:
case 194 /* ConditionalExpression */:
case 197 /* SpreadElement */:
case 195 /* TemplateExpression */:
case 12 /* NoSubstitutionTemplateLiteral */:
case 199 /* OmittedExpression */:
case 248 /* JsxElement */:
case 249 /* JsxSelfClosingElement */:
case 196 /* YieldExpression */:
case 190 /* AwaitExpression */:
case 203 /* MetaProperty */:
return true;
case 142 /* QualifiedName */:
while (node.parent.kind === 142 /* QualifiedName */) {
node = node.parent;
}
return node.parent.kind === 161 /* TypeQuery */ || isJSXTagName(node);
case 70 /* Identifier */:
if (node.parent.kind === 161 /* TypeQuery */ || isJSXTagName(node)) {
return true;
}
// fall through
case 8 /* NumericLiteral */:
case 9 /* StringLiteral */:
case 98 /* ThisKeyword */:
var parent = node.parent;
switch (parent.kind) {
case 225 /* VariableDeclaration */:
case 145 /* Parameter */:
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
case 262 /* EnumMember */:
case 259 /* PropertyAssignment */:
case 175 /* BindingElement */:
return parent.initializer === node;
case 209 /* ExpressionStatement */:
case 210 /* IfStatement */:
case 211 /* DoStatement */:
case 212 /* WhileStatement */:
case 218 /* ReturnStatement */:
case 219 /* WithStatement */:
case 220 /* SwitchStatement */:
case 255 /* CaseClause */:
case 222 /* ThrowStatement */:
case 220 /* SwitchStatement */:
return parent.expression === node;
case 213 /* ForStatement */:
var forStatement = parent;
return (forStatement.initializer === node && forStatement.initializer.kind !== 226 /* VariableDeclarationList
*/) ||
forStatement.condition === node ||
forStatement.incrementor === node;
case 214 /* ForInStatement */:
case 215 /* ForOfStatement */:
var forInStatement = parent;
return (forInStatement.initializer === node && forInStatement.initializer.kind !== 226 /* VariableDeclarationList
*/) ||
forInStatement.expression === node;
case 183 /* TypeAssertionExpression */:
case 201 /* AsExpression */:
return node === parent.expression;
case 204 /* TemplateSpan */:
return node === parent.expression;
case 143 /* C ...n/a
function isPartOfTypeNode(node) {
if (157 /* FirstTypeNode */ <= node.kind && node.kind <= 172 /* LastTypeNode */) {
return true;
}
switch (node.kind) {
case 118 /* AnyKeyword */:
case 132 /* NumberKeyword */:
case 135 /* StringKeyword */:
case 121 /* BooleanKeyword */:
case 136 /* SymbolKeyword */:
case 138 /* UndefinedKeyword */:
case 129 /* NeverKeyword */:
return true;
case 104 /* VoidKeyword */:
return node.parent.kind !== 189 /* VoidExpression */;
case 200 /* ExpressionWithTypeArguments */:
return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
// Identifiers and qualified names may be type nodes, depending on their context. Climb
// above them to find the lowest container
case 70 /* Identifier */:
// If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
if (node.parent.kind === 142 /* QualifiedName */ && node.parent.right === node) {
node = node.parent;
}
else if (node.parent.kind === 178 /* PropertyAccessExpression */ && node.parent.name === node) {
node = node.parent;
}
// At this point, node is either a qualified name or an identifier
ts.Debug.assert(node.kind === 70 /* Identifier */ || node.kind === 142 /* QualifiedName */ || node.kind === 178 /* PropertyAccessExpression
*/, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
case 142 /* QualifiedName */:
case 178 /* PropertyAccessExpression */:
case 98 /* ThisKeyword */:
var parent = node.parent;
if (parent.kind === 161 /* TypeQuery */) {
return false;
}
// Do not recursively call isPartOfTypeNode on the parent. In the example:
//
// let a: A.B.C;
//
// Calling isPartOfTypeNode would consider the qualified name A.B a type node. Only C or
// A.B.C is a type node.
if (157 /* FirstTypeNode */ <= parent.kind && parent.kind <= 172 /* LastTypeNode */) {
return true;
}
switch (parent.kind) {
case 200 /* ExpressionWithTypeArguments */:
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 144 /* TypeParameter */:
return node === parent.constraint;
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
case 145 /* Parameter */:
case 225 /* VariableDeclaration */:
return node === parent.type;
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
case 186 /* ArrowFunction */:
case 151 /* Constructor */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
return node === parent.type;
case 154 /* CallSignature */:
case 155 /* ConstructSignature */:
case 156 /* IndexSignature */:
return node === parent.type;
case 183 /* TypeAssertionExpression */:
return node === parent.type;
case 180 /* CallExpression */:
case 181 /* NewExpression */:
return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0;
case 182 /* TaggedTemplateExpression */:
// TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
return false;
}
}
return false;
}n/a
function isPartiallyEmittedExpression(node) {
return node.kind === 297 /* PartiallyEmittedExpression */;
}n/a
function isPrefixUnaryExpression(node) {
return node.kind === 191 /* PrefixUnaryExpression */;
}n/a
function isPrologueDirective(node) {
return node.kind === 209 /* ExpressionStatement */
&& node.expression.kind === 9 /* StringLiteral */;
}n/a
function isPropertyAccessExpression(node) {
return node.kind === 178 /* PropertyAccessExpression */;
}n/a
function isPropertyAssignment(node) {
return node.kind === 259 /* PropertyAssignment */;
}n/a
function isPropertyName(node) {
var kind = node.kind;
return kind === 70 /* Identifier */
|| kind === 9 /* StringLiteral */
|| kind === 8 /* NumericLiteral */
|| kind === 143 /* ComputedPropertyName */;
}n/a
function isPunctuation(kind) {
return 16 /* FirstPunctuation */ <= kind && kind <= 69 /* LastPunctuation */;
}n/a
function isPushOrUnshiftIdentifier(node) {
return node.text === "push" || node.text === "unshift";
}n/a
function isQualifiedName(node) {
return node.kind === 142 /* QualifiedName */;
}n/a
function isRequireCall(expression, checkArgumentIsStringLiteral) {
// of the form 'require("name")'
var isRequire = expression.kind === 180 /* CallExpression */ &&
expression.expression.kind === 70 /* Identifier */ &&
expression.expression.text === "require" &&
expression.arguments.length === 1;
return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9 /* StringLiteral */);
}n/a
function isRestParameter(node) {
if (node && (node.flags & 65536 /* JavaScriptFile */)) {
if (node.type && node.type.kind === 278 /* JSDocVariadicType */ ||
ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 278
/* JSDocVariadicType */; })) {
return true;
}
}
return isDeclaredRestParam(node);
}n/a
function isRightSideOfPropertyAccess(node) {
return node && node.parent && node.parent.kind === 178 /* PropertyAccessExpression */ && node.parent.name === node;
}n/a
function isRightSideOfQualifiedName(node) {
return node.parent.kind === 142 /* QualifiedName */ && node.parent.right === node;
}n/a
function isRightSideOfQualifiedNameOrPropertyAccess(node) {
return (node.parent.kind === 142 /* QualifiedName */ && node.parent.right === node) ||
(node.parent.kind === 178 /* PropertyAccessExpression */ && node.parent.name === node);
}n/a
function isRootedDiskPath(path) {
return getRootLength(path) !== 0;
}n/a
function isShorthandAmbientModuleSymbol(moduleSymbol) {
return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
}n/a
function isShorthandPropertyAssignment(node) {
return node.kind === 260 /* ShorthandPropertyAssignment */;
}n/a
function isSimpleExpression(node) {
return isSimpleExpressionWorker(node, 0);
}n/a
function isSingleOrDoubleQuote(charCode) {
return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
}n/a
function isSourceFile(node) {
return node.kind === 263 /* SourceFile */;
}n/a
function isSourceFileJavaScript(file) {
return isInJavaScriptFile(file);
}n/a
function isSpreadExpression(node) {
return node.kind === 197 /* SpreadElement */;
}n/a
function isStatement(node) {
var kind = node.kind;
return isStatementKindButNotDeclarationKind(kind)
|| isDeclarationStatementKind(kind)
|| kind === 206 /* Block */;
}n/a
function isStatementButNotDeclaration(node) {
return isStatementKindButNotDeclarationKind(node.kind);
}n/a
function isStatementWithLocals(node) {
switch (node.kind) {
case 206 /* Block */:
case 234 /* CaseBlock */:
case 213 /* ForStatement */:
case 214 /* ForInStatement */:
case 215 /* ForOfStatement */:
return true;
}
return false;
}n/a
function isStringLiteralOrJsxExpression(node) {
var kind = node.kind;
return kind === 9 /* StringLiteral */
|| kind === 254 /* JsxExpression */;
}n/a
function isStringOrNumericLiteral(node) {
var kind = node.kind;
return kind === 9 /* StringLiteral */
|| kind === 8 /* NumericLiteral */;
}n/a
function isStringOrRegularExpressionOrTemplateLiteral(kind) {
if (kind === 9 /* StringLiteral */
|| kind === 11 /* RegularExpressionLiteral */
|| ts.isTemplateLiteralKind(kind)) {
return true;
}
return false;
}n/a
function isSuperCall(n) {
return n.kind === 180 /* CallExpression */ && n.expression.kind === 96 /* SuperKeyword */;
}n/a
function isSuperProperty(node) {
var kind = node.kind;
return (kind === 178 /* PropertyAccessExpression */ || kind === 179 /* ElementAccessExpression */)
&& node.expression.kind === 96 /* SuperKeyword */;
}n/a
function isSupportedExpressionWithTypeArguments(node) {
return isSupportedExpressionWithTypeArgumentsRest(node.expression);
}n/a
function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
if (!fileName) {
return false;
}
for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) {
var extension = _a[_i];
if (fileExtensionIs(fileName, extension)) {
return true;
}
}
return false;
}n/a
function isTemplateHead(node) {
return node.kind === 13 /* TemplateHead */;
}n/a
function isTemplateLiteral(node) {
var kind = node.kind;
return kind === 195 /* TemplateExpression */
|| kind === 12 /* NoSubstitutionTemplateLiteral */;
}n/a
function isTemplateLiteralKind(kind) {
return 12 /* FirstTemplateToken */ <= kind && kind <= 15 /* LastTemplateToken */;
}n/a
function isTemplateMiddleOrTemplateTail(node) {
var kind = node.kind;
return kind === 14 /* TemplateMiddle */
|| kind === 15 /* TemplateTail */;
}n/a
function isTemplateSpan(node) {
return node.kind === 204 /* TemplateSpan */;
}n/a
function isTextualLiteralKind(kind) {
return kind === 9 /* StringLiteral */ || kind === 12 /* NoSubstitutionTemplateLiteral */;
}n/a
function isThis(node) {
switch (node.kind) {
case 98 /* ThisKeyword */:
// case SyntaxKind.ThisType: TODO: GH#9267
return true;
case 70 /* Identifier */:
// 'this' as a parameter
return ts.identifierIsThisKeyword(node) && node.parent.kind === 145 /* Parameter */;
default:
return false;
}
}n/a
function isThisIdentifier(node) {
return node && node.kind === 70 /* Identifier */ && identifierIsThisKeyword(node);
}n/a
function isThisTypePredicate(predicate) {
return predicate && predicate.kind === 0 /* This */;
}n/a
function isToken(n) {
return n.kind >= 0 /* FirstToken */ && n.kind <= 141 /* LastToken */;
}n/a
function isTraceEnabled(compilerOptions, host) {
return compilerOptions.traceResolution && host.trace !== undefined;
}n/a
function isTrivia(token) {
return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
}n/a
function isTypeKeyword(kind) {
switch (kind) {
case 118 /* AnyKeyword */:
case 121 /* BooleanKeyword */:
case 129 /* NeverKeyword */:
case 132 /* NumberKeyword */:
case 133 /* ObjectKeyword */:
case 135 /* StringKeyword */:
case 136 /* SymbolKeyword */:
case 104 /* VoidKeyword */:
return true;
default:
return false;
}
}n/a
function isTypeNode(node) {
return isTypeNodeKind(node.kind);
}n/a
function isTypeParameter(node) {
return node.kind === 144 /* TypeParameter */;
}n/a
function isUnaryExpression(node) {
return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
}n/a
function isUnicodeIdentifierStart(code, languageVersion) {
return languageVersion >= 1 /* ES5 */ ?
lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
lookupInUnicodeMap(code, unicodeES3IdentifierStart);
}n/a
function isUrl(path) {
return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1;
}n/a
function isVariableDeclaration(node) {
return node.kind === 225 /* VariableDeclaration */;
}n/a
function isVariableDeclarationList(node) {
return node.kind === 226 /* VariableDeclarationList */;
}n/a
function isVariableLike(node) {
if (node) {
switch (node.kind) {
case 175 /* BindingElement */:
case 262 /* EnumMember */:
case 145 /* Parameter */:
case 259 /* PropertyAssignment */:
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
case 260 /* ShorthandPropertyAssignment */:
case 225 /* VariableDeclaration */:
return true;
}
}
return false;
}n/a
function isVoidExpression(node) {
return node.kind === 189 /* VoidExpression */;
}n/a
function isWatchSet(options) {
// Firefox has Object.prototype.watch
return options.watch && options.hasOwnProperty("watch");
}n/a
function isWellKnownSymbolSyntactically(node) {
return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
}n/a
function isWhiteSpace(ch) {
return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
}n/a
function isWhiteSpaceSingleLine(ch) {
// Note: nextLine is in the Zs space, and should be considered to be a whitespace.
// It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
return ch === 32 /* space */ ||
ch === 9 /* tab */ ||
ch === 11 /* verticalTab */ ||
ch === 12 /* formFeed */ ||
ch === 160 /* nonBreakingSpace */ ||
ch === 133 /* nextLine */ ||
ch === 5760 /* ogham */ ||
ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
ch === 8239 /* narrowNoBreakSpace */ ||
ch === 8287 /* mathematicalSpace */ ||
ch === 12288 /* ideographicSpace */ ||
ch === 65279 /* byteOrderMark */;
}n/a
function isWord(kind) {
return kind === 70 /* Identifier */ || ts.isKeyword(kind);
}n/a
function keywordPart(kind) {
return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword);
}n/a
function lastOrUndefined(array) {
return array && array.length > 0
? array[array.length - 1]
: undefined;
}n/a
function length(array) {
return array ? array.length : 0;
}n/a
function liftToBlock(nodes) {
Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block.");
return ts.singleOrUndefined(nodes) || ts.createBlock(nodes);
}n/a
function lineBreakPart() {
return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak);
}n/a
function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2
, projectName, moduleName, globalCache);
}
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
var failedLookupLocations = [];
var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state);
return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations);
}n/a
function makeIdentifierFromModuleName(moduleName) {
return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
}n/a
function map(array, f) {
var result;
if (array) {
result = [];
for (var i = 0; i < array.length; i++) {
result.push(f(array[i], i));
}
}
return result;
}n/a
function mapEntries(map, f) {
if (!map) {
return undefined;
}
var result = createMap();
map.forEach(function (value, key) {
var _a = f(key, value), newKey = _a[0], newValue = _a[1];
result.set(newKey, newValue);
});
return result;
}n/a
function mapToDisplayParts(writeDisplayParts) {
writeDisplayParts(displayPartWriter);
var result = displayPartWriter.displayParts();
displayPartWriter.clear();
return result;
}n/a
function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) {
path = normalizePath(path);
currentDirectory = normalizePath(currentDirectory);
var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
var regexFlag = useCaseSensitiveFileNames ? "" : "i";
var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp
(pattern, regexFlag); });
var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag);
var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag);
// Associate an array of results with each include regex. This keeps results in order of the "include" order.
// If there are no "includes", then just put everything in results[0].
var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive;
for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
var basePath = _a[_i];
visitDirectory(basePath, combinePaths(currentDirectory, basePath));
}
return flatten(results);
function visitDirectory(path, absolutePath) {
var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
files = files.slice().sort(comparer);
directories = directories.slice().sort(comparer);
var _loop_1 = function (current) {
var name = combinePaths(path, current);
var absoluteName = combinePaths(absolutePath, current);
if (extensions && !fileExtensionIsAny(name, extensions))
return "continue";
if (excludeRegex && excludeRegex.test(absoluteName))
return "continue";
if (!includeFileRegexes) {
results[0].push(name);
}
else {
var includeIndex = findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
if (includeIndex !== -1) {
results[includeIndex].push(name);
}
}
};
for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
var current = files_1[_i];
_loop_1(current);
}
for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) {
var current = directories_1[_b];
var name = combinePaths(path, current);
var absoluteName = combinePaths(absolutePath, current);
if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
(!excludeRegex || !excludeRegex.test(absoluteName))) {
visitDirectory(name, absoluteName);
}
}
}
}n/a
function matchPatternOrExact(patternStrings, candidate) {
var patterns = [];
for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
var patternString = patternStrings_1[_i];
var pattern = tryParsePattern(patternString);
if (pattern) {
patterns.push(pattern);
}
else if (patternString === candidate) {
// pattern was matched as is - no need to search further
return patternString;
}
}
return findBestPatternMatch(patterns, function (_) { return _; }, candidate);
}n/a
function matchedText(pattern, candidate) {
Debug.assert(isPatternMatch(pattern, candidate));
return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
}n/a
function memoize(callback) {
var value;
return function () {
if (callback) {
value = callback();
callback = undefined;
}
return value;
};
}n/a
function mergeFunctionBodyLexicalEnvironment(body, declarations) {
if (body && declarations !== undefined && declarations.length > 0) {
if (ts.isBlock(body)) {
return ts.updateBlock(body, ts.setTextRange(ts.createNodeArray(ts.concatenate(body.statements, declarations)), body.
statements));
}
else {
return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray([ts.setTextRange(ts.createReturn(body), body
)].concat(declarations)), body),
/*multiLine*/ true),
/*location*/ body);
}
}
return body;
}n/a
function mergeLexicalEnvironment(statements, declarations) {
if (!ts.some(declarations)) {
return statements;
}
return ts.isNodeArray(statements)
? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements)
: ts.addRange(statements, declarations);
}n/a
function modifierToFlag(token) {
switch (token) {
case 114 /* StaticKeyword */: return 32 /* Static */;
case 113 /* PublicKeyword */: return 4 /* Public */;
case 112 /* ProtectedKeyword */: return 16 /* Protected */;
case 111 /* PrivateKeyword */: return 8 /* Private */;
case 116 /* AbstractKeyword */: return 128 /* Abstract */;
case 83 /* ExportKeyword */: return 1 /* Export */;
case 123 /* DeclareKeyword */: return 2 /* Ambient */;
case 75 /* ConstKeyword */: return 2048 /* Const */;
case 78 /* DefaultKeyword */: return 512 /* Default */;
case 119 /* AsyncKeyword */: return 256 /* Async */;
case 130 /* ReadonlyKeyword */: return 64 /* Readonly */;
}
return 0 /* None */;
}n/a
function moduleHasNonRelativeName(moduleName) {
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}n/a
function moduleResolutionIsEqualTo(oldResolution, newResolution) {
return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
oldResolution.extension === newResolution.extension &&
oldResolution.resolvedFileName === newResolution.resolvedFileName;
}n/a
function moveEmitHelpers(source, target, predicate) {
var sourceEmitNode = source.emitNode;
var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
if (!ts.some(sourceEmitHelpers))
return;
var targetEmitNode = getOrCreateEmitNode(target);
var helpersRemoved = 0;
for (var i = 0; i < sourceEmitHelpers.length; i++) {
var helper = sourceEmitHelpers[i];
if (predicate(helper)) {
helpersRemoved++;
if (!ts.contains(targetEmitNode.helpers, helper)) {
targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper);
}
}
else if (helpersRemoved > 0) {
sourceEmitHelpers[i - helpersRemoved] = helper;
}
}
if (helpersRemoved > 0) {
sourceEmitHelpers.length -= helpersRemoved;
}
}n/a
function movePos(pos, value) {
return ts.positionIsSynthesized(pos) ? -1 : pos + value;
}n/a
function moveRangeEnd(range, end) {
return createRange(range.pos, end);
}n/a
function moveRangePastDecorators(node) {
return node.decorators && node.decorators.length > 0
? moveRangePos(node, node.decorators.end)
: node;
}n/a
function moveRangePastModifiers(node) {
return node.modifiers && node.modifiers.length > 0
? moveRangePos(node, node.modifiers.end)
: moveRangePastDecorators(node);
}n/a
function moveRangePos(range, pos) {
return createRange(pos, range.end);
}n/a
function nodeCanBeDecorated(node) {
switch (node.kind) {
case 228 /* ClassDeclaration */:
// classes are valid targets
return true;
case 148 /* PropertyDeclaration */:
// property declarations are valid if their parent is a class declaration.
return node.parent.kind === 228 /* ClassDeclaration */;
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 150 /* MethodDeclaration */:
// if this method has a body and its parent is a class declaration, this is a valid target.
return node.body !== undefined
&& node.parent.kind === 228 /* ClassDeclaration */;
case 145 /* Parameter */:
// if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
return node.parent.body !== undefined
&& (node.parent.kind === 151 /* Constructor */
|| node.parent.kind === 150 /* MethodDeclaration */
|| node.parent.kind === 153 /* SetAccessor */)
&& node.parent.parent.kind === 228 /* ClassDeclaration */;
}
return false;
}n/a
function nodeIsDecorated(node) {
return node.decorators !== undefined
&& nodeCanBeDecorated(node);
}n/a
function nodeIsMissing(node) {
if (node === undefined) {
return true;
}
return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
}n/a
function nodeIsPresent(node) {
return !nodeIsMissing(node);
}n/a
function nodeIsSynthesized(node) {
return ts.positionIsSynthesized(node.pos)
|| ts.positionIsSynthesized(node.end);
}n/a
function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) {
return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, /* jsOnly*/ false);
}n/a
function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) {
if (jsOnly === void 0) { jsOnly = false; }
var containingDirectory = ts.getDirectoryPath(containingFile);
var traceEnabled = isTraceEnabled(compilerOptions, host);
var failedLookupLocations = [];
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript
));
if (result && result.value) {
var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport;
return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations);
}
return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
function tryResolve(extensions) {
var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName
(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); };
var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations
, state);
if (resolved) {
return toSearchResult({ resolved: resolved, isExternalLibraryImport: false });
}
if (moduleHasNonRelativeName(moduleName)) {
if (traceEnabled) {
trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[
extensions]);
}
var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state
, cache);
// For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate
files.
return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled
), extension: resolved_1.value.extension }, isExternalLibraryImport: true } };
}
else {
var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false
, state, /*considerPackageJson*/ true);
return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false });
}
}
}n/a
function nodeOrChildIsDecorated(node) {
return nodeIsDecorated(node) || childIsDecorated(node);
}n/a
function nodePosToString(node) {
var file = getSourceFileOfNode(node);
var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
}n/a
function nodeStartsNewLexicalEnvironment(node) {
var kind = node.kind;
return kind === 151 /* Constructor */
|| kind === 185 /* FunctionExpression */
|| kind === 227 /* FunctionDeclaration */
|| kind === 186 /* ArrowFunction */
|| kind === 150 /* MethodDeclaration */
|| kind === 152 /* GetAccessor */
|| kind === 153 /* SetAccessor */
|| kind === 232 /* ModuleDeclaration */
|| kind === 263 /* SourceFile */;
}n/a
function noop() { }n/a
function normalizePath(path) {
path = normalizeSlashes(path);
var rootLength = getRootLength(path);
var root = path.substr(0, rootLength);
var normalized = getNormalizedParts(path, rootLength);
if (normalized.length) {
var joinedParts = root + normalized.join(ts.directorySeparator);
return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts;
}
else {
return root;
}
}n/a
function normalizeSlashes(path) {
return path.replace(/\\/g, "/");
}n/a
function notImplemented() {
throw new Error("Not implemented");
}n/a
function operatorPart(kind) {
return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator);
}n/a
function orderedRemoveItem(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i] === item) {
orderedRemoveItemAt(array, i);
return true;
}
}
return false;
}n/a
function orderedRemoveItemAt(array, index) {
// This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
for (var i = index; i < array.length - 1; i++) {
array[i] = array[i + 1];
}
array.pop();
}n/a
function parameterIsThisKeyword(parameter) {
return isThisIdentifier(parameter.name);
}n/a
function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
var skipped = skipPartiallyEmittedExpressions(operand);
// If the resulting expression is already parenthesized, we do not need to do any further processing.
if (skipped.kind === 184 /* ParenthesizedExpression */) {
return operand;
}
return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
? ts.createParen(operand)
: operand;
}n/a
function parenthesizeConciseBody(body) {
var emittedBody = skipPartiallyEmittedExpressions(body);
if (emittedBody.kind === 177 /* ObjectLiteralExpression */) {
return ts.setTextRange(ts.createParen(body), body);
}
return body;
}n/a
function parenthesizeExpressionForExpressionStatement(expression) {
var emittedExpression = skipPartiallyEmittedExpressions(expression);
if (ts.isCallExpression(emittedExpression)) {
var callee = emittedExpression.expression;
var kind = skipPartiallyEmittedExpressions(callee).kind;
if (kind === 185 /* FunctionExpression */ || kind === 186 /* ArrowFunction */) {
var mutableCall = ts.getMutableClone(emittedExpression);
mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee);
return recreatePartiallyEmittedExpressions(expression, mutableCall);
}
}
else {
var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind;
if (leftmostExpressionKind === 177 /* ObjectLiteralExpression */ || leftmostExpressionKind === 185 /* FunctionExpression
*/) {
return ts.setTextRange(ts.createParen(expression), expression);
}
}
return expression;
}n/a
function parenthesizeExpressionForList(expression) {
var emittedExpression = skipPartiallyEmittedExpressions(expression);
var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
var commaPrecedence = ts.getOperatorPrecedence(193 /* BinaryExpression */, 25 /* CommaToken */);
return expressionPrecedence > commaPrecedence
? expression
: ts.setTextRange(ts.createParen(expression), expression);
}n/a
function parenthesizeForAccess(expression) {
// isLeftHandSideExpression is almost the correct criterion for when it is not necessary
// to parenthesize the expression before a dot. The known exceptions are:
//
// NewExpression:
// new C.x -> not the same as (new C).x
// NumericLiteral
// 1.x -> not the same as (1).x
//
var emittedExpression = skipPartiallyEmittedExpressions(expression);
if (ts.isLeftHandSideExpression(emittedExpression)
&& (emittedExpression.kind !== 181 /* NewExpression */ || emittedExpression.arguments)
&& emittedExpression.kind !== 8 /* NumericLiteral */) {
return expression;
}
return ts.setTextRange(ts.createParen(expression), expression);
}n/a
function parenthesizeForConditionalHead(condition) {
var conditionalPrecedence = ts.getOperatorPrecedence(194 /* ConditionalExpression */, 54 /* QuestionToken */);
var emittedCondition = skipPartiallyEmittedExpressions(condition);
var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) {
return ts.createParen(condition);
}
return condition;
}n/a
function parenthesizeForNew(expression) {
var emittedExpression = skipPartiallyEmittedExpressions(expression);
switch (emittedExpression.kind) {
case 180 /* CallExpression */:
return ts.createParen(expression);
case 181 /* NewExpression */:
return emittedExpression.arguments
? expression
: ts.createParen(expression);
}
return parenthesizeForAccess(expression);
}n/a
function parenthesizeListElements(elements) {
var result;
for (var i = 0; i < elements.length; i++) {
var element = parenthesizeExpressionForList(elements[i]);
if (result !== undefined || element !== elements[i]) {
if (result === undefined) {
result = elements.slice(0, i);
}
result.push(element);
}
}
if (result !== undefined) {
return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements);
}
return elements;
}n/a
function parenthesizePostfixOperand(operand) {
return ts.isLeftHandSideExpression(operand)
? operand
: ts.setTextRange(ts.createParen(operand), operand);
}n/a
function parenthesizePrefixOperand(operand) {
return ts.isUnaryExpression(operand)
? operand
: ts.setTextRange(ts.createParen(operand), operand);
}n/a
function parenthesizeSubexpressionOfConditionalExpression(e) {
// per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
// so in case when comma expression is introduced as a part of previous transformations
// if should be wrapped in parens since comma operator has the lowest precedence
return e.kind === 193 /* BinaryExpression */ && e.operatorToken.kind === 25 /* CommaToken */
? ts.createParen(e)
: e;
}n/a
function parseCommandLine(commandLine, readFile) {
var options = {};
var fileNames = [];
var errors = [];
var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames;
parseStrings(commandLine);
return {
options: options,
fileNames: fileNames,
errors: errors
};
function parseStrings(args) {
var i = 0;
while (i < args.length) {
var s = args[i];
i++;
if (s.charCodeAt(0) === 64 /* at */) {
parseResponseFile(s.slice(1));
}
else if (s.charCodeAt(0) === 45 /* minus */) {
s = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase();
// Try to translate short option names to their full equivalents.
var short = shortOptionNames.get(s);
if (short !== undefined) {
s = short;
}
var opt = optionNameMap.get(s);
if (opt) {
if (opt.isTSConfigOnly) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file
, opt.name));
}
else {
// Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
if (!args[i] && opt.type !== "boolean") {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name
));
}
switch (opt.type) {
case "number":
options[opt.name] = parseInt(args[i]);
i++;
break;
case "boolean":
// boolean flag has optional value true, false, others
var optValue = args[i];
options[opt.name] = optValue !== "false";
// consume next argument as boolean flag value
if (optValue === "false" || optValue === "true") {
i++;
}
break;
case "string":
options[opt.name] = args[i] || "";
i++;
break;
case "list":
var result = parseListTypeOption(opt, args[i], errors);
options[opt.name] = result || [];
if (result) {
i++;
}
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
i++;
break;
}
}
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s));
}
}
else {
fileNames.push(s);
}
}
}
function parseResponseFile(fileName) {
var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName);
if (!text) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName));
return;
}
var args = [];
var pos = 0;
while (true) {
while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
pos++;
if (pos >= text.length)
break; ...n/a
function parseConfigFileTextToJson(fileName, jsonText, stripComments) {
if (stripComments === void 0) { stripComments = true; }
try {
var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText;
return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} };
}
catch (e) {
return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) };
}
}n/a
function parseCustomTypeOption(opt, value, errors) {
return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
}n/a
function parseIsolatedEntityName(text, languageVersion) {
return Parser.parseIsolatedEntityName(text, languageVersion);
}n/a
function parseIsolatedJSDocComment(content, start, length) {
var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
if (result && result.jsDoc) {
// because the jsDocComment was parsed out of the source file, it might
// not be covered by the fixupParentReferences.
Parser.fixupParentReferences(result.jsDoc);
}
return result;
}n/a
function parseJSDocTypeExpressionForTests(content, start, length) {
return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
}n/a
function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) {
if (existingOptions === void 0) { existingOptions = {}; }
if (resolutionStack === void 0) { resolutionStack = []; }
if (extraFileExtensions === void 0) { extraFileExtensions = []; }
var errors = [];
basePath = ts.normalizeSlashes(basePath);
var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName);
if (resolutionStack.indexOf(resolvedPath) >= 0) {
return {
options: {},
fileNames: [],
typeAcquisition: {},
raw: json,
errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack
.concat([resolvedPath]).join(" -> "))],
wildcardDirectories: {}
};
}
var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName);
// typingOptions has been deprecated and is only supported for backward compatibility purposes.
// It should be removed in future releases - use typeAcquisition instead.
var jsonOptions = json["typeAcquisition"] || json["typingOptions"];
var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
if (json["extends"]) {
var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3];
if (typeof json["extends"] === "string") {
_b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseOptions]), include = _b[0], exclude = _b[1],
files = _b[2], baseOptions = _b[3];
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string
"));
}
if (include && !json["include"]) {
json["include"] = include;
}
if (exclude && !json["exclude"]) {
json["exclude"] = exclude;
}
if (files && !json["files"]) {
json["files"] = files;
}
options = ts.assign({}, baseOptions, options);
}
options = ts.extend(existingOptions, options);
options.configFilePath = configFileName;
var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories;
var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
return {
options: options,
fileNames: fileNames,
typeAcquisition: typeAcquisition,
raw: json,
errors: errors,
wildcardDirectories: wildcardDirectories,
compileOnSave: compileOnSave
};
function tryExtendsName(extendedConfig) {
// If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id
like paths in the future)
if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts
.normalizeSlashes(extendedConfig), "../"))) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not
, extendedConfig));
return;
}
var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName);
if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) {
extendedConfigPath = extendedConfigPath + ".json";
if (!host.fileExists(extendedConfigPath)) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig));
return;
}
}
var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
if (extendedResult.error) {
errors.push(extendedResult.error); ...n/a
function parseListTypeOption(opt, value, errors) {
if (value === void 0) { value = ""; }
value = trimString(value);
if (ts.startsWith(value, "-")) {
return undefined;
}
if (value === "") {
return [];
}
var values = value.split(",");
switch (opt.element.type) {
case "number":
return ts.map(values, parseInt);
case "string":
return ts.map(values, function (v) { return v || ""; });
default:
return ts.filter(ts.map(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }), function (v
) { return !!v; });
}
}n/a
function pathEndsWithDirectorySeparator(path) {
return path.charCodeAt(path.length - 1) === directorySeparatorCharCode;
}n/a
function patternText(_a) {
var prefix = _a.prefix, suffix = _a.suffix;
return prefix + "*" + suffix;
}n/a
function positionBelongsToNode(candidate, position, sourceFile) {
return candidate.end > position || !isCompletedNode(candidate, sourceFile);
}n/a
function positionIsSynthesized(pos) {
// This is a fast way of testing the following conditions:
// pos === undefined || pos === null || isNaN(pos) || pos < 0;
return !(pos >= 0);
}n/a
function positionsAreOnSameLine(pos1, pos2, sourceFile) {
return pos1 === pos2 ||
getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2);
}n/a
function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
if (readImportFiles === void 0) { readImportFiles = true; }
if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; }
var referencedFiles = [];
var typeReferenceDirectives = [];
var importedFiles = [];
var ambientExternalModules;
var isNoDefaultLib = false;
var braceNesting = 0;
// assume that text represent an external module if it contains at least one top level import/export
// ambient modules that are found inside external modules are interpreted as module augmentations
var externalModule = false;
function nextToken() {
var token = ts.scanner.scan();
if (token === 16 /* OpenBraceToken */) {
braceNesting++;
}
else if (token === 17 /* CloseBraceToken */) {
braceNesting--;
}
return token;
}
function processTripleSlashDirectives() {
var commentRanges = ts.getLeadingCommentRanges(sourceText, 0);
ts.forEach(commentRanges, function (commentRange) {
var comment = sourceText.substring(commentRange.pos, commentRange.end);
var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange);
if (referencePathMatchResult) {
isNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
var fileReference = referencePathMatchResult.fileReference;
if (fileReference) {
var collection = referencePathMatchResult.isTypeReferenceDirective
? typeReferenceDirectives
: referencedFiles;
collection.push(fileReference);
}
}
});
}
function getFileReference() {
var file = ts.scanner.getTokenValue();
var pos = ts.scanner.getTokenPos();
return {
fileName: file,
pos: pos,
end: pos + file.length
};
}
function recordAmbientExternalModule() {
if (!ambientExternalModules) {
ambientExternalModules = [];
}
ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting });
}
function recordModuleName() {
importedFiles.push(getFileReference());
markAsExternalModuleIfTopLevel();
}
function markAsExternalModuleIfTopLevel() {
if (braceNesting === 0) {
externalModule = true;
}
}
/**
* Returns true if at least one token was consumed from the stream
*/
function tryConsumeDeclare() {
var token = ts.scanner.getToken();
if (token === 123 /* DeclareKeyword */) {
// declare module "mod"
token = nextToken();
if (token === 127 /* ModuleKeyword */) {
token = nextToken();
if (token === 9 /* StringLiteral */) {
recordAmbientExternalModule();
}
}
return true;
}
return false;
}
/**
* Returns true if at least one token was consumed from the stream
*/
function tryConsumeImport() {
var token = ts.scanner.getToken();
if (token === 90 /* ImportKeyword */) {
token = nextToken();
if (token === 9 /* StringLiteral */) {
// import "mod";
recordModuleName();
return true;
}
else {
if (token === 70 /* Identifier */ || ts.isKeyword(token)) {
token = nextToken();
if (token === 139 /* FromKeyword */) {
token = nextToken();
if (token === 9 /* StringLiteral */) {
// import d from "mod";
recordModuleName();
return true;
}
}
else if (token === 57 /* EqualsToken */) { ...n/a
function punctuationPart(kind) {
return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation);
}n/a
function rangeContainsRange(r1, r2) {
return startEndContainsRange(r1.pos, r1.end, r2);
}n/a
function rangeContainsStartEnd(range, start, end) {
return range.pos <= start && range.end >= end;
}n/a
function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile);
}n/a
function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
}n/a
function rangeEquals(array1, array2, pos, end) {
while (pos < end) {
if (array1[pos] !== array2[pos]) {
return false;
}
pos++;
}
return true;
}n/a
function rangeIsOnSingleLine(range, sourceFile) {
return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
}n/a
function rangeOverlapsWithStartEnd(r1, start, end) {
return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end);
}n/a
function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile);
}n/a
function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile
);
}n/a
function readConfigFile(fileName, readFile) {
var text = "";
try {
text = readFile(fileName);
}
catch (e) {
return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) };
}
return parseConfigFileTextToJson(fileName, text);
}n/a
function realizeDiagnostics(diagnostics, newLine) {
return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); });
}n/a
function reduceEachChild(node, initial, cbNode, cbNodeArray) {
if (node === undefined) {
return initial;
}
var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft;
var cbNodes = cbNodeArray || cbNode;
var kind = node.kind;
// No need to visit nodes with no children.
if ((kind > 0 /* FirstToken */ && kind <= 141 /* LastToken */)) {
return initial;
}
// We do not yet support types.
if ((kind >= 157 /* TypePredicate */ && kind <= 172 /* LiteralType */)) {
return initial;
}
var result = initial;
switch (node.kind) {
// Leaf nodes
case 205 /* SemicolonClassElement */:
case 208 /* EmptyStatement */:
case 199 /* OmittedExpression */:
case 224 /* DebuggerStatement */:
case 296 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
case 142 /* QualifiedName */:
result = reduceNode(node.left, cbNode, result);
result = reduceNode(node.right, cbNode, result);
break;
case 143 /* ComputedPropertyName */:
result = reduceNode(node.expression, cbNode, result);
break;
// Signature elements
case 145 /* Parameter */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.initializer, cbNode, result);
break;
case 146 /* Decorator */:
result = reduceNode(node.expression, cbNode, result);
break;
// Type member
case 148 /* PropertyDeclaration */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.initializer, cbNode, result);
break;
case 150 /* MethodDeclaration */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
result = reduceNodes(node.typeParameters, cbNodes, result);
result = reduceNodes(node.parameters, cbNodes, result);
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.body, cbNode, result);
break;
case 151 /* Constructor */:
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNodes(node.parameters, cbNodes, result);
result = reduceNode(node.body, cbNode, result);
break;
case 152 /* GetAccessor */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
result = reduceNodes(node.parameters, cbNodes, result);
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.body, cbNode, result);
break;
case 153 /* SetAccessor */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
result = reduceNodes(node.parameters, cbNodes, result);
result = reduceNode(node.body, cbNode, result);
break;
// Binding patterns
case 173 /* ObjectBindingPattern */:
case 174 /* ArrayBindingPattern */:
result = reduceNodes(node.elements, cbNodes, result);
break;
case 175 /* BindingElement */:
result = reduceNode(node.propertyName, cbNode, result);
result = reduceNode(node ...n/a
function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
}n/a
function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
}n/a
function reduceLeft(array, f, initial, start, count) {
if (array && array.length > 0) {
var size = array.length;
if (size > 0) {
var pos = start === undefined || start < 0 ? 0 : start;
var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
var result = void 0;
if (arguments.length <= 2) {
result = array[pos];
pos++;
}
else {
result = initial;
}
while (pos <= end) {
result = f(result, array[pos], pos);
pos++;
}
return result;
}
}
return initial;
}n/a
function reduceRight(array, f, initial, start, count) {
if (array) {
var size = array.length;
if (size > 0) {
var pos = start === undefined || start > size - 1 ? size - 1 : start;
var end = count === undefined || pos - count < 0 ? 0 : pos - count;
var result = void 0;
if (arguments.length <= 2) {
result = array[pos];
pos--;
}
else {
result = initial;
}
while (pos >= end) {
result = f(result, array[pos], pos);
pos--;
}
return result;
}
}
return initial;
}n/a
function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) {
if (comparer === void 0) { comparer = compareValues; }
if (offsetA === void 0) { offsetA = 0; }
if (offsetB === void 0) { offsetB = 0; }
if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
return arrayB;
var result = [];
outer: for (; offsetB < arrayB.length; offsetB++) {
inner: for (; offsetA < arrayA.length; offsetA++) {
switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
case -1 /* LessThan */: break inner;
case 0 /* EqualTo */: continue outer;
case 1 /* GreaterThan */: continue inner;
}
}
result.push(arrayB[offsetB]);
}
return result;
}n/a
function releaseStringWriter(writer) {
writer.clear();
stringWriters.push(writer);
}n/a
function removeEmitHelper(node, helper) {
var emitNode = node.emitNode;
if (emitNode) {
var helpers = emitNode.helpers;
if (helpers) {
return ts.orderedRemoveItem(helpers, helper);
}
}
return false;
}n/a
function removeExtension(path, extension) {
return path.substring(0, path.length - extension.length);
}n/a
function removeFileExtension(path) {
for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
var ext = extensionsToRemove_1[_i];
var extensionless = tryRemoveExtension(path, ext);
if (extensionless !== undefined) {
return extensionless;
}
}
return path;
}n/a
function removeTrailingDirectorySeparator(path) {
if (path.charAt(path.length - 1) === ts.directorySeparator) {
return path.substr(0, path.length - 1);
}
return path;
}n/a
function removeWhere(array, f) {
var outIndex = 0;
for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
var item = array_2[_i];
if (!f(item)) {
array[outIndex] = item;
outIndex++;
}
}
if (outIndex !== array.length) {
array.length = outIndex;
return true;
}
return false;
}n/a
function replaceElement(array, index, value) {
var result = array.slice(0);
result[index] = value;
return result;
}n/a
function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
}
var containingDirectory = ts.getDirectoryPath(containingFile);
var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
var result = perFolderCache && perFolderCache.get(moduleName);
if (result) {
if (traceEnabled) {
trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
}
}
else {
var moduleResolution = compilerOptions.moduleResolution;
if (moduleResolution === undefined) {
moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs
: ts.ModuleResolutionKind.Classic;
if (traceEnabled) {
trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution
]);
}
}
else {
if (traceEnabled) {
trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution
]);
}
}
switch (moduleResolution) {
case ts.ModuleResolutionKind.NodeJs:
result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache);
break;
case ts.ModuleResolutionKind.Classic:
result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache);
break;
}
if (perFolderCache) {
perFolderCache.set(moduleName, result);
// put result in per-module name cache
var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName);
if (perModuleNameCache) {
perModuleNameCache.set(containingDirectory, result);
}
}
}
if (traceEnabled) {
if (result.resolvedModule) {
trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName
);
}
else {
trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
}
}
return result;
}n/a
function resolveTripleslashReference(moduleName, containingFile) {
var basePath = ts.getDirectoryPath(containingFile);
var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
return ts.normalizePath(referencedFileName);
}n/a
function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
var traceEnabled = isTraceEnabled(options, host);
var moduleResolutionState = {
compilerOptions: options,
host: host,
traceEnabled: traceEnabled
};
var typeRoots = getEffectiveTypeRoots(options, host);
if (traceEnabled) {
if (containingFile === undefined) {
if (typeRoots === undefined) {
trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set,
typeReferenceDirectiveName);
}
else {
trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName
, typeRoots);
}
}
else {
if (typeRoots === undefined) {
trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName
, containingFile);
}
else {
trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName
, containingFile, typeRoots);
}
}
}
var failedLookupLocations = [];
var resolved = primaryLookup();
var primary = true;
if (!resolved) {
resolved = secondaryLookup();
primary = false;
}
var resolvedTypeReferenceDirective;
if (resolved) {
resolved = realpath(resolved, host, traceEnabled);
if (traceEnabled) {
trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName
, resolved, primary);
}
resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved };
}
return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
function primaryLookup() {
// Check primary library paths
if (typeRoots && typeRoots.length) {
if (traceEnabled) {
trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
}
return ts.forEach(typeRoots, function (typeRoot) {
var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
var candidateDirectory = ts.getDirectoryPath(candidate);
var directoryExists = directoryProbablyExists(candidateDirectory, host);
if (!directoryExists && traceEnabled) {
trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
}
return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !
directoryExists, moduleResolutionState));
});
}
else {
if (traceEnabled) {
trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
}
}
}
function secondaryLookup() {
var resolvedFile;
var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
if (initialLocationForSecondaryLookup !== undefined) {
// check secondary locations
if (traceEnabled) {
trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup
);
}
var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup
, failedLookupLocations, moduleResolutionState, /*cache*/ undefined);
resolvedFile = resolvedTypeScriptOnly(result && result.value);
if (!resolvedFile && traceEnabled) {
trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
} ...n/a
function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
if (!outermostLabeledStatement) {
return node;
}
var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement
.kind === 221 /* LabeledStatement */
? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
: node);
if (afterRestoreLabelCallback) {
afterRestoreLabelCallback(outermostLabeledStatement);
}
return updated;
}n/a
function sameMap(array, f) {
var result;
if (array) {
for (var i = 0; i < array.length; i++) {
if (result) {
result.push(f(array[i], i));
}
else {
var item = array[i];
var mapped = f(item, i);
if (item !== mapped) {
result = array.slice(0, i);
result.push(mapped);
}
}
}
}
return result || array;
}n/a
function sanitizeConfigFile(configFileName, content) {
var options = {
fileName: "config.js",
compilerOptions: {
target: 2 /* ES2015 */,
removeComments: true
},
reportDiagnostics: true
};
var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics;
// Becasue the content was wrapped in "()", the start position of diagnostics needs to be subtract by 1
// also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these
// as well
var trimmedOutput = outputText.trim();
for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
var diagnostic = diagnostics_2[_i];
diagnostic.start = diagnostic.start - 1;
}
var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/
false), config = _b.config, error = _b.error;
return {
configJsonObject: config || {},
diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics
};
}n/a
function scriptKindIs(fileName, host) {
var scriptKinds = [];
for (var _i = 2; _i < arguments.length; _i++) {
scriptKinds[_i - 2] = arguments[_i];
}
var scriptKind = getScriptKind(fileName, host);
return ts.forEach(scriptKinds, function (k) { return k === scriptKind; });
}n/a
function setCommentRange(node, range) {
getOrCreateEmitNode(node).commentRange = range;
return node;
}n/a
function setConstantValue(node, value) {
var emitNode = getOrCreateEmitNode(node);
emitNode.constantValue = value;
return node;
}n/a
function setEmitFlags(node, emitFlags) {
getOrCreateEmitNode(node).flags = emitFlags;
return node;
}n/a
function setOriginalNode(node, original) {
node.original = original;
if (original) {
var emitNode = original.emitNode;
if (emitNode)
node.emitNode = mergeEmitNode(emitNode, node.emitNode);
}
return node;
}n/a
function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
if (!sourceFile.resolvedModules) {
sourceFile.resolvedModules = ts.createMap();
}
sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
}n/a
function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
}
sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
}n/a
function setSourceMapRange(node, range) {
getOrCreateEmitNode(node).sourceMapRange = range;
return node;
}n/a
function setTextRange(range, location) {
if (location) {
range.pos = location.pos;
range.end = location.end;
}
return range;
}n/a
function setTokenSourceMapRange(node, token, range) {
var emitNode = getOrCreateEmitNode(node);
var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []);
tokenSourceMapRanges[token] = range;
return node;
}n/a
function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) {
return mapToDisplayParts(function (writer) {
typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags);
});
}n/a
function singleOrMany(array) {
return array && array.length === 1
? array[0]
: array;
}n/a
function singleOrUndefined(array) {
return array && array.length === 1
? array[0]
: undefined;
}n/a
function skipAssertions(node) {
while (ts.isAssertionExpression(node)) {
node = node.expression;
}
return node;
}n/a
function skipOuterExpressions(node, kinds) {
if (kinds === void 0) { kinds = 7 /* All */; }
var previousNode;
do {
previousNode = node;
if (kinds & 1 /* Parentheses */) {
node = skipParentheses(node);
}
if (kinds & 2 /* Assertions */) {
node = skipAssertions(node);
}
if (kinds & 4 /* PartiallyEmittedExpressions */) {
node = skipPartiallyEmittedExpressions(node);
}
} while (previousNode !== node);
return node;
}n/a
function skipParentheses(node) {
while (node.kind === 184 /* ParenthesizedExpression */) {
node = node.expression;
}
return node;
}n/a
function skipPartiallyEmittedExpressions(node) {
while (node.kind === 297 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
}n/a
function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
if (stopAtComments === void 0) { stopAtComments = false; }
if (ts.positionIsSynthesized(pos)) {
return pos;
}
// Keep in sync with couldStartTrivia
while (true) {
var ch = text.charCodeAt(pos);
switch (ch) {
case 13 /* carriageReturn */:
if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
pos++;
}
case 10 /* lineFeed */:
pos++;
if (stopAfterLineBreak) {
return pos;
}
continue;
case 9 /* tab */:
case 11 /* verticalTab */:
case 12 /* formFeed */:
case 32 /* space */:
pos++;
continue;
case 47 /* slash */:
if (stopAtComments) {
break;
}
if (text.charCodeAt(pos + 1) === 47 /* slash */) {
pos += 2;
while (pos < text.length) {
if (isLineBreak(text.charCodeAt(pos))) {
break;
}
pos++;
}
continue;
}
if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
pos += 2;
while (pos < text.length) {
if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
pos += 2;
break;
}
pos++;
}
continue;
}
break;
case 60 /* lessThan */:
case 61 /* equals */:
case 62 /* greaterThan */:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos);
continue;
}
break;
case 35 /* hash */:
if (pos === 0 && isShebangTrivia(text, pos)) {
pos = scanShebangTrivia(text, pos);
continue;
}
break;
default:
if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpace(ch))) {
pos++;
continue;
}
break;
}
return pos;
}
}n/a
function some(array, predicate) {
if (array) {
if (predicate) {
for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
var v = array_5[_i];
if (predicate(v)) {
return true;
}
}
}
else {
return array.length > 0;
}
}
return false;
}n/a
function sortAndDeduplicateDiagnostics(diagnostics) {
return deduplicateSortedDiagnostics(diagnostics.sort(compareDiagnostics));
}n/a
function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) {
return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary
(sourceFile);
}n/a
function spacePart() {
return displayPart(" ", ts.SymbolDisplayPartKind.space);
}n/a
function span(array, f) {
if (array) {
for (var i = 0; i < array.length; i++) {
if (!f(array[i], i)) {
return [array.slice(0, i), array.slice(i)];
}
}
return [array.slice(0), []];
}
return undefined;
}n/a
function spanMap(array, keyfn, mapfn) {
var result;
if (array) {
result = [];
var len = array.length;
var previousKey = void 0;
var key = void 0;
var start = 0;
var pos = 0;
while (start < len) {
while (pos < len) {
var value = array[pos];
key = keyfn(value, pos);
if (pos === 0) {
previousKey = key;
}
else if (key !== previousKey) {
break;
}
pos++;
}
if (start < pos) {
var v = mapfn(array.slice(start, pos), previousKey, start, pos);
if (v) {
result.push(v);
}
start = pos;
}
previousKey = key;
pos++;
}
}
return result;
}n/a
function stableSort(array, comparer) {
if (comparer === void 0) { comparer = compareValues; }
return array
.map(function (_, i) { return i; }) // create array of indices
.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) // sort indices by value then position
.map(function (i) { return array[i]; }); // get sorted array
}n/a
function startEndContainsRange(start, end, range) {
return start <= range.pos && end >= range.end;
}n/a
function startEndOverlapsWithStartEnd(start1, end1, start2, end2) {
var start = Math.max(start1, start2);
var end = Math.min(end1, end2);
return start < end;
}n/a
function startOnNewLine(node) {
node.startsOnNewLine = true;
return node;
}n/a
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}n/a
function startsWithUseStrict(statements) {
var firstStatement = ts.firstOrUndefined(statements);
return firstStatement !== undefined
&& ts.isPrologueDirective(firstStatement)
&& isUseStrictPrologue(firstStatement);
}n/a
function stringToToken(s) {
return textToToken.get(s);
}n/a
function stripQuotes(name) {
var length = name.length;
if (length >= 2 &&
name.charCodeAt(0) === name.charCodeAt(length - 1) &&
(name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) {
return name.substring(1, length - 1);
}
;
return name;
}n/a
function sum(array, prop) {
var result = 0;
for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
var v = array_7[_i];
result += v[prop];
}
return result;
}n/a
function symbolPart(text, symbol) {
return displayPart(text, displayPartKind(symbol));
function displayPartKind(symbol) {
var flags = symbol.flags;
if (flags & 3 /* Variable */) {
return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind
.localName;
}
else if (flags & 4 /* Property */) {
return ts.SymbolDisplayPartKind.propertyName;
}
else if (flags & 32768 /* GetAccessor */) {
return ts.SymbolDisplayPartKind.propertyName;
}
else if (flags & 65536 /* SetAccessor */) {
return ts.SymbolDisplayPartKind.propertyName;
}
else if (flags & 8 /* EnumMember */) {
return ts.SymbolDisplayPartKind.enumMemberName;
}
else if (flags & 16 /* Function */) {
return ts.SymbolDisplayPartKind.functionName;
}
else if (flags & 32 /* Class */) {
return ts.SymbolDisplayPartKind.className;
}
else if (flags & 64 /* Interface */) {
return ts.SymbolDisplayPartKind.interfaceName;
}
else if (flags & 384 /* Enum */) {
return ts.SymbolDisplayPartKind.enumName;
}
else if (flags & 1536 /* Module */) {
return ts.SymbolDisplayPartKind.moduleName;
}
else if (flags & 8192 /* Method */) {
return ts.SymbolDisplayPartKind.methodName;
}
else if (flags & 262144 /* TypeParameter */) {
return ts.SymbolDisplayPartKind.typeParameterName;
}
else if (flags & 524288 /* TypeAlias */) {
return ts.SymbolDisplayPartKind.aliasName;
}
else if (flags & 8388608 /* Alias */) {
return ts.SymbolDisplayPartKind.aliasName;
}
return ts.SymbolDisplayPartKind.text;
}
}n/a
function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) {
return mapToDisplayParts(function (writer) {
typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags);
});
}n/a
function textChangeRangeIsUnchanged(range) {
return textSpanIsEmpty(range.span) && range.newLength === 0;
}n/a
function textChangeRangeNewSpan(range) {
return createTextSpan(range.span.start, range.newLength);
}n/a
function textOrKeywordPart(text) {
var kind = ts.stringToToken(text);
return kind === undefined
? textPart(text)
: keywordPart(kind);
}n/a
function textPart(text) {
return displayPart(text, ts.SymbolDisplayPartKind.text);
}n/a
function textSpanContainsPosition(span, position) {
return position >= span.start && position < textSpanEnd(span);
}n/a
function textSpanContainsTextSpan(span, other) {
return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
}n/a
function textSpanEnd(span) {
return span.start + span.length;
}n/a
function textSpanIntersection(span1, span2) {
var intersectStart = Math.max(span1.start, span2.start);
var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2));
if (intersectStart <= intersectEnd) {
return createTextSpanFromBounds(intersectStart, intersectEnd);
}
return undefined;
}n/a
function textSpanIntersectsWith(span, start, length) {
var end = start + length;
return start <= textSpanEnd(span) && end >= span.start;
}n/a
function textSpanIntersectsWithPosition(span, position) {
return position <= textSpanEnd(span) && position >= span.start;
}n/a
function textSpanIntersectsWithTextSpan(span, other) {
return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start;
}n/a
function textSpanIsEmpty(span) {
return span.length === 0;
}n/a
function textSpanOverlap(span1, span2) {
var overlapStart = Math.max(span1.start, span2.start);
var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2));
if (overlapStart < overlapEnd) {
return createTextSpanFromBounds(overlapStart, overlapEnd);
}
return undefined;
}n/a
function textSpanOverlapsWith(span, other) {
var overlapStart = Math.max(span.start, other.start);
var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other));
return overlapStart < overlapEnd;
}n/a
function now() { [native code] }n/a
function toEditorSettings(optionsAsMap) {
var allPropertiesAreCamelCased = true;
for (var key in optionsAsMap) {
if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) {
allPropertiesAreCamelCased = false;
break;
}
}
if (allPropertiesAreCamelCased) {
return optionsAsMap;
}
var settings = {};
for (var key in optionsAsMap) {
if (ts.hasProperty(optionsAsMap, key)) {
var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1);
settings[newKey] = optionsAsMap[key];
}
}
return settings;
}n/a
function toPath(fileName, basePath, getCanonicalFileName) {
var nonCanonicalizedPath = isRootedDiskPath(fileName)
? normalizePath(fileName)
: getNormalizedAbsolutePath(fileName, basePath);
return getCanonicalFileName(nonCanonicalizedPath);
}n/a
function tokenIsIdentifierOrKeyword(token) {
return token >= 70 /* Identifier */;
}n/a
function tokenToString(t) {
return tokenStrings[t];
}n/a
function trace(host) {
host.trace(ts.formatMessage.apply(undefined, arguments));
}n/a
function transformES2015(context) {
var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment,
endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
var resolver = context.getEmitResolver();
var previousOnSubstituteNode = context.onSubstituteNode;
var previousOnEmitNode = context.onEmitNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
var currentSourceFile;
var currentText;
var hierarchyFacts;
/**
* Used to track if we are emitting body of the converted loop
*/
var convertedLoopState;
/**
* Keeps track of whether substitutions have been enabled for specific cases.
* They are persisted between each SourceFile transformation and should not
* be reset.
*/
var enabledSubstitutions;
return transformSourceFile;
function transformSourceFile(node) {
if (ts.isDeclarationFile(node)) {
return node;
}
currentSourceFile = node;
currentText = node.text;
var visited = visitSourceFile(node);
ts.addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
currentText = undefined;
hierarchyFacts = 0 /* None */;
return visited;
}
/**
* Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification
.
* @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
* @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
**/
function enterSubtree(excludeFacts, includeFacts) {
var ancestorFacts = hierarchyFacts;
hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
return ancestorFacts;
}
/**
* Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
* subtree, propagating specific facts from the subtree.
* @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
* @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
* @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
**/
function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
}
function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
return hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */
&& node.kind === 218 /* ReturnStatement */
&& !node.expression;
}
function shouldVisitNode(node) {
return (node.transformFlags & 128 /* ContainsES2015 */) !== 0
|| convertedLoopState !== undefined
|| (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && ts.isStatement(node))
|| (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node));
}
function visitor(node) {
if (shouldVisitNode(node)) {
return visitJavaScript(node);
}
else {
return node;
}
}
function functionBodyVisitor(node) {
if (shouldVisitNode(node)) {
return visitBlock(node, /*isFunctionBody*/ true);
}
return node;
}
function callExpressionVisitor(node) {
if (node.kind === 96 /* SuperKeyword */) {
return visitSuperKeyword(/*isExpressionOfCall*/ true);
}
return visitor(node);
}
function visitJavaScript(node) {
switch (node.kind) {
case 114 /* StaticKeyword */:
return undefined; // elide static keyword
case 228 /* ClassDeclaration */:
return visitClassDeclaration(node); ...n/a
function transformES2015Module(context) {
var compilerOptions = context.getCompilerOptions();
var previousOnEmitNode = context.onEmitNode;
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
context.enableEmitNotification(263 /* SourceFile */);
context.enableSubstitution(70 /* Identifier */);
var currentSourceFile;
return transformSourceFile;
function transformSourceFile(node) {
if (ts.isDeclarationFile(node)) {
return node;
}
if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions);
if (externalHelpersModuleName) {
var statements = [];
var statementOffset = ts.addPrologueDirectives(statements, node.statements);
ts.append(statements, ts.createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName
)), ts.createLiteral(ts.externalHelpersModuleNameText)));
ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
}
else {
return ts.visitEachChild(node, visitor, context);
}
}
return node;
}
function visitor(node) {
switch (node.kind) {
case 236 /* ImportEqualsDeclaration */:
// Elide `import=` as it is not legal with --module ES6
return undefined;
case 242 /* ExportAssignment */:
return visitExportAssignment(node);
}
return node;
}
function visitExportAssignment(node) {
// Elide `export=` as it is not legal with --module ES6
return node.isExportEquals ? undefined : node;
}
//
// Emit Notification
//
/**
* Hook for node emit.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
if (ts.isSourceFile(node)) {
currentSourceFile = node;
previousOnEmitNode(hint, node, emitCallback);
currentSourceFile = undefined;
}
else {
previousOnEmitNode(hint, node, emitCallback);
}
}
//
// Substitutions
//
/**
* Hooks node substitutions.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to substitute.
*/
function onSubstituteNode(hint, node) {
node = previousOnSubstituteNode(hint, node);
if (ts.isIdentifier(node) && hint === 1 /* Expression */) {
return substituteExpressionIdentifier(node);
}
return node;
}
function substituteExpressionIdentifier(node) {
if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
if (externalHelpersModuleName) {
return ts.createPropertyAccess(externalHelpersModuleName, node);
}
}
return node;
}
}n/a
function transformES2016(context) {
var hoistVariableDeclaration = context.hoistVariableDeclaration;
return transformSourceFile;
function transformSourceFile(node) {
if (ts.isDeclarationFile(node)) {
return node;
}
return ts.visitEachChild(node, visitor, context);
}
function visitor(node) {
if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) {
return node;
}
switch (node.kind) {
case 193 /* BinaryExpression */:
return visitBinaryExpression(node);
default:
return ts.visitEachChild(node, visitor, context);
}
}
function visitBinaryExpression(node) {
switch (node.operatorToken.kind) {
case 61 /* AsteriskAsteriskEqualsToken */:
return visitExponentiationAssignmentExpression(node);
case 39 /* AsteriskAsteriskToken */:
return visitExponentiationExpression(node);
default:
return ts.visitEachChild(node, visitor, context);
}
}
function visitExponentiationAssignmentExpression(node) {
var target;
var value;
var left = ts.visitNode(node.left, visitor, ts.isExpression);
var right = ts.visitNode(node.right, visitor, ts.isExpression);
if (ts.isElementAccessExpression(left)) {
// Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration);
target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression),
left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)),
left);
value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left);
}
else if (ts.isPropertyAccessExpression(left)) {
// Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression
), left.expression), left.name), left);
value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left);
}
else {
// Transforms `a **= b` into `a = Math.pow(a, b)`
target = left;
value = left;
}
return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node);
}
function visitExponentiationExpression(node) {
// Transforms `a ** b` into `Math.pow(a, b)`
var left = ts.visitNode(node.left, visitor, ts.isExpression);
var right = ts.visitNode(node.right, visitor, ts.isExpression);
return ts.createMathPow(left, right, /*location*/ node);
}
}n/a
function transformES2017(context) {
var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment,
endLexicalEnvironment = context.endLexicalEnvironment;
var resolver = context.getEmitResolver();
var compilerOptions = context.getCompilerOptions();
var languageVersion = ts.getEmitScriptTarget(compilerOptions);
// These variables contain state that changes as we descend into the tree.
var currentSourceFile;
/**
* Keeps track of whether expression substitution has been enabled for specific edge cases.
* They are persisted between each SourceFile transformation and should not be reset.
*/
var enabledSubstitutions;
/**
* This keeps track of containers where `super` is valid, for use with
* just-in-time substitution for `super` expressions inside of async methods.
*/
var currentSuperContainer;
// Save the previous transformation hooks.
var previousOnEmitNode = context.onEmitNode;
var previousOnSubstituteNode = context.onSubstituteNode;
// Set new transformation hooks.
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
return transformSourceFile;
function transformSourceFile(node) {
if (ts.isDeclarationFile(node)) {
return node;
}
currentSourceFile = node;
var visited = ts.visitEachChild(node, visitor, context);
ts.addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
return visited;
}
function visitor(node) {
if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) {
return node;
}
switch (node.kind) {
case 119 /* AsyncKeyword */:
// ES2017 async modifier should be elided for targets < ES2017
return undefined;
case 190 /* AwaitExpression */:
// ES2017 'await' expressions must be transformed for targets < ES2017.
return visitAwaitExpression(node);
case 150 /* MethodDeclaration */:
// ES2017 method declarations may be 'async'
return visitMethodDeclaration(node);
case 227 /* FunctionDeclaration */:
// ES2017 function declarations may be 'async'
return visitFunctionDeclaration(node);
case 185 /* FunctionExpression */:
// ES2017 function expressions may be 'async'
return visitFunctionExpression(node);
case 186 /* ArrowFunction */:
// ES2017 arrow functions may be 'async'
return visitArrowFunction(node);
default:
return ts.visitEachChild(node, visitor, context);
}
}
/**
* Visits an AwaitExpression node.
*
* This function will be called any time a ES2017 await expression is encountered.
*
* @param node The node to visit.
*/
function visitAwaitExpression(node) {
return ts.setOriginalNode(ts.setTextRange(ts.createYield(
/*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
}
/**
* Visits a MethodDeclaration node.
*
* This function will be called when one of the following conditions are met:
* - The node is marked as async
*
* @param node The node to visit.
*/
function visitMethodDeclaration(node) {
return ts.updateMethod(node,
/*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name,
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
/*type*/ undefined, ts.isAsyncFunctionLike(node)
? transformAsyncFunctionBody(node)
: ts.visitFunctionBody(node.body, visitor, context));
}
/**
* Visits a FunctionDeclaration node.
*
* This function will be called when one of the following conditions are met:
* - The node is marke ...n/a
function transformES5(context) {
var compilerOptions = context.getCompilerOptions();
// enable emit notification only if using --jsx preserve or react-native
var previousOnEmitNode;
var noSubstitution;
if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
previousOnEmitNode = context.onEmitNode;
context.onEmitNode = onEmitNode;
context.enableEmitNotification(250 /* JsxOpeningElement */);
context.enableEmitNotification(251 /* JsxClosingElement */);
context.enableEmitNotification(249 /* JsxSelfClosingElement */);
noSubstitution = [];
}
var previousOnSubstituteNode = context.onSubstituteNode;
context.onSubstituteNode = onSubstituteNode;
context.enableSubstitution(178 /* PropertyAccessExpression */);
context.enableSubstitution(259 /* PropertyAssignment */);
return transformSourceFile;
/**
* Transforms an ES5 source file to ES3.
*
* @param node A SourceFile
*/
function transformSourceFile(node) {
return node;
}
/**
* Called by the printer just before a node is printed.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emitCallback A callback used to emit the node.
*/
function onEmitNode(hint, node, emitCallback) {
switch (node.kind) {
case 250 /* JsxOpeningElement */:
case 251 /* JsxClosingElement */:
case 249 /* JsxSelfClosingElement */:
var tagName = node.tagName;
noSubstitution[ts.getOriginalNodeId(tagName)] = true;
break;
}
previousOnEmitNode(hint, node, emitCallback);
}
/**
* Hooks node substitutions.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to substitute.
*/
function onSubstituteNode(hint, node) {
if (node.id && noSubstitution && noSubstitution[node.id]) {
return previousOnSubstituteNode(hint, node);
}
node = previousOnSubstituteNode(hint, node);
if (ts.isPropertyAccessExpression(node)) {
return substitutePropertyAccessExpression(node);
}
else if (ts.isPropertyAssignment(node)) {
return substitutePropertyAssignment(node);
}
return node;
}
/**
* Substitutes a PropertyAccessExpression whose name is a reserved word.
*
* @param node A PropertyAccessExpression
*/
function substitutePropertyAccessExpression(node) {
var literalName = trySubstituteReservedName(node.name);
if (literalName) {
return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node);
}
return node;
}
/**
* Substitutes a PropertyAssignment whose name is a reserved word.
*
* @param node A PropertyAssignment
*/
function substitutePropertyAssignment(node) {
var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
if (literalName) {
return ts.updatePropertyAssignment(node, literalName, node.initializer);
}
return node;
}
/**
* If an identifier name is a reserved word, returns a string literal for the name.
*
* @param name An Identifier
*/
function trySubstituteReservedName(name) {
var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined);
if (token >= 71 /* FirstReservedWord */ && token <= 106 /* LastReservedWord */) {
return ts.setTextRange(ts.createLiteral(name), name);
}
return undefined;
}
}n/a
function transformESNext(context) {
var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment;
return transformSourceFile;
function transformSourceFile(node) {
if (ts.isDeclarationFile(node)) {
return node;
}
var visited = ts.visitEachChild(node, visitor, context);
ts.addEmitHelpers(visited, context.readEmitHelpers());
return visited;
}
function visitor(node) {
return visitorWorker(node, /*noDestructuringValue*/ false);
}
function visitorNoDestructuringValue(node) {
return visitorWorker(node, /*noDestructuringValue*/ true);
}
function visitorWorker(node, noDestructuringValue) {
if ((node.transformFlags & 8 /* ContainsESNext */) === 0) {
return node;
}
switch (node.kind) {
case 177 /* ObjectLiteralExpression */:
return visitObjectLiteralExpression(node);
case 193 /* BinaryExpression */:
return visitBinaryExpression(node, noDestructuringValue);
case 225 /* VariableDeclaration */:
return visitVariableDeclaration(node);
case 215 /* ForOfStatement */:
return visitForOfStatement(node);
case 213 /* ForStatement */:
return visitForStatement(node);
case 189 /* VoidExpression */:
return visitVoidExpression(node);
case 151 /* Constructor */:
return visitConstructorDeclaration(node);
case 150 /* MethodDeclaration */:
return visitMethodDeclaration(node);
case 152 /* GetAccessor */:
return visitGetAccessorDeclaration(node);
case 153 /* SetAccessor */:
return visitSetAccessorDeclaration(node);
case 227 /* FunctionDeclaration */:
return visitFunctionDeclaration(node);
case 185 /* FunctionExpression */:
return visitFunctionExpression(node);
case 186 /* ArrowFunction */:
return visitArrowFunction(node);
case 145 /* Parameter */:
return visitParameter(node);
case 209 /* ExpressionStatement */:
return visitExpressionStatement(node);
case 184 /* ParenthesizedExpression */:
return visitParenthesizedExpression(node, noDestructuringValue);
default:
return ts.visitEachChild(node, visitor, context);
}
}
function chunkObjectLiteralElements(elements) {
var chunkObject;
var objects = [];
for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
var e = elements_4[_i];
if (e.kind === 261 /* SpreadAssignment */) {
if (chunkObject) {
objects.push(ts.createObjectLiteral(chunkObject));
chunkObject = undefined;
}
var target = e.expression;
objects.push(ts.visitNode(target, visitor, ts.isExpression));
}
else {
if (!chunkObject) {
chunkObject = [];
}
if (e.kind === 259 /* PropertyAssignment */) {
var p = e;
chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression)));
}
else {
chunkObject.push(e);
}
}
}
if (chunkObject) {
objects.push(ts.createObjectLiteral(chunkObject));
}
return objects;
}
function visitObjectLiteralExpression(node) {
if (node.transformFlags & 1048576 /* ContainsObjectSpread */) {
// spread elements emit like so:
// non-spread elements are chunked together into object literals, and then all are passed to __assign:
// { a, ...o, b } => __assign ...n/a
function transformFiles(resolver, host, sourceFiles, transformers) {
var enabledSyntaxKindFeatures = new Array(300 /* Count */);
var lexicalEnvironmentDisabled = false;
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
var lexicalEnvironmentFunctionDeclarationsStack = [];
var lexicalEnvironmentStackOffset = 0;
var lexicalEnvironmentSuspended = false;
var emitHelpers;
// The transformation context is provided to each transformer as part of transformer
// initialization.
var context = {
getCompilerOptions: function () { return host.getCompilerOptions(); },
getEmitResolver: function () { return resolver; },
getEmitHost: function () { return host; },
startLexicalEnvironment: startLexicalEnvironment,
suspendLexicalEnvironment: suspendLexicalEnvironment,
resumeLexicalEnvironment: resumeLexicalEnvironment,
endLexicalEnvironment: endLexicalEnvironment,
hoistVariableDeclaration: hoistVariableDeclaration,
hoistFunctionDeclaration: hoistFunctionDeclaration,
requestEmitHelper: requestEmitHelper,
readEmitHelpers: readEmitHelpers,
onSubstituteNode: function (_, node) { return node; },
enableSubstitution: enableSubstitution,
isSubstitutionEnabled: isSubstitutionEnabled,
onEmitNode: function (hint, node, callback) { return callback(hint, node); },
enableEmitNotification: enableEmitNotification,
isEmitNotificationEnabled: isEmitNotificationEnabled
};
ts.performance.mark("beforeTransform");
// Chain together and initialize each transformer.
var transformation = ts.chain.apply(void 0, transformers)(context);
// Transform each source file.
var transformed = ts.map(sourceFiles, transformSourceFile);
// Disable modification of the lexical environment.
lexicalEnvironmentDisabled = true;
ts.performance.mark("afterTransform");
ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
return {
transformed: transformed,
emitNodeWithSubstitution: emitNodeWithSubstitution,
emitNodeWithNotification: emitNodeWithNotification
};
/**
* Transforms a source file.
*
* @param sourceFile The source file to transform.
*/
function transformSourceFile(sourceFile) {
if (ts.isDeclarationFile(sourceFile)) {
return sourceFile;
}
return transformation(sourceFile);
}
/**
* Enables expression substitutions in the pretty printer for the provided SyntaxKind.
*/
function enableSubstitution(kind) {
enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
}
/**
* Determines whether expression substitutions are enabled for the provided node.
*/
function isSubstitutionEnabled(node) {
return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
&& (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
}
/**
* Emits a node with possible substitution.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emitCallback The callback used to emit the node or its substitute.
*/
function emitNodeWithSubstitution(hint, node, emitCallback) {
if (node) {
if (isSubstitutionEnabled(node)) {
node = context.onSubstituteNode(hint, node) || node;
}
emitCallback(hint, node);
}
}
/**
* Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
*/
function enableEmitNotification(kind) {
enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
}
/**
* Determines whether before/after emit notifications should be raised in the pretty
* printer when it emits a node.
*/
function isEmitNotificationEnabled(node) {
return (enabledSyntaxKin ...n/a
function transformGenerators(context) {
var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration
= context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
var compilerOptions = context.getCompilerOptions();
var languageVersion = ts.getEmitScriptTarget(compilerOptions);
var resolver = context.getEmitResolver();
var previousOnSubstituteNode = context.onSubstituteNode;
context.onSubstituteNode = onSubstituteNode;
var currentSourceFile;
var renamedCatchVariables;
var renamedCatchVariableDeclarations;
var inGeneratorFunctionBody;
var inStatementContainingYield;
// The following three arrays store information about generated code blocks.
// All three arrays are correlated by their index. This approach is used over allocating
// objects to store the same information to avoid GC overhead.
//
var blocks; // Information about the code block
var blockOffsets; // The operation offset at which a code block begins or ends
var blockActions; // Whether the code block is opened or closed
var blockStack; // A stack of currently open code blocks
// Labels are used to mark locations in the code that can be the target of a Break (jump)
// operation. These are translated into case clauses in a switch statement.
// The following two arrays are correlated by their index. This approach is used over
// allocating objects to store the same information to avoid GC overhead.
//
var labelOffsets; // The operation offset at which the label is defined.
var labelExpressions; // The NumericLiteral nodes bound to each label.
var nextLabelId = 1; // The next label id to use.
// Operations store information about generated code for the function body. This
// Includes things like statements, assignments, breaks (jumps), and yields.
// The following three arrays are correlated by their index. This approach is used over
// allocating objects to store the same information to avoid GC overhead.
//
var operations; // The operation to perform.
var operationArguments; // The arguments to the operation.
var operationLocations; // The source map location for the operation.
var state; // The name of the state object used by the generator at runtime.
// The following variables store information used by the `build` function:
//
var blockIndex = 0; // The index of the current block.
var labelNumber = 0; // The current label number.
var labelNumbers;
var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
var clauses; // The case clauses generated for labels.
var statements; // The statements for the current label.
var exceptionBlockStack; // A stack of containing exception blocks.
var currentExceptionBlock; // The current exception block.
var withBlockStack; // A stack containing `with` blocks.
return transformSourceFile;
function transformSourceFile(node) {
if (ts.isDeclarationFile(node)
|| (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
return node;
}
currentSourceFile = node;
var visited = ts.visitEachChild(node, visitor, context);
ts.addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
return visited;
}
/**
* Visits a node.
*
* @param node The node to visit.
*/
function visitor(node) {
var transformFlags = node.transformFlags;
if (inStatementContainingYield) {
return visitJavaScriptInStatementContainingYield(node);
}
else if (inGeneratorFunctionBody) {
return visitJavaScriptInGeneratorFunctionBody(node);
}
else if (transformFlags & 256 /* Generator */) {
return visitG ...n/a
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
return transformSourceFile;
/**
* Transform JSX-specific syntax in a SourceFile.
*
* @param node A SourceFile node.
*/
function transformSourceFile(node) {
if (ts.isDeclarationFile(node)) {
return node;
}
currentSourceFile = node;
var visited = ts.visitEachChild(node, visitor, context);
ts.addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
return visited;
}
function visitor(node) {
if (node.transformFlags & 4 /* ContainsJsx */) {
return visitorWorker(node);
}
else {
return node;
}
}
function visitorWorker(node) {
switch (node.kind) {
case 248 /* JsxElement */:
return visitJsxElement(node, /*isChild*/ false);
case 249 /* JsxSelfClosingElement */:
return visitJsxSelfClosingElement(node, /*isChild*/ false);
case 254 /* JsxExpression */:
return visitJsxExpression(node);
default:
return ts.visitEachChild(node, visitor, context);
}
}
function transformJsxChildToExpression(node) {
switch (node.kind) {
case 10 /* JsxText */:
return visitJsxText(node);
case 254 /* JsxExpression */:
return visitJsxExpression(node);
case 248 /* JsxElement */:
return visitJsxElement(node, /*isChild*/ true);
case 249 /* JsxSelfClosingElement */:
return visitJsxSelfClosingElement(node, /*isChild*/ true);
default:
ts.Debug.failBadSyntaxKind(node);
return undefined;
}
}
function visitJsxElement(node, isChild) {
return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
}
function visitJsxSelfClosingElement(node, isChild) {
return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
}
function visitJsxOpeningLikeElement(node, children, isChild, location) {
var tagName = getTagName(node);
var objectProperties;
var attrs = node.attributes;
if (attrs.length === 0) {
// When there are no attributes, React wants "null"
objectProperties = ts.createNull();
}
else {
// Map spans of JsxAttribute nodes into object literals and spans
// of JsxSpreadAttribute nodes into expressions.
var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
? ts.map(attrs, transformJsxSpreadAttributeToExpression)
: ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
if (ts.isJsxSpreadAttribute(attrs[0])) {
// We must always emit at least one object literal before a spread
// argument.
segments.unshift(ts.createObjectLiteral());
}
// Either emit one big object literal (no spread attribs), or
// a call to the __assign helper.
objectProperties = ts.singleOrUndefined(segments);
if (!objectProperties) {
objectProperties = ts.createAssignHelper(context, segments);
}
}
var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace
, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location);
if (isChild) {
ts.startOnNewLine(element);
}
return element;
}
function transformJsxSpreadAttributeToExpression(node) {
return ts.visitNode(node.expression, visitor, ts.isExpression);
}
function transformJsxA ...n/a
function transformModule(context) {
function getTransformModuleDelegate(moduleKind) {
switch (moduleKind) {
case ts.ModuleKind.AMD: return transformAMDModule;
case ts.ModuleKind.UMD: return transformUMDModule;
default: return transformCommonJSModule;
}
}
var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment;
var compilerOptions = context.getCompilerOptions();
var resolver = context.getEmitResolver();
var host = context.getEmitHost();
var languageVersion = ts.getEmitScriptTarget(compilerOptions);
var moduleKind = ts.getEmitModuleKind(compilerOptions);
var previousOnSubstituteNode = context.onSubstituteNode;
var previousOnEmitNode = context.onEmitNode;
context.onSubstituteNode = onSubstituteNode;
context.onEmitNode = onEmitNode;
context.enableSubstitution(70 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
context.enableSubstitution(193 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(191 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(192 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(260 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported
/exported symbols.
context.enableEmitNotification(263 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var currentSourceFile; // The current file.
var currentModuleInfo; // The ExternalModuleInfo for the current file.
var noSubstitution; // Set of nodes for which substitution rules should be ignored.
return transformSourceFile;
/**
* Transforms the module aspects of a SourceFile.
*
* @param node The SourceFile node.
*/
function transformSourceFile(node) {
if (ts.isDeclarationFile(node)
|| !(ts.isExternalModule(node)
|| compilerOptions.isolatedModules)) {
return node;
}
currentSourceFile = node;
currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
// Perform the transformation.
var transformModule = getTransformModuleDelegate(moduleKind);
var updated = transformModule(node);
currentSourceFile = undefined;
currentModuleInfo = undefined;
return ts.aggregateTransformFlags(updated);
}
/**
* Transforms a SourceFile into a CommonJS module.
*
* @param node The SourceFile node.
*/
function transformCommonJSModule(node) {
startLexicalEnvironment();
var statements = [];
var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict
, sourceElementVisitor);
if (!currentModuleInfo.exportEquals) {
ts.append(statements, createUnderscoreUnderscoreESModule());
}
ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement
, /*optional*/ true));
ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
ts.addRange(statements, endLexicalEnvironment());
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
if (currentModuleInfo.hasExportStarsToExportValues) {
ts.addEmitHelper(updated, exportStarHelper);
}
return updated;
}
/**
* Transforms a SourceFile into an AMD module. ...n/a
function transformSystemModule(context) {
var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration
= context.hoistVariableDeclaration;
var compilerOptions = context.getCompilerOptions();
var resolver = context.getEmitResolver();
var host = context.getEmitHost();
var previousOnSubstituteNode = context.onSubstituteNode;
var previousOnEmitNode = context.onEmitNode;
context.onSubstituteNode = onSubstituteNode;
context.onEmitNode = onEmitNode;
context.enableSubstitution(70 /* Identifier */); // Substitutes expression identifiers for imported symbols.
context.enableSubstitution(193 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(191 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(192 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableEmitNotification(263 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var exportFunctionsMap = []; // The export function associated with a source file.
var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
var currentSourceFile; // The current file.
var moduleInfo; // ExternalModuleInfo for the current file.
var exportFunction; // The export function for the current file.
var contextObject; // The context object for the current file.
var hoistedStatements;
var enclosingBlockScopedContainer;
var noSubstitution; // Set of nodes for which substitution rules should be ignored.
return transformSourceFile;
/**
* Transforms the module aspects of a SourceFile.
*
* @param node The SourceFile node.
*/
function transformSourceFile(node) {
if (ts.isDeclarationFile(node)
|| !(ts.isExternalModule(node)
|| compilerOptions.isolatedModules)) {
return node;
}
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
enclosingBlockScopedContainer = node;
// System modules have the following shape:
//
// System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
//
// The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
// is used to publish exported values. 'exports' returns its 'value' argument so in
// most cases expressions that mutate exported values can be rewritten as:
//
// expr -> exports('name', expr)
//
// The only exception in this rule is postfix unary operators,
// see comment to 'substitutePostfixUnaryExpression' for more details
// Collect information about the external module and dependency groups.
moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
// Make sure that the name of the 'exports' function does not conflict with
// existing identifiers.
exportFunction = ts.createUniqueName("exports");
exportFunctionsMap[id] = exportFunction;
contextObject = ts.createUniqueName("context");
// Add the body of the module.
var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
var moduleBodyFunction = ts.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined, [
ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefine ...n/a
function transformTypeScript(context) {
var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment,
endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
var resolver = context.getEmitResolver();
var compilerOptions = context.getCompilerOptions();
var languageVersion = ts.getEmitScriptTarget(compilerOptions);
var moduleKind = ts.getEmitModuleKind(compilerOptions);
// Save the previous transformation hooks.
var previousOnEmitNode = context.onEmitNode;
var previousOnSubstituteNode = context.onSubstituteNode;
// Set new transformation hooks.
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
// Enable substitution for property/element access to emit const enum values.
context.enableSubstitution(178 /* PropertyAccessExpression */);
context.enableSubstitution(179 /* ElementAccessExpression */);
// These variables contain state that changes as we descend into the tree.
var currentSourceFile;
var currentNamespace;
var currentNamespaceContainerName;
var currentScope;
var currentScopeFirstDeclarationsOfName;
/**
* Keeps track of whether expression substitution has been enabled for specific edge cases.
* They are persisted between each SourceFile transformation and should not be reset.
*/
var enabledSubstitutions;
/**
* A map that keeps track of aliases created for classes with decorators to avoid issues
* with the double-binding behavior of classes.
*/
var classAliases;
/**
* Keeps track of whether we are within any containing namespaces when performing
* just-in-time substitution while printing an expression identifier.
*/
var applicableSubstitutions;
return transformSourceFile;
/**
* Transform TypeScript-specific syntax in a SourceFile.
*
* @param node A SourceFile node.
*/
function transformSourceFile(node) {
if (ts.isDeclarationFile(node)) {
return node;
}
currentSourceFile = node;
var visited = saveStateAndInvoke(node, visitSourceFile);
ts.addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
return visited;
}
/**
* Visits a node, saving and restoring state variables on the stack.
*
* @param node The node to visit.
*/
function saveStateAndInvoke(node, f) {
// Save state
var savedCurrentScope = currentScope;
var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
// Handle state changes before visiting a node.
onBeforeVisitNode(node);
var visited = f(node);
// Restore state
if (currentScope !== savedCurrentScope) {
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
}
currentScope = savedCurrentScope;
return visited;
}
/**
* Performs actions that should always occur immediately before visiting a node.
*
* @param node The node to visit.
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
case 263 /* SourceFile */:
case 234 /* CaseBlock */:
case 233 /* ModuleBlock */:
case 206 /* Block */:
currentScope = node;
currentScopeFirstDeclarationsOfName = undefined;
break;
case 228 /* ClassDeclaration */:
case 227 /* FunctionDeclaration */:
if (ts.hasModifier(node, 2 /* Ambient */)) {
break;
}
recordEmittedDeclarationInScope(node);
break;
}
}
/**
* General-purpose node visitor.
*
* @param node The node to visit.
*/
function visitor(node) {
return saveStateAndInvoke(node, visitorWorker);
}
/**
* Visits and possibly transf ...n/a
function transpile(input, compilerOptions, fileName, diagnostics, moduleName) {
var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics
, moduleName: moduleName });
// addRange correctly handles cases when wither 'from' or 'to' argument is missing
ts.addRange(diagnostics, output.diagnostics);
return output.outputText;
}n/a
function transpileModule(input, transpileOptions) {
var diagnostics = [];
var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : ts.getDefaultCompilerOptions
();
options.isolatedModules = true;
// transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and
output paths.
options.suppressOutputPathCheck = true;
// Filename can be non-ts file.
options.allowNonTsExtensions = true;
// We are not returning a sourceFile for lib file when asked by the program,
// so pass --noLib to avoid reporting a file not found error.
options.noLib = true;
// Clear out other settings that would not be used in transpiling this module
options.lib = undefined;
options.types = undefined;
options.noEmit = undefined;
options.noEmitOnError = undefined;
options.paths = undefined;
options.rootDirs = undefined;
options.declaration = undefined;
options.declarationDir = undefined;
options.out = undefined;
options.outFile = undefined;
// We are not doing a full typecheck, we are not resolving the whole context,
// so pass --noResolve to avoid reporting missing file errors.
options.noResolve = true;
// if jsx is specified then treat file as .tsx
var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts");
var sourceFile = ts.createSourceFile(inputFileName, input, options.target);
if (transpileOptions.moduleName) {
sourceFile.moduleName = transpileOptions.moduleName;
}
if (transpileOptions.renamedDependencies) {
sourceFile.renamedDependencies = ts.createMapFromTemplate(transpileOptions.renamedDependencies);
}
var newLine = ts.getNewLineCharacter(options);
// Output
var outputText;
var sourceMapText;
// Create a compilerHost object to allow the compiler to read and write files
var compilerHost = {
getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; },
writeFile: function (name, text) {
if (ts.fileExtensionIs(name, ".map")) {
ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'");
sourceMapText = text;
}
else {
ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'");
outputText = text;
}
},
getDefaultLibFileName: function () { return "lib.d.ts"; },
useCaseSensitiveFileNames: function () { return false; },
getCanonicalFileName: function (fileName) { return fileName; },
getCurrentDirectory: function () { return ""; },
getNewLine: function () { return newLine; },
fileExists: function (fileName) { return fileName === inputFileName; },
readFile: function () { return ""; },
directoryExists: function () { return true; },
getDirectories: function () { return []; }
};
var program = ts.createProgram([inputFileName], options, compilerHost);
if (transpileOptions.reportDiagnostics) {
ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile));
ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics());
}
// Emit
program.emit();
ts.Debug.assert(outputText !== undefined, "Output generation failed");
return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText };
}n/a
function tryExtractTypeScriptExtension(fileName) {
return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName
, extension); });
}n/a
function tryGetClassExtendingExpressionWithTypeArguments(node) {
if (node.kind === 200 /* ExpressionWithTypeArguments */ &&
node.parent.token === 84 /* ExtendsKeyword */ &&
isClassLike(node.parent.parent)) {
return node.parent.parent;
}
}n/a
function tryGetExtensionFromPath(path) {
if (fileExtensionIs(path, ".d.ts")) {
return ts.Extension.Dts;
}
if (fileExtensionIs(path, ".ts")) {
return ts.Extension.Ts;
}
if (fileExtensionIs(path, ".tsx")) {
return ts.Extension.Tsx;
}
if (fileExtensionIs(path, ".js")) {
return ts.Extension.Js;
}
if (fileExtensionIs(path, ".jsx")) {
return ts.Extension.Jsx;
}
}n/a
function tryGetModuleNameFromFile(file, host, options) {
if (!file) {
return undefined;
}
if (file.moduleName) {
return ts.createLiteral(file.moduleName);
}
if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) {
return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
}
return undefined;
}n/a
function tryParsePattern(pattern) {
// This should be verified outside of here and a proper error thrown.
Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
var indexOfStar = pattern.indexOf("*");
return indexOfStar === -1 ? undefined : {
prefix: pattern.substr(0, indexOfStar),
suffix: pattern.substr(indexOfStar + 1)
};
}n/a
function tryRemoveExtension(path, extension) {
return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
}n/a
function tryResolveScriptReference(host, sourceFile, reference) {
if (!host.getCompilerOptions().noResolve) {
var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath
(sourceFile.fileName), reference.fileName);
return host.getSourceFile(referenceFileName);
}
}n/a
function typeDirectiveIsEqualTo(oldResolution, newResolution) {
return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
}n/a
function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) {
return mapToDisplayParts(function (writer) {
typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags);
});
}n/a
function unescapeIdentifier(identifier) {
return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier
.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier;
}n/a
function unorderedRemoveItem(array, item) {
unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
}n/a
function unorderedRemoveItemAt(array, index) {
// Fill in the "hole" left at `index`.
array[index] = array[array.length - 1];
array.pop();
}n/a
function unwrapInnermostStatmentOfLabel(node, beforeUnwrapLabelCallback) {
while (true) {
if (beforeUnwrapLabelCallback) {
beforeUnwrapLabelCallback(node);
}
if (node.statement.kind !== 221 /* LabeledStatement */) {
return node.statement;
}
node = node.statement;
}
}n/a
function updateArrayBindingPattern(node, elements) {
return node.elements !== elements
? updateNode(createArrayBindingPattern(elements), node)
: node;
}n/a
function updateArrayLiteral(node, elements) {
return node.elements !== elements
? updateNode(createArrayLiteral(elements, node.multiLine), node)
: node;
}n/a
function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) {
return node.modifiers !== modifiers
|| node.typeParameters !== typeParameters
|| node.parameters !== parameters
|| node.type !== type
|| node.body !== body
? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body), node)
: node;
}n/a
function updateAsExpression(node, expression, type) {
return node.expression !== expression
|| node.type !== type
? updateNode(createAsExpression(expression, type), node)
: node;
}n/a
function updateAwait(node, expression) {
return node.expression !== expression
? updateNode(createAwait(expression), node)
: node;
}n/a
function updateBinary(node, left, right) {
return node.left !== left
|| node.right !== right
? updateNode(createBinary(left, node.operatorToken, right), node)
: node;
}n/a
function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
return node.propertyName !== propertyName
|| node.dotDotDotToken !== dotDotDotToken
|| node.name !== name
|| node.initializer !== initializer
? updateNode(createBindingElement(propertyName, dotDotDotToken, name, initializer), node)
: node;
}n/a
function updateBlock(node, statements) {
return statements !== node.statements
? updateNode(createBlock(statements, node.multiLine), node)
: node;
}n/a
function updateBreak(node, label) {
return node.label !== label
? updateNode(createBreak(label), node)
: node;
}n/a
function updateBundle(node, sourceFiles) {
if (node.sourceFiles !== sourceFiles) {
return createBundle(sourceFiles);
}
return node;
}n/a
function updateCall(node, expression, typeArguments, argumentsArray) {
return expression !== node.expression
|| typeArguments !== node.typeArguments
|| argumentsArray !== node.arguments
? updateNode(createCall(expression, typeArguments, argumentsArray), node)
: node;
}n/a
function updateCaseBlock(node, clauses) {
return node.clauses !== clauses
? updateNode(createCaseBlock(clauses), node)
: node;
}n/a
function updateCaseClause(node, expression, statements) {
if (node.expression !== expression || node.statements !== statements) {
return updateNode(createCaseClause(expression, statements), node);
}
return node;
}n/a
function updateCatchClause(node, variableDeclaration, block) {
if (node.variableDeclaration !== variableDeclaration || node.block !== block) {
return updateNode(createCatchClause(variableDeclaration, block), node);
}
return node;
}n/a
function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.name !== name
|| node.typeParameters !== typeParameters
|| node.heritageClauses !== heritageClauses
|| node.members !== members
? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
: node;
}n/a
function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
return node.modifiers !== modifiers
|| node.name !== name
|| node.typeParameters !== typeParameters
|| node.heritageClauses !== heritageClauses
|| node.members !== members
? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node)
: node;
}n/a
function updateComputedPropertyName(node, expression) {
return node.expression !== expression
? updateNode(createComputedPropertyName(expression), node)
: node;
}n/a
function updateConditional(node, condition, whenTrue, whenFalse) {
return node.condition !== condition
|| node.whenTrue !== whenTrue
|| node.whenFalse !== whenFalse
? updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse), node)
: node;
}n/a
function updateConstructor(node, decorators, modifiers, parameters, body) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.parameters !== parameters
|| node.body !== body
? updateNode(createConstructor(decorators, modifiers, parameters, body), node)
: node;
}n/a
function updateContinue(node, label) {
return node.label !== label
? updateNode(createContinue(label), node)
: node;
}n/a
function updateDecorator(node, expression) {
return node.expression !== expression
? updateNode(createDecorator(expression), node)
: node;
}n/a
function updateDefaultClause(node, statements) {
if (node.statements !== statements) {
return updateNode(createDefaultClause(statements), node);
}
return node;
}n/a
function updateDelete(node, expression) {
return node.expression !== expression
? updateNode(createDelete(expression), node)
: node;
}n/a
function updateDo(node, statement, expression) {
return node.statement !== statement
|| node.expression !== expression
? updateNode(createDo(statement, expression), node)
: node;
}n/a
function updateElementAccess(node, expression, argumentExpression) {
return node.expression !== expression
|| node.argumentExpression !== argumentExpression
? updateNode(createElementAccess(expression, argumentExpression), node)
: node;
}n/a
function updateEnumDeclaration(node, decorators, modifiers, name, members) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.name !== name
|| node.members !== members
? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node)
: node;
}n/a
function updateEnumMember(node, name, initializer) {
return node.name !== name
|| node.initializer !== initializer
? updateNode(createEnumMember(name, initializer), node)
: node;
}n/a
function updateExportAssignment(node, decorators, modifiers, expression) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.expression !== expression
? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
: node;
}n/a
function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.exportClause !== exportClause
|| node.moduleSpecifier !== moduleSpecifier
? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier), node)
: node;
}n/a
function updateExportSpecifier(node, name, propertyName) {
return node.name !== name || node.propertyName !== propertyName
? updateNode(createExportSpecifier(name, propertyName), node)
: node;
}n/a
function updateExpressionWithTypeArguments(node, typeArguments, expression) {
return node.typeArguments !== typeArguments
|| node.expression !== expression
? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
: node;
}n/a
function updateExternalModuleReference(node, expression) {
return node.expression !== expression
? updateNode(createExternalModuleReference(expression), node)
: node;
}n/a
function updateFor(node, initializer, condition, incrementor, statement) {
return node.initializer !== initializer
|| node.condition !== condition
|| node.incrementor !== incrementor
|| node.statement !== statement
? updateNode(createFor(initializer, condition, incrementor, statement), node)
: node;
}n/a
function updateForIn(node, initializer, expression, statement) {
return node.initializer !== initializer
|| node.expression !== expression
|| node.statement !== statement
? updateNode(createForIn(initializer, expression, statement), node)
: node;
}n/a
function updateForOf(node, initializer, expression, statement) {
return node.initializer !== initializer
|| node.expression !== expression
|| node.statement !== statement
? updateNode(createForOf(initializer, expression, statement), node)
: node;
}n/a
function updateFunctionDeclaration(node, decorators, modifiers, name, typeParameters, parameters, type, body) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.name !== name
|| node.typeParameters !== typeParameters
|| node.parameters !== parameters
|| node.type !== type
|| node.body !== body
? updateNode(createFunctionDeclaration(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type
, body), node)
: node;
}n/a
function updateFunctionExpression(node, modifiers, name, typeParameters, parameters, type, body) {
return node.name !== name
|| node.modifiers !== modifiers
|| node.typeParameters !== typeParameters
|| node.parameters !== parameters
|| node.type !== type
|| node.body !== body
? updateNode(createFunctionExpression(modifiers, node.asteriskToken, name, typeParameters, parameters, type, body), node
)
: node;
}n/a
function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.name !== name
|| node.parameters !== parameters
|| node.type !== type
|| node.body !== body
? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node)
: node;
}n/a
function updateHeritageClause(node, types) {
if (node.types !== types) {
return updateNode(createHeritageClause(node.token, types), node);
}
return node;
}n/a
function updateIf(node, expression, thenStatement, elseStatement) {
return node.expression !== expression
|| node.thenStatement !== thenStatement
|| node.elseStatement !== elseStatement
? updateNode(createIf(expression, thenStatement, elseStatement), node)
: node;
}n/a
function updateImportClause(node, name, namedBindings) {
return node.name !== name
|| node.namedBindings !== namedBindings
? updateNode(createImportClause(name, namedBindings), node)
: node;
}n/a
function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier
? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
: node;
}n/a
function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.name !== name
|| node.moduleReference !== moduleReference
? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
: node;
}n/a
function updateImportSpecifier(node, propertyName, name) {
return node.propertyName !== propertyName
|| node.name !== name
? updateNode(createImportSpecifier(propertyName, name), node)
: node;
}n/a
function updateJsxAttribute(node, name, initializer) {
return node.name !== name
|| node.initializer !== initializer
? updateNode(createJsxAttribute(name, initializer), node)
: node;
}n/a
function updateJsxClosingElement(node, tagName) {
return node.tagName !== tagName
? updateNode(createJsxClosingElement(tagName), node)
: node;
}n/a
function updateJsxElement(node, openingElement, children, closingElement) {
return node.openingElement !== openingElement
|| node.children !== children
|| node.closingElement !== closingElement
? updateNode(createJsxElement(openingElement, children, closingElement), node)
: node;
}n/a
function updateJsxExpression(node, expression) {
return node.expression !== expression
? updateNode(createJsxExpression(expression, node.dotDotDotToken), node)
: node;
}n/a
function updateJsxOpeningElement(node, tagName, attributes) {
return node.tagName !== tagName
|| node.attributes !== attributes
? updateNode(createJsxOpeningElement(tagName, attributes), node)
: node;
}n/a
function updateJsxSelfClosingElement(node, tagName, attributes) {
return node.tagName !== tagName
|| node.attributes !== attributes
? updateNode(createJsxSelfClosingElement(tagName, attributes), node)
: node;
}n/a
function updateJsxSpreadAttribute(node, expression) {
return node.expression !== expression
? updateNode(createJsxSpreadAttribute(expression), node)
: node;
}n/a
function updateLabel(node, label, statement) {
return node.label !== label
|| node.statement !== statement
? updateNode(createLabel(label, statement), node)
: node;
}n/a
function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, textChangeRange, aggressiveChecks) {
// If we were given a text change range, and our version or open-ness changed, then
// incrementally parse this file.
if (textChangeRange) {
if (version !== sourceFile.version) {
// Once incremental parsing is ready, then just call into this function.
if (!ts.disableIncrementalParsing) {
var newText = void 0;
// grab the fragment from the beginning of the original text to the beginning of the span
var prefix = textChangeRange.span.start !== 0
? sourceFile.text.substr(0, textChangeRange.span.start)
: "";
// grab the fragment from the end of the span till the end of the original text
var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length
? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span))
: "";
if (textChangeRange.newLength === 0) {
// edit was a deletion - just combine prefix and suffix
newText = prefix && suffix ? prefix + suffix : prefix || suffix;
}
else {
// it was actual edit, fetch the fragment of new text that correspond to new span
var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange
.newLength);
// combine prefix, changed text and suffix
newText = prefix && suffix
? prefix + changedText + suffix
: prefix
? (prefix + changedText)
: (changedText + suffix);
}
var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
setSourceFileFields(newSourceFile, scriptSnapshot, version);
// after incremental parsing nameTable might not be up-to-date
// drop it so it can be lazily recreated later
newSourceFile.nameTable = undefined;
// dispose all resources held by old script snapshot
if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) {
if (sourceFile.scriptSnapshot.dispose) {
sourceFile.scriptSnapshot.dispose();
}
sourceFile.scriptSnapshot = undefined;
}
return newSourceFile;
}
}
}
// Otherwise, just create a new source file.
return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents
*/ true, sourceFile.scriptKind);
}n/a
function updateMethod(node, decorators, modifiers, name, typeParameters, parameters, type, body) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.name !== name
|| node.typeParameters !== typeParameters
|| node.parameters !== parameters
|| node.type !== type
|| node.body !== body
? updateNode(createMethod(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body), node
)
: node;
}n/a
function updateModuleBlock(node, statements) {
return node.statements !== statements
? updateNode(createModuleBlock(statements), node)
: node;
}n/a
function updateModuleDeclaration(node, decorators, modifiers, name, body) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.name !== name
|| node.body !== body
? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
: node;
}n/a
function updateNamedExports(node, elements) {
return node.elements !== elements
? updateNode(createNamedExports(elements), node)
: node;
}n/a
function updateNamedImports(node, elements) {
return node.elements !== elements
? updateNode(createNamedImports(elements), node)
: node;
}n/a
function updateNamespaceImport(node, name) {
return node.name !== name
? updateNode(createNamespaceImport(name), node)
: node;
}n/a
function updateNew(node, expression, typeArguments, argumentsArray) {
return node.expression !== expression
|| node.typeArguments !== typeArguments
|| node.arguments !== argumentsArray
? updateNode(createNew(expression, typeArguments, argumentsArray), node)
: node;
}n/a
function updateNode(updated, original) {
if (updated !== original) {
setOriginalNode(updated, original);
setTextRange(updated, original);
if (original.startsOnNewLine) {
updated.startsOnNewLine = true;
}
ts.aggregateTransformFlags(updated);
}
return updated;
}n/a
function updateNonNullExpression(node, expression) {
return node.expression !== expression
? updateNode(createNonNullExpression(expression), node)
: node;
}n/a
function updateObjectBindingPattern(node, elements) {
return node.elements !== elements
? updateNode(createObjectBindingPattern(elements), node)
: node;
}n/a
function updateObjectLiteral(node, properties) {
return node.properties !== properties
? updateNode(createObjectLiteral(properties, node.multiLine), node)
: node;
}n/a
function updateParameter(node, decorators, modifiers, dotDotDotToken, name, type, initializer) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.dotDotDotToken !== dotDotDotToken
|| node.name !== name
|| node.type !== type
|| node.initializer !== initializer
? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer), node)
: node;
}n/a
function updateParen(node, expression) {
return node.expression !== expression
? updateNode(createParen(expression), node)
: node;
}n/a
function updatePartiallyEmittedExpression(node, expression) {
if (node.expression !== expression) {
return updateNode(createPartiallyEmittedExpression(expression, node.original), node);
}
return node;
}n/a
function updatePostfix(node, operand) {
return node.operand !== operand
? updateNode(createPostfix(operand, node.operator), node)
: node;
}n/a
function updatePrefix(node, operand) {
return node.operand !== operand
? updateNode(createPrefix(node.operator, operand), node)
: node;
}n/a
function updateProperty(node, decorators, modifiers, name, type, initializer) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.name !== name
|| node.type !== type
|| node.initializer !== initializer
? updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer), node)
: node;
}n/a
function updatePropertyAccess(node, expression, name) {
// Because we are updating existed propertyAccess we want to inherit its emitFlags
// instead of using the default from createPropertyAccess
return node.expression !== expression
|| node.name !== name
? updateNode(setEmitFlags(createPropertyAccess(expression, name), getEmitFlags(node)), node)
: node;
}n/a
function updatePropertyAssignment(node, name, initializer) {
if (node.name !== name || node.initializer !== initializer) {
return updateNode(createPropertyAssignment(name, initializer), node);
}
return node;
}n/a
function updateQualifiedName(node, left, right) {
return node.left !== left
|| node.right !== right
? updateNode(createQualifiedName(left, right), node)
: node;
}n/a
function updateReturn(node, expression) {
return node.expression !== expression
? updateNode(createReturn(expression), node)
: node;
}n/a
function updateSetAccessor(node, decorators, modifiers, name, parameters, body) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.name !== name
|| node.parameters !== parameters
|| node.body !== body
? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node)
: node;
}n/a
function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) {
return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node);
}
return node;
}n/a
function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
}n/a
function updateSourceFileNode(node, statements) {
if (node.statements !== statements) {
var updated = createSynthesizedNode(263 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
updated.fileName = node.fileName;
updated.path = node.path;
updated.text = node.text;
if (node.amdDependencies !== undefined)
updated.amdDependencies = node.amdDependencies;
if (node.moduleName !== undefined)
updated.moduleName = node.moduleName;
if (node.referencedFiles !== undefined)
updated.referencedFiles = node.referencedFiles;
if (node.typeReferenceDirectives !== undefined)
updated.typeReferenceDirectives = node.typeReferenceDirectives;
if (node.languageVariant !== undefined)
updated.languageVariant = node.languageVariant;
if (node.isDeclarationFile !== undefined)
updated.isDeclarationFile = node.isDeclarationFile;
if (node.renamedDependencies !== undefined)
updated.renamedDependencies = node.renamedDependencies;
if (node.hasNoDefaultLib !== undefined)
updated.hasNoDefaultLib = node.hasNoDefaultLib;
if (node.languageVersion !== undefined)
updated.languageVersion = node.languageVersion;
if (node.scriptKind !== undefined)
updated.scriptKind = node.scriptKind;
if (node.externalModuleIndicator !== undefined)
updated.externalModuleIndicator = node.externalModuleIndicator;
if (node.commonJsModuleIndicator !== undefined)
updated.commonJsModuleIndicator = node.commonJsModuleIndicator;
if (node.identifiers !== undefined)
updated.identifiers = node.identifiers;
if (node.nodeCount !== undefined)
updated.nodeCount = node.nodeCount;
if (node.identifierCount !== undefined)
updated.identifierCount = node.identifierCount;
if (node.symbolCount !== undefined)
updated.symbolCount = node.symbolCount;
if (node.parseDiagnostics !== undefined)
updated.parseDiagnostics = node.parseDiagnostics;
if (node.bindDiagnostics !== undefined)
updated.bindDiagnostics = node.bindDiagnostics;
if (node.lineMap !== undefined)
updated.lineMap = node.lineMap;
if (node.classifiableNames !== undefined)
updated.classifiableNames = node.classifiableNames;
if (node.resolvedModules !== undefined)
updated.resolvedModules = node.resolvedModules;
if (node.resolvedTypeReferenceDirectiveNames !== undefined)
updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames;
if (node.imports !== undefined)
updated.imports = node.imports;
if (node.moduleAugmentations !== undefined)
updated.moduleAugmentations = node.moduleAugmentations;
return updateNode(updated, node);
}
return node;
}n/a
function updateSpread(node, expression) {
return node.expression !== expression
? updateNode(createSpread(expression), node)
: node;
}n/a
function updateSpreadAssignment(node, expression) {
if (node.expression !== expression) {
return updateNode(createSpreadAssignment(expression), node);
}
return node;
}n/a
function updateStatement(node, expression) {
return node.expression !== expression
? updateNode(createStatement(expression), node)
: node;
}n/a
function updateSwitch(node, expression, caseBlock) {
return node.expression !== expression
|| node.caseBlock !== caseBlock
? updateNode(createSwitch(expression, caseBlock), node)
: node;
}n/a
function updateTaggedTemplate(node, tag, template) {
return node.tag !== tag
|| node.template !== template
? updateNode(createTaggedTemplate(tag, template), node)
: node;
}n/a
function updateTemplateExpression(node, head, templateSpans) {
return node.head !== head
|| node.templateSpans !== templateSpans
? updateNode(createTemplateExpression(head, templateSpans), node)
: node;
}n/a
function updateTemplateSpan(node, expression, literal) {
return node.expression !== expression
|| node.literal !== literal
? updateNode(createTemplateSpan(expression, literal), node)
: node;
}n/a
function updateThrow(node, expression) {
return node.expression !== expression
? updateNode(createThrow(expression), node)
: node;
}n/a
function updateTry(node, tryBlock, catchClause, finallyBlock) {
return node.tryBlock !== tryBlock
|| node.catchClause !== catchClause
|| node.finallyBlock !== finallyBlock
? updateNode(createTry(tryBlock, catchClause, finallyBlock), node)
: node;
}n/a
function updateTypeAssertion(node, type, expression) {
return node.type !== type
|| node.expression !== expression
? updateNode(createTypeAssertion(type, expression), node)
: node;
}n/a
function updateTypeOf(node, expression) {
return node.expression !== expression
? updateNode(createTypeOf(expression), node)
: node;
}n/a
function updateVariableDeclaration(node, name, type, initializer) {
return node.name !== name
|| node.type !== type
|| node.initializer !== initializer
? updateNode(createVariableDeclaration(name, type, initializer), node)
: node;
}n/a
function updateVariableDeclarationList(node, declarations) {
return node.declarations !== declarations
? updateNode(createVariableDeclarationList(declarations, node.flags), node)
: node;
}n/a
function updateVariableStatement(node, modifiers, declarationList) {
return node.modifiers !== modifiers
|| node.declarationList !== declarationList
? updateNode(createVariableStatement(modifiers, declarationList), node)
: node;
}n/a
function updateVoid(node, expression) {
return node.expression !== expression
? updateNode(createVoid(expression), node)
: node;
}n/a
function updateWhile(node, expression, statement) {
return node.expression !== expression
|| node.statement !== statement
? updateNode(createWhile(expression, statement), node)
: node;
}n/a
function updateWith(node, expression, statement) {
return node.expression !== expression
|| node.statement !== statement
? updateNode(createWith(expression, statement), node)
: node;
}n/a
function updateYield(node, expression) {
return node.expression !== expression
? updateNode(createYield(node.asteriskToken, expression), node)
: node;
}n/a
function validateLocaleAndSetLanguage(locale, sys, errors) {
var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
if (!matchResult) {
if (errors) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1
, "en", "ja-jp"));
}
return;
}
var language = matchResult[1];
var territory = matchResult[3];
// First try the entire locale, then fall back to just language if that's all we have.
// Either ways do not fail, and fallback to the English diagnostic strings.
if (!trySetLanguageAndTerritory(language, territory, errors)) {
trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
}
function trySetLanguageAndTerritory(language, territory, errors) {
var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
var filePath = ts.combinePaths(containingDirectoryPath, language);
if (territory) {
filePath = filePath + "-" + territory;
}
filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
if (!sys.fileExists(filePath)) {
return false;
}
// TODO: Add codePage support for readFile?
var fileContents = "";
try {
fileContents = sys.readFile(filePath);
}
catch (e) {
if (errors) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
}
return false;
}
try {
ts.localizedDiagnosticMessages = JSON.parse(fileContents);
}
catch (e) {
if (errors) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
}
return false;
}
return true;
}
}n/a
function visitEachChild(node, visitor, context) {
if (node === undefined) {
return undefined;
}
var kind = node.kind;
// No need to visit nodes with no children.
if ((kind > 0 /* FirstToken */ && kind <= 141 /* LastToken */)) {
return node;
}
// We do not yet support types.
if ((kind >= 157 /* TypePredicate */ && kind <= 172 /* LiteralType */)) {
return node;
}
switch (node.kind) {
case 205 /* SemicolonClassElement */:
case 208 /* EmptyStatement */:
case 199 /* OmittedExpression */:
case 224 /* DebuggerStatement */:
// No need to visit nodes with no children.
return node;
// Names
case 142 /* QualifiedName */:
return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts
.isIdentifier));
case 143 /* ComputedPropertyName */:
return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
// Signature elements
case 145 /* Parameter */:
return ts.updateParameter(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor
, ts.isModifier), node.dotDotDotToken, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode
, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true));
case 146 /* Decorator */:
return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression));
// Type member
case 148 /* PropertyDeclaration */:
return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor
, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true
), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true));
case 150 /* MethodDeclaration */:
return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor
, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter),
visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody
(node.body, visitor, context));
case 151 /* Constructor */:
return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor
, ts.isModifier), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context));
case 152 /* GetAccessor */:
return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor
, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitNode
(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context));
case 153 /* SetAccessor */:
return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor
, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitFunctionBody
(node.body, visitor, context));
// Binding patterns
case 173 /* ObjectBindingPattern */:
return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement));
case 174 /* ArrayBindingPattern */:
return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement));
case 175 /* BindingElement */:
return ts.updateBindingElement(node, node.dotDotDotToken, visitNode(node.propertyName, visitor, ts.isPropertyName, /*
optional*/ true), visitNode(node.name, ...n/a
function visitFunctionBody(node, visitor, context) {
context.resumeLexicalEnvironment();
var updated = visitNode(node, visitor, ts.isConciseBody);
var declarations = context.endLexicalEnvironment();
if (ts.some(declarations)) {
var block = ts.convertToFunctionBody(updated);
var statements = mergeLexicalEnvironment(block.statements, declarations);
return ts.updateBlock(block, statements);
}
return updated;
}n/a
function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
context.startLexicalEnvironment();
statements = visitNodes(statements, visitor, ts.isStatement, start);
if (ensureUseStrict && !ts.startsWithUseStrict(statements)) {
statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)),
statements);
}
var declarations = context.endLexicalEnvironment();
return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements);
}n/a
function visitNode(node, visitor, test, optional, lift) {
if (node === undefined || visitor === undefined) {
return node;
}
aggregateTransformFlags(node);
var visited = visitor(node);
if (visited === node) {
return node;
}
var visitedNode;
if (visited === undefined) {
if (!optional) {
Debug.failNotOptional();
}
return undefined;
}
else if (ts.isArray(visited)) {
visitedNode = (lift || extractSingleNode)(visited);
}
else {
visitedNode = visited;
}
Debug.assertNode(visitedNode, test);
aggregateTransformFlags(visitedNode);
return visitedNode;
}n/a
function visitNodes(nodes, visitor, test, start, count) {
if (nodes === undefined) {
return undefined;
}
var updated;
// Ensure start and count have valid values
var length = nodes.length;
if (start === undefined || start < 0) {
start = 0;
}
if (count === undefined || count > length - start) {
count = length - start;
}
if (start > 0 || count < length) {
// If we are not visiting all of the original nodes, we must always create a new array.
// Since this is a fragment of a node array, we do not copy over the previous location
// and will only copy over `hasTrailingComma` if we are including the last element.
updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
}
// Visit each original node.
for (var i = 0; i < count; i++) {
var node = nodes[i + start];
aggregateTransformFlags(node);
var visited = node !== undefined ? visitor(node) : undefined;
if (updated !== undefined || visited === undefined || visited !== node) {
if (updated === undefined) {
// Ensure we have a copy of `nodes`, up to the current index.
updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
ts.setTextRange(updated, nodes);
}
if (visited) {
if (ts.isArray(visited)) {
for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
var visitedNode = visited_1[_i];
Debug.assertNode(visitedNode, test);
aggregateTransformFlags(visitedNode);
updated.push(visitedNode);
}
}
else {
Debug.assertNode(visited, test);
aggregateTransformFlags(visited);
updated.push(visited);
}
}
}
}
return updated || nodes;
}n/a
function visitParameterList(nodes, visitor, context) {
context.startLexicalEnvironment();
var updated = visitNodes(nodes, visitor, ts.isParameterDeclaration);
context.suspendLexicalEnvironment();
return updated;
}n/a
function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
var lineCount = lineMap.length;
var firstCommentLineIndent = void 0;
for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
var nextLineStart = (currentLine + 1) === lineCount
? text.length + 1
: lineMap[currentLine + 1];
if (pos !== commentPos) {
// If we are not emitting first line, we need to write the spaces to adjust the alignment
if (firstCommentLineIndent === undefined) {
firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
}
// These are number of spaces writer is going to write at current indent
var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
// Number of spaces we want to be writing
// eg: Assume writer indent
// module m {
// /* starts at character 9 this is line 1
// * starts at character pos 4 line --1 = 8 - 8 + 3
// More left indented comment */ --2 = 8 - 8 + 2
// class c { }
// }
// module m {
// /* this is line 1 -- Assume current writer indent 8
// * line --3 = 8 - 4 + 5
// More right indented comment */ --4 = 8 - 4 + 11
// class c { }
// }
var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart
);
if (spacesToEmit > 0) {
var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
// Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
writer.rawWrite(indentSizeSpaceString);
// Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
while (numberOfSingleSpacesToEmit) {
writer.rawWrite(" ");
numberOfSingleSpacesToEmit--;
}
}
else {
// No spaces to emit write empty string
writer.rawWrite("");
}
}
// Write the comment line text
writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
pos = nextLineStart;
}
}
else {
// Single line comment of style //....
writer.write(text.substring(commentPos, commentEnd));
}
}n/a
function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) {
var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles
);
var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions
().noEmit;
if (!emitSkipped) {
var sourceFiles = sourceFileOrBundle.kind === 264 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle];
var declarationOutput = emitDeclarationResult.referencesOutput
+ getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo
);
ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles
);
}
return emitSkipped;
function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) {
var appliedSyncOutputPos = 0;
var declarationOutput = "";
// apply asynchronous additions to the synchronous output
ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) {
if (aliasEmitInfo.asynchronousOutput) {
declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos);
declarationOutput += getDeclarationOutput(aliasEmitInfo.asynchronousOutput, aliasEmitInfo.subModuleElementDeclarationEmitInfo
);
appliedSyncOutputPos = aliasEmitInfo.outputPos;
}
});
declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos);
return declarationOutput;
}
}n/a
function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
}, sourceFiles);
}n/a
function zipWith(arrayA, arrayB, callback) {
Debug.assert(arrayA.length === arrayB.length);
for (var i = 0; i < arrayA.length; i++) {
callback(arrayA[i], arrayB[i], i);
}
}n/a
function spanInSourceFileAtLocation(sourceFile, position) {
// Cannot set breakpoint in dts file
if (sourceFile.isDeclarationFile) {
return undefined;
}
var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position);
var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
// Get previous token if the token is returned starts on new line
// eg: let x =10; |--- cursor is here
// let y = 10;
// token at position will return let keyword on second line as the token but we would like to use
// token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line
tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile);
// It's a blank line
if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) {
return undefined;
}
}
// Cannot set breakpoint in ambient declarations
if (ts.isInAmbientContext(tokenAtLocation)) {
return undefined;
}
// Get the span in the node based on its syntax
return spanInNode(tokenAtLocation);
function textSpan(startNode, endNode) {
var start = startNode.decorators ?
ts.skipTrivia(sourceFile.text, startNode.decorators.end) :
startNode.getStart(sourceFile);
return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd());
}
function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) {
return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent));
}
function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
return spanInNode(node);
}
return spanInNode(otherwiseOnNode);
}
function spanInNodeArray(nodeArray) {
return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end);
}
function spanInPreviousNode(node) {
return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
}
function spanInNextNode(node) {
return spanInNode(ts.findNextToken(node, node.parent));
}
function spanInNode(node) {
if (node) {
switch (node.kind) {
case 207 /* VariableStatement */:
// Span on first variable declaration
return spanInVariableDeclaration(node.declarationList.declarations[0]);
case 225 /* VariableDeclaration */:
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
return spanInVariableDeclaration(node);
case 145 /* Parameter */:
return spanInParameterDeclaration(node);
case 227 /* FunctionDeclaration */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
case 151 /* Constructor */:
case 185 /* FunctionExpression */:
case 186 /* ArrowFunction */:
return spanInFunctionDeclaration(node);
case 206 /* Block */:
if (ts.isFunctionBlock(node)) {
return spanInFunctionBlock(node);
}
// Fall through
case 233 /* ModuleBlock */:
return spanInBlock(node);
case 258 /* CatchClause */:
return spanInBlock(node.block);
case 209 /* ExpressionStatement */:
// span on the expression
return textSpan(node.expression);
case 2 ...n/a
function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) {
// Compute all the completion symbols again.
var completionData = getCompletionData(typeChecker, log, sourceFile, position);
if (completionData) {
var symbols = completionData.symbols, location_1 = completionData.location;
// Find the symbol with the matching entry name.
// We don't need to perform character checks here because we're only comparing the
// name against 'entryName' (which is known to be good), not building a new
// completion entry.
var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions
.target, /*performCharacterChecks*/ false, location_1) === entryName ? s : undefined; });
if (symbol) {
var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_1
, location_1, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind;
return {
name: entryName,
kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
kind: symbolKind,
displayParts: displayParts,
documentation: documentation
};
}
}
// Didn't find a symbol with this name. See if we can find a keyword instead.
var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; });
if (keywordCompletion) {
return {
name: entryName,
kind: ts.ScriptElementKind.keyword,
kindModifiers: ts.ScriptElementKindModifier.none,
displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)],
documentation: undefined
};
}
return undefined;
}n/a
function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) {
// Compute all the completion symbols again.
var completionData = getCompletionData(typeChecker, log, sourceFile, position);
if (completionData) {
var symbols = completionData.symbols, location_2 = completionData.location;
// Find the symbol with the matching entry name.
// We don't need to perform character checks here because we're only comparing the
// name against 'entryName' (which is known to be good), not building a new
// completion entry.
return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.
target, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; });
}
return undefined;
}n/a
function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) {
if (ts.isInReferenceComment(sourceFile, position)) {
return getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host);
}
if (ts.isInString(sourceFile, position)) {
return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log);
}
var completionData = getCompletionData(typeChecker, log, sourceFile, position);
if (!completionData) {
return undefined;
}
var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData
.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName
= completionData.isJsDocTagName;
if (isJsDocTagName) {
// If the current position is a jsDoc tag name, only tag names should be provided for completion
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries
() };
}
var entries = [];
if (ts.isSourceFileJavaScript(sourceFile)) {
var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker
, compilerOptions.target, log);
ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target));
}
else {
if (!symbols || symbols.length === 0) {
if (sourceFile.languageVariant === 1 /* JSX */ &&
location.parent && location.parent.kind === 251 /* JsxClosingElement */) {
// In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag
,
// instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element
.
// For example:
// var x = <div> </ /*1*/> completion list at "1" will contain "div" with type any
var tagName = location.parent.parent.openingElement.tagName;
entries.push({
name: tagName.text,
kind: undefined,
kindModifiers: undefined,
sortText: "0",
});
}
else {
return undefined;
}
}
getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions
.target, log);
}
// Add keywords if this is not a member completion list
if (!isMemberCompletion && !isJsDocTagName) {
ts.addRange(entries, keywordCompletions);
}
return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation
, entries: entries };
}n/a
function CoreServicesShimHostAdapter(shimHost) {
var _this = this;
this.shimHost = shimHost;
this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false
;
if ("directoryExists" in this.shimHost) {
this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
}
if ("realpath" in this.shimHost) {
this.realpath = function (path) { return _this.shimHost.realpath(path); };
}
}n/a
fileExists = function (fileName) {
return this.shimHost.fileExists(fileName);
}n/a
getDirectories = function (path) {
return JSON.parse(this.shimHost.getDirectories(path));
}n/a
readDirectory = function (rootDir, extensions, exclude, include, depth) {
// Wrap the API changes for 2.0 release. This try/catch
// should be removed once TypeScript 2.0 has shipped.
try {
var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost
.getCurrentDirectory());
return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern
.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth));
}
catch (e) {
var results = [];
for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
var extension = extensions_2[_i];
for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) {
var file = _b[_a];
if (!ts.contains(results, file)) {
results.push(file);
}
}
}
return results;
}
}n/a
readDirectoryFallback = function (rootDir, extension, exclude) {
return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)));
}n/a
readFile = function (fileName) {
return this.shimHost.readFile(fileName);
}n/a
function assert(expression, message, verboseDebugInfo) {
if (!expression) {
var verboseDebugString = "";
if (verboseDebugInfo) {
verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo();
}
debugger;
throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString);
}
}n/a
function noop() { }n/a
function noop() { }n/a
function noop() { }n/a
function noop() { }n/a
function noop() { }n/a
function fail(message) {
Debug.assert(/*expression*/ false, message);
}n/a
function noop() { }n/a
function noop() { }n/a
function shouldAssert(level) {
return Debug.currentAssertionLevel >= level;
}n/a
function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) {
var node = ts.getTouchingWord(sourceFile, position);
return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights
(node, sourceFile));
}n/a
function convertReferences(referenceSymbols) {
return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; });
}n/a
function findReferencedSymbols(typeChecker, cancellationToken, sourceFiles, sourceFile, position, findInStrings, findInComments, isForRename) {
var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
return getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, isForRename
);
}n/a
function getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result) {
var refSymbol = typeChecker.getSymbolAtLocation(node);
var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration);
if (shorthandSymbol) {
for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) {
var declaration = _a[_i];
if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) {
result.push(getReferenceEntryFromNode(declaration));
}
}
}
}n/a
function getReferenceEntryFromNode(node) {
var start = node.getStart();
var end = node.getEnd();
if (node.kind === 9 /* StringLiteral */) {
start += 1;
end -= 1;
}
return {
fileName: node.getSourceFile().fileName,
textSpan: ts.createTextSpanFromBounds(start, end),
isWriteAccess: isWriteAccess(node),
isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node)
};
}n/a
function getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, isForRename , implementations) {
if (!implementations) {
var special = getReferencedSymbolsSpecial(node, sourceFiles, typeChecker, cancellationToken);
if (special) {
return special;
}
}
// `getSymbolAtLocation` normally returns the symbol of the class when given the constructor keyword,
// so we have to specify that we want the constructor symbol.
var symbol = typeChecker.getSymbolAtLocation(node);
// Could not find a symbol e.g. unknown identifier
if (!symbol) {
if (!implementations && node.kind === 9 /* StringLiteral */) {
return getReferencesForStringLiteral(node, sourceFiles, typeChecker, cancellationToken);
}
// Can't have references to something that we have no symbol for.
return undefined;
}
var declarations = symbol.declarations;
// The symbol was an internal symbol and does not have a declaration e.g. undefined symbol
if (!declarations || !declarations.length) {
return undefined;
}
var _a = followAliases(symbol, node, typeChecker, isForRename), aliasedSymbol = _a.symbol, shorthandModuleSymbol = _a.shorthandModuleSymbol
;
symbol = aliasedSymbol;
// Build the set of symbols to search for, initially it has only the current symbol
var searchSymbols = populateSearchSymbolSet(symbol, node, typeChecker, implementations);
if (shorthandModuleSymbol) {
searchSymbols.push(shorthandModuleSymbol);
}
// Compute the meaning from the location and the symbol it references
var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), declarations);
var result = [];
// Maps from a symbol ID to the ReferencedSymbol entry in 'result'.
var symbolToIndex = [];
var inheritsFromCache = ts.createMap();
// Get the text to search for.
// Note: if this is an external module symbol, the name doesn't include quotes.
var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node));
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
var scope = getSymbolScope(symbol);
if (scope) {
getRefs(scope, declaredName);
}
else {
var isDefault = ts.isExportDefaultSymbol(symbol);
var internedName = isDefault ? symbol.valueDeclaration.localSymbol.name : getInternedName(symbol, node);
for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
var sourceFile = sourceFiles_5[_i];
cancellationToken.throwIfCancellationRequested();
var searchName = (isDefault ? getDefaultImportName(symbol, sourceFile, typeChecker) : undefined) ||
(sourceFileHasName(sourceFile, internedName) ? declaredName : undefined);
if (searchName !== undefined) {
getRefs(sourceFile, searchName);
}
}
}
return result;
function getRefs(scope, searchName) {
getReferencesInNode(scope, symbol, searchName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex
, implementations, typeChecker, cancellationToken, searchSymbols, inheritsFromCache);
}
}n/a
function getDefinitionAtPosition(program, sourceFile, position) {
/// Triple slash reference comments
var comment = findReferenceInPosition(sourceFile.referencedFiles, position);
if (comment) {
var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment);
if (referenceFile) {
return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)];
}
return undefined;
}
// Type reference directives
var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
var referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
return referenceFile && referenceFile.resolvedFileName &&
[getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)];
}
var node = ts.getTouchingPropertyName(sourceFile, position);
if (node === sourceFile) {
return undefined;
}
// Labels
if (ts.isJumpStatementTarget(node)) {
var labelName = node.text;
var label = ts.getTargetLabel(node.parent, node.text);
return label ? [createDefinitionInfoFromName(label, ts.ScriptElementKind.label, labelName, /*containerName*/ undefined)] :
undefined;
}
var typeChecker = program.getTypeChecker();
var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
if (calledDeclaration) {
return [createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration)];
}
var symbol = typeChecker.getSymbolAtLocation(node);
// Could not find a symbol e.g. node is string or number keyword,
// or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol
if (!symbol) {
return undefined;
}
// If this is an alias, and the request came at the declaration location
// get the aliased symbol instead. This allows for goto def on an import e.g.
// import {A, B} from "mod";
// to jump to the implementation directly.
if (symbol.flags & 8388608 /* Alias */) {
var declaration = symbol.declarations[0];
// Go to the original declaration for cases:
//
// (1) when the aliased symbol was declared in the location(parent).
// (2) when the aliased symbol is originating from a named import.
//
if (node.kind === 70 /* Identifier */ &&
(node.parent === declaration ||
(declaration.kind === 241 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 240 /* NamedImports
*/))) {
symbol = typeChecker.getAliasedSymbol(symbol);
}
}
// Because name in short-hand property assignment has two different meanings: property name and property value,
// using go-to-definition at such position should go to the variable declaration of the property value rather than
// go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition
// is performed at the location of property access, we would like to go to definition of the property in the short-hand
// assignment. This case and others are handled by the following code.
if (node.parent.kind === 260 /* ShorthandPropertyAssignment */) {
var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration);
if (!shorthandSymbol) {
return [];
}
var shorthandDeclarations = shorthandSymbol.getDeclarations();
var shorthandSymbolKind_1 = ts.SymbolDisplay.getSymbolKind(typeChecker, shorthandSymbol, node);
var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol);
var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node);
return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1
, shorthandSymbolName_1, shorthandContainerName_1); }); ...n/a
function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) {
var node = ts.getTouchingPropertyName(sourceFile, position);
if (node === sourceFile) {
return undefined;
}
var symbol = typeChecker.getSymbolAtLocation(node);
if (!symbol) {
return undefined;
}
var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node);
if (!type) {
return undefined;
}
if (type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */)) {
var result_5 = [];
ts.forEach(type.types, function (t) {
if (t.symbol) {
ts.addRange(/*to*/ result_5, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node));
}
});
return result_5;
}
if (!type.symbol) {
return undefined;
}
return getDefinitionFromSymbol(typeChecker, type.symbol, node);
}n/a
function getImplementationAtPosition(typeChecker, cancellationToken, sourceFiles, node) {
// If invoked directly on a shorthand property assignment, then return
// the declaration of the symbol being assigned (not the symbol being assigned to).
if (node.parent.kind === 260 /* ShorthandPropertyAssignment */) {
var result = [];
ts.FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result);
return result.length > 0 ? result : undefined;
}
else if (node.kind === 96 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
// need to "Find all References"
var symbol = typeChecker.getSymbolAtLocation(node);
return symbol.valueDeclaration && [ts.FindAllReferences.getReferenceEntryFromNode(symbol.valueDeclaration)];
}
else {
// Perform "Find all References" and retrieve only those that are implementations
var referencedSymbols = ts.FindAllReferences.getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles
, /*findInStrings*/ false, /*findInComments*/ false, /*isForRename*/ false, /*implementations*/ true);
var result = ts.flatMap(referencedSymbols, function (symbol) {
return ts.map(symbol.references, function (_a) {
var textSpan = _a.textSpan, fileName = _a.fileName;
return ({ textSpan: textSpan, fileName: fileName });
});
});
return result && result.length > 0 ? result : undefined;
}
}n/a
function getAllJsDocCompletionEntries() {
return jsDocCompletionEntries || (jsDocCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
return {
name: tagName,
kind: ts.ScriptElementKind.keyword,
kindModifiers: "",
sortText: "0",
};
}));
}n/a
function getDocCommentTemplateAtPosition(newLine, sourceFile, position) {
// Check if in a context where we don't want to perform any insertion
if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) {
return undefined;
}
var tokenAtPos = ts.getTokenAtPosition(sourceFile, position);
var tokenStart = tokenAtPos.getStart();
if (!tokenAtPos || tokenStart < position) {
return undefined;
}
// TODO: add support for:
// - enums/enum members
// - interfaces
// - property declarations
// - potentially property assignments
var commentOwner;
findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) {
switch (commentOwner.kind) {
case 227 /* FunctionDeclaration */:
case 150 /* MethodDeclaration */:
case 151 /* Constructor */:
case 228 /* ClassDeclaration */:
case 207 /* VariableStatement */:
break findOwner;
case 263 /* SourceFile */:
return undefined;
case 232 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
// then we must be somewhere within a dotted namespace name; however we don't
// want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'.
if (commentOwner.parent.kind === 232 /* ModuleDeclaration */) {
return undefined;
}
break findOwner;
}
}
if (!commentOwner || commentOwner.getStart() < position) {
return undefined;
}
var parameters = getParametersForJsDocOwningNode(commentOwner);
var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position);
var lineStart = sourceFile.getLineStarts()[posLineAndChar.line];
var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character);
var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName);
var docParams = "";
for (var i = 0; i < parameters.length; i++) {
var currentName = parameters[i].name;
var paramName = currentName.kind === 70 /* Identifier */ ?
currentName.text :
"param" + i;
if (isJavaScriptFile) {
docParams += indentationStr + " * @param {any} " + paramName + newLine;
}
else {
docParams += indentationStr + " * @param " + paramName + newLine;
}
}
// A doc comment consists of the following
// * The opening comment line
// * the first line (without a param) for the object's untagged info (this is also where the caret ends up)
// * the '@param'-tagged lines
// * TODO: other tags.
// * the closing comment line
// * if the caret was directly in front of the object, then we add an extra line and indentation.
var preamble = "/**" + newLine +
indentationStr + " * ";
var result = preamble + newLine +
docParams +
indentationStr + " */" +
(tokenStart === position ? newLine + indentationStr : "");
return { newText: result, caretOffset: preamble.length };
}n/a
function getJsDocCommentsFromDeclarations(declarations) {
// Only collect doc comments from duplicate declarations once:
// In case of a union property there might be same declaration multiple times
// which only varies in type parameter
// Eg. const a: Array<string> | Array<number>; a.length
// The property length will have two declarations of property length coming
// from Array<T> - Array<string> and Array<number>
var documentationComment = [];
forEachUnique(declarations, function (declaration) {
var comments = ts.getCommentsFromJSDoc(declaration);
if (!comments) {
return;
}
for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) {
var comment = comments_3[_i];
if (comment) {
if (documentationComment.length) {
documentationComment.push(ts.lineBreakPart());
}
documentationComment.push(ts.textPart(comment));
}
}
});
return documentationComment;
}n/a
function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typeAcquisition, unresolvedImports ) {
// A typing name to typing file path mapping
var inferredTypings = ts.createMap();
if (!typeAcquisition || !typeAcquisition.enable) {
return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
}
// Only infer typings for .js and .jsx files
fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) {
var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f));
return kind === 1 /* JS */ || kind === 2 /* JSX */;
});
if (!safeList) {
var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
safeList = result.config ? ts.createMapFromTemplate(result.config) : EmptySafeList;
}
var filesToWatch = [];
// Directories to search for package.json, bower.json and other typing information
var searchDirs = [];
var exclude = [];
mergeTypings(typeAcquisition.include);
exclude = typeAcquisition.exclude || [];
var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath);
if (projectRootPath) {
possibleSearchDirs.push(projectRootPath);
}
searchDirs = ts.deduplicate(possibleSearchDirs);
for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) {
var searchDir = searchDirs_1[_i];
var packageJsonPath = ts.combinePaths(searchDir, "package.json");
getTypingNamesFromJson(packageJsonPath, filesToWatch);
var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
getTypingNamesFromJson(bowerJsonPath, filesToWatch);
var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
getTypingNamesFromNodeModuleFolder(nodeModulesPath);
}
getTypingNamesFromSourceFileNames(fileNames);
// add typings for unresolved imports
if (unresolvedImports) {
for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) {
var moduleId = unresolvedImports_1[_a];
var typingName = nodeCoreModules.has(moduleId) ? "node" : moduleId;
if (!inferredTypings.has(typingName)) {
inferredTypings.set(typingName, undefined);
}
}
}
// Add the cached typing locations for inferred typings that are already installed
packageNameToTypingLocation.forEach(function (typingLocation, name) {
if (inferredTypings.has(name) && inferredTypings.get(name) === undefined) {
inferredTypings.set(name, typingLocation);
}
});
// Remove typings that the user has added to the exclude list
for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) {
var excludeTypingName = exclude_1[_b];
inferredTypings.delete(excludeTypingName);
}
var newTypingNames = [];
var cachedTypingPaths = [];
inferredTypings.forEach(function (inferred, typing) {
if (inferred !== undefined) {
cachedTypingPaths.push(inferred);
}
else {
newTypingNames.push(typing);
}
});
return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
/**
* Merge a given list of typingNames to the inferredTypings map
*/
function mergeTypings(typingNames) {
if (!typingNames) {
return;
}
for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) {
var typing = typingNames_1[_i];
if (!inferredTypings.has(typing)) {
inferredTypings.set(typing, undefined);
}
}
}
/**
* Get the typing info from common package manager json files like package.json or bower.json
*/
function getTypingNamesFromJson(jsonPath, filesToWatch) {
if (host.fileExists(jsonPath)) {
filesToWatch.push(jsonPath);
}
var result = ts.readConfigFile(jsonPath, function (pat ...n/a
function LanguageServiceShimHostAdapter(shimHost) {
var _this = this;
this.shimHost = shimHost;
this.loggingEnabled = false;
this.tracingEnabled = false;
// if shimHost is a COM object then property check will become method call with no arguments.
// 'in' does not have this effect.
if ("getModuleResolutionsForFile" in this.shimHost) {
this.resolveModuleNames = function (moduleNames, containingFile) {
var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile));
return ts.map(moduleNames, function (name) {
var result = ts.getProperty(resolutionsInFile, name);
return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false
} : undefined;
});
};
}
if ("directoryExists" in this.shimHost) {
this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
}
if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile));
return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); });
};
}
}n/a
error = function (s) {
this.shimHost.error(s);
}n/a
fileExists = function (path) {
return this.shimHost.fileExists(path);
}n/a
getCancellationToken = function () {
var hostCancellationToken = this.shimHost.getCancellationToken();
return new ThrottledCancellationToken(hostCancellationToken);
}n/a
getCompilationSettings = function () {
var settingsJson = this.shimHost.getCompilationSettings();
// TODO: should this be '==='?
if (settingsJson == null || settingsJson == "") {
throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
}
var compilerOptions = JSON.parse(settingsJson);
// permit language service to handle all files (filtering should be performed on the host side)
compilerOptions.allowNonTsExtensions = true;
return compilerOptions;
}n/a
getCurrentDirectory = function () {
return this.shimHost.getCurrentDirectory();
}n/a
getDefaultLibFileName = function (options) {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
}n/a
getDirectories = function (path) {
return JSON.parse(this.shimHost.getDirectories(path));
}n/a
getLocalizedDiagnosticMessages = function () {
var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
if (diagnosticMessagesJson == null || diagnosticMessagesJson == "") {
return null;
}
try {
return JSON.parse(diagnosticMessagesJson);
}
catch (e) {
this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format");
return null;
}
}n/a
getProjectVersion = function () {
if (!this.shimHost.getProjectVersion) {
// shimmed host does not support getProjectVersion
return undefined;
}
return this.shimHost.getProjectVersion();
}n/a
getScriptFileNames = function () {
var encoded = this.shimHost.getScriptFileNames();
return this.files = JSON.parse(encoded);
}n/a
getScriptKind = function (fileName) {
if ("getScriptKind" in this.shimHost) {
return this.shimHost.getScriptKind(fileName);
}
else {
return 0 /* Unknown */;
}
}n/a
getScriptSnapshot = function (fileName) {
var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot);
}n/a
getScriptVersion = function (fileName) {
return this.shimHost.getScriptVersion(fileName);
}n/a
getTypeRootsVersion = function () {
if (!this.shimHost.getTypeRootsVersion) {
return 0;
}
return this.shimHost.getTypeRootsVersion();
}n/a
log = function (s) {
if (this.loggingEnabled) {
this.shimHost.log(s);
}
}n/a
readDirectory = function (path, extensions, exclude, include, depth) {
var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory
());
return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern
, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth));
}n/a
readFile = function (path, encoding) {
return this.shimHost.readFile(path, encoding);
}n/a
trace = function (s) {
if (this.tracingEnabled) {
this.shimHost.trace(s);
}
}n/a
useCaseSensitiveFileNames = function () {
return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
}n/a
function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) {
var patternMatcher = ts.createPatternMatcher(searchValue);
var rawItems = [];
var _loop_4 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) {
return "continue";
}
ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) {
if (declarations) {
// First do a quick check to see if the name of the declaration matches the
// last portion of the (possibly) dotted name they're searching for.
var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name);
if (!matches) {
return; // continue to next named declarations
}
for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
var declaration = declarations_9[_i];
// It was a match! If the pattern has dots in it, then also see if the
// declaration container matches as well.
if (patternMatcher.patternContainsDots) {
var containers = getContainers(declaration);
if (!containers) {
return true; // Break out of named declarations and go to the next source file.
}
matches = patternMatcher.getMatches(containers, name);
if (!matches) {
return; // continue to next named declarations
}
}
var fileName = sourceFile.fileName;
var matchKind = bestMatchKind(matches);
rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive
(matches), declaration: declaration });
}
}
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) {
var sourceFile = sourceFiles_8[_i];
_loop_4(sourceFile);
}
// Remove imports when the imported declaration is already in the list and has the same name.
rawItems = ts.filter(rawItems, function (item) {
var decl = item.declaration;
if (decl.kind === 238 /* ImportClause */ || decl.kind === 241 /* ImportSpecifier */ || decl.kind === 236 /* ImportEqualsDeclaration
*/) {
var importer = checker.getSymbolAtLocation(decl.name);
var imported = checker.getAliasedSymbol(importer);
return importer.name !== imported.name;
}
else {
return true;
}
});
rawItems.sort(compareNavigateToItems);
if (maxResultCount !== undefined) {
rawItems = rawItems.slice(0, maxResultCount);
}
var items = ts.map(rawItems, createNavigateToItem);
return items;
function allMatchesAreCaseSensitive(matches) {
ts.Debug.assert(matches.length > 0);
// This is a case sensitive match, only if all the submatches were case sensitive.
for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) {
var match = matches_2[_i];
if (!match.isCaseSensitive) {
return false;
}
}
return true;
}
function getTextOfIdentifierOrLiteral(node) {
if (node) {
if (node.kind === 70 /* Identifier */ ||
node.kind === 9 /* StringLiteral */ ||
node.kind === 8 /* NumericLiteral */) {
return node.text;
}
}
return undefined;
}
function tryAddSingleDeclarationName(declaration, containers) {
if (declaration && declaration.name) {
var text = ...n/a
function getNavigationBarItems(sourceFile) {
curSourceFile = sourceFile;
var result = ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem);
curSourceFile = undefined;
return result;
}n/a
function getNavigationTree(sourceFile) {
curSourceFile = sourceFile;
var result = convertToTree(rootNavigationBarNode(sourceFile));
curSourceFile = undefined;
return result;
}n/a
function collectElements(sourceFile) {
var elements = [];
var collapseText = "...";
function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) {
if (hintSpanNode && startElement && endElement) {
var span_12 = {
textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end),
hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span_12);
}
}
function addOutliningSpanComments(commentSpan, autoCollapse) {
if (commentSpan) {
var span_13 = {
textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span_13);
}
}
function addOutliningForLeadingCommentsForNode(n) {
var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile);
if (comments) {
var firstSingleLineCommentStart = -1;
var lastSingleLineCommentEnd = -1;
var isFirstSingleLineComment = true;
var singleLineCommentCount = 0;
for (var _i = 0, comments_4 = comments; _i < comments_4.length; _i++) {
var currentComment = comments_4[_i];
// For single line comments, combine consecutive ones (2 or more) into
// a single span from the start of the first till the end of the last
if (currentComment.kind === 2 /* SingleLineCommentTrivia */) {
if (isFirstSingleLineComment) {
firstSingleLineCommentStart = currentComment.pos;
}
isFirstSingleLineComment = false;
lastSingleLineCommentEnd = currentComment.end;
singleLineCommentCount++;
}
else if (currentComment.kind === 3 /* MultiLineCommentTrivia */) {
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd
);
addOutliningSpanComments(currentComment, /*autoCollapse*/ false);
singleLineCommentCount = 0;
lastSingleLineCommentEnd = -1;
isFirstSingleLineComment = true;
}
}
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd
);
}
}
function combineAndAddMultipleSingleLineComments(count, start, end) {
// Only outline spans of two or more consecutive single line comments
if (count > 1) {
var multipleSingleLineComments = {
pos: start,
end: end,
kind: 2 /* SingleLineCommentTrivia */
};
addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false);
}
}
function autoCollapse(node) {
return ts.isFunctionBlock(node) && node.parent.kind !== 186 /* ArrowFunction */;
}
var depth = 0;
var maxDepth = 20;
function walk(n) {
if (depth > maxDepth) {
return;
}
if (ts.isDeclaration(n)) {
addOutliningForLeadingCommentsForNode(n);
}
switch (n.kind) {
case 206 /* Block */:
if (!ts.isFunctionBlock(n)) {
var parent = n.parent;
var openBrace = ts.findChildOfKind(n, 16 /* OpenBraceToken */, sourceFile);
var closeBrace = ts.findChildOfKind(n, 17 /* CloseBraceToken */, sourceFile);
// Check if the block is standalone, or 'attached' to some parent statement.
// If the latter, we want to collapse the block, but consider its hint span ...n/a
function getRenameInfo(typeChecker, defaultLibFileName, getCanonicalFileName, sourceFile, position) {
var getCanonicalDefaultLibName = ts.memoize(function () { return getCanonicalFileName(ts.normalizePath(defaultLibFileName)); });
var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true);
var renameInfo = node && nodeIsEligibleForRename(node)
? getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile)
: undefined;
return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element);
function isDefinedInLibraryFile(declaration) {
if (!defaultLibFileName) {
return false;
}
var sourceFile = declaration.getSourceFile();
var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile.fileName));
return canonicalName === getCanonicalDefaultLibName();
}
}n/a
function fromString(text) {
return new StringScriptSnapshot(text);
}n/a
function getContainingArgumentInfo(node, position, sourceFile) {
for (var n = node; n.kind !== 263 /* SourceFile */; n = n.parent) {
if (ts.isFunctionBlock(n)) {
return undefined;
}
// If the node is not a subspan of its parent, this is a big problem.
// There have been crashes that might be caused by this violation.
if (n.pos < n.parent.pos || n.end > n.parent.end) {
ts.Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind);
}
var argumentInfo = getImmediatelyContainingArgumentInfo(n, position, sourceFile);
if (argumentInfo) {
return argumentInfo;
}
// TODO: Handle generic call with incomplete syntax
}
return undefined;
}n/a
function getImmediatelyContainingArgumentInfo(node, position, sourceFile) {
if (node.parent.kind === 180 /* CallExpression */ || node.parent.kind === 181 /* NewExpression */) {
var callExpression = node.parent;
// There are 3 cases to handle:
// 1. The token introduces a list, and should begin a sig help session
// 2. The token is either not associated with a list, or ends a list, so the session should end
// 3. The token is buried inside a list, and should give sig help
//
// The following are examples of each:
//
// Case 1:
// foo<#T, U>(#a, b) -> The token introduces a list, and should begin a sig help session
// Case 2:
// fo#o<T, U>#(a, b)# -> The token is either not associated with a list, or ends a list, so the session should
end
// Case 3:
// foo<T#, U#>(a#, #b#) -> The token is buried inside a list, and should give sig help
// Find out if 'node' is an argument, a type argument, or neither
if (node.kind === 26 /* LessThanToken */ ||
node.kind === 18 /* OpenParenToken */) {
// Find the list that starts right *after* the < or ( token.
// If the user has just opened a list, consider this item 0.
var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile);
var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos;
ts.Debug.assert(list !== undefined);
return {
kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */,
invocation: callExpression,
argumentsSpan: getApplicableSpanForArguments(list, sourceFile),
argumentIndex: 0,
argumentCount: getArgumentCount(list)
};
}
// findListItemInfo can return undefined if we are not in parent's argument list
// or type argument list. This includes cases where the cursor is:
// - To the right of the closing paren, non-substitution template, or template tail.
// - Between the type arguments and the arguments (greater than token)
// - On the target of the call (parent.func)
// - On the 'new' keyword in a 'new' expression
var listItemInfo = ts.findListItemInfo(node);
if (listItemInfo) {
var list = listItemInfo.list;
var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos;
var argumentIndex = getArgumentIndex(list, node);
var argumentCount = getArgumentCount(list);
ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount
+ " < " + argumentIndex);
return {
kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */,
invocation: callExpression,
argumentsSpan: getApplicableSpanForArguments(list, sourceFile),
argumentIndex: argumentIndex,
argumentCount: argumentCount
};
}
return undefined;
}
else if (node.kind === 12 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 182 /* TaggedTemplateExpression */) {
// Check if we're actually inside the template;
// otherwise we'll fall out and return undefined.
if (ts.isInsideTemplateLiteral(node, position)) {
return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile);
}
}
else if (node.kind === 13 /* TemplateHead */ && node.parent.parent.kind === 182 /* TaggedTemplateExpression */) {
var templateExpression = node.parent;
var tagExpression = templateExpression.parent;
ts.Debug.assert(templateExpression.kind === 195 /* TemplateExpression */);
var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1;
return getArgumen ...n/a
function getSignatureHelpItems(program, sourceFile, position, cancellationToken) {
var typeChecker = program.getTypeChecker();
// Decide whether to show signature help
var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position);
if (!startingToken) {
// We are at the beginning of the file
return undefined;
}
var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile);
cancellationToken.throwIfCancellationRequested();
// Semantic filtering of signature help
if (!argumentInfo) {
return undefined;
}
var call = argumentInfo.invocation;
var candidates = [];
var resolvedSignature = typeChecker.getResolvedSignature(call, candidates);
cancellationToken.throwIfCancellationRequested();
if (!candidates.length) {
// We didn't have any sig help items produced by the TS compiler. If this is a JS
// file, then see if we can figure out anything better.
if (ts.isSourceFileJavaScript(sourceFile)) {
return createJavaScriptSignatureHelpItems(argumentInfo, program);
}
return undefined;
}
return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo, typeChecker);
}n/a
function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning ) {
if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); }
var displayParts = [];
var documentation;
var symbolFlags = symbol.flags;
var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location);
var hasAddedSymbolInfo;
var isThisExpression = location.kind === 98 /* ThisKeyword */ && ts.isExpression(location);
var type;
// Class at constructor site need to be shown as constructor apart from property,method, vars
if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 /* Class */ || symbolFlags & 8388608 /* Alias */) {
// If it is accessor they are allowed only if location is at name of the accessor
if (symbolKind === ts.ScriptElementKind.memberGetAccessorElement || symbolKind === ts.ScriptElementKind.memberSetAccessorElement
) {
symbolKind = ts.ScriptElementKind.memberVariableElement;
}
var signature = void 0;
type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location
);
if (type) {
if (location.parent && location.parent.kind === 178 /* PropertyAccessExpression */) {
var right = location.parent.name;
// Either the location is on the right of a property access, or on the left and the right is missing
if (right === location || (right && right.getFullWidth() === 0)) {
location = location.parent;
}
}
// try get the call/construct signature from the type if it matches
var callExpression = void 0;
if (location.kind === 180 /* CallExpression */ || location.kind === 181 /* NewExpression */) {
callExpression = location;
}
else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) {
callExpression = location.parent;
}
if (callExpression) {
var candidateSignatures = [];
signature = typeChecker.getResolvedSignature(callExpression, candidateSignatures);
if (!signature && candidateSignatures.length) {
// Use the first candidate:
signature = candidateSignatures[0];
}
var useConstructSignatures = callExpression.kind === 181 /* NewExpression */ || callExpression.expression.kind ===
96 /* SuperKeyword */;
var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures();
if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) {
// Get the first signature if there is one -- allSignatures may contain
// either the original signature or its target, so check for either
signature = allSignatures.length ? allSignatures[0] : undefined;
}
if (signature) {
if (useConstructSignatures && (symbolFlags & 32 /* Class */)) {
// Constructor
symbolKind = ts.ScriptElementKind.constructorImplementationElement;
addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
}
else if (symbolFlags & 8388608 /* Alias */) {
symbolKind = ts.ScriptElementKind.alias;
pushTypePart(symbolKind);
displayParts.push(ts.spacePart());
if (useConstructSignatures) {
displayParts.push(ts.keywordPart(93 /* NewKeyword */));
displayParts.push(ts.spacePart());
}
addFullSymbolName(symbol); ...n/a
function getSymbolKind(typeChecker, symbol, location) {
var flags = symbol.getFlags();
if (flags & 32 /* Class */)
return ts.getDeclarationOfKind(symbol, 198 /* ClassExpression */) ?
ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement;
if (flags & 384 /* Enum */)
return ts.ScriptElementKind.enumElement;
if (flags & 524288 /* TypeAlias */)
return ts.ScriptElementKind.typeElement;
if (flags & 64 /* Interface */)
return ts.ScriptElementKind.interfaceElement;
if (flags & 262144 /* TypeParameter */)
return ts.ScriptElementKind.typeParameterElement;
var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, flags, location);
if (result === ts.ScriptElementKind.unknown) {
if (flags & 262144 /* TypeParameter */)
return ts.ScriptElementKind.typeParameterElement;
if (flags & 8 /* EnumMember */)
return ts.ScriptElementKind.variableElement;
if (flags & 8388608 /* Alias */)
return ts.ScriptElementKind.alias;
if (flags & 1536 /* Module */)
return ts.ScriptElementKind.moduleElement;
}
return result;
}n/a
function getSymbolModifiers(symbol) {
return symbol && symbol.declarations && symbol.declarations.length > 0
? ts.getNodeModifiers(symbol.declarations[0])
: ts.ScriptElementKindModifier.none;
}n/a
function TypeScriptServicesFactory() {
this._shims = [];
}n/a
close = function () {
// Forget all the registered shims
this._shims = [];
this.documentRegistry = undefined;
}n/a
createClassifierShim = function (logger) {
try {
return new ClassifierShimObject(this, logger);
}
catch (err) {
logInternalError(logger, err);
throw err;
}
}n/a
createCoreServicesShim = function (host) {
try {
var adapter = new CoreServicesShimHostAdapter(host);
return new CoreServicesShimObject(this, host, adapter);
}
catch (err) {
logInternalError(host, err);
throw err;
}
}n/a
createLanguageServiceShim = function (host) {
try {
if (this.documentRegistry === undefined) {
this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(),
host.getCurrentDirectory());
}
var hostAdapter = new LanguageServiceShimHostAdapter(host);
var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry);
return new LanguageServiceShimObject(this, host, languageService);
}
catch (err) {
logInternalError(host, err);
throw err;
}
}n/a
getServicesVersion = function () {
return ts.servicesVersion;
}n/a
registerShim = function (shim) {
this._shims.push(shim);
}n/a
unregisterShim = function (shim) {
for (var i = 0; i < this._shims.length; i++) {
if (this._shims[i] === shim) {
delete this._shims[i];
return;
}
}
throw new Error("Invalid operation");
}n/a
function getFixes(context) {
var fixes = codeFixes[context.errorCode];
var allActions = [];
ts.forEach(fixes, function (f) {
var actions = f.getCodeActions(context);
if (actions && actions.length > 0) {
allActions = allActions.concat(actions);
}
});
return allActions;
}n/a
function getMissingMembersInsertion(classDeclaration, possiblyMissingSymbols, checker, newlineChar) {
var classMembers = classDeclaration.symbol.members;
var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.getName()); });
var insertion = "";
for (var _i = 0, missingMembers_1 = missingMembers; _i < missingMembers_1.length; _i++) {
var symbol = missingMembers_1[_i];
insertion = insertion.concat(getInsertionForMemberSymbol(symbol, classDeclaration, checker, newlineChar));
}
return insertion;
}n/a
function getStubbedMethod(visibility, name, sigString, newlineChar) {
if (sigString === void 0) { sigString = "()"; }
return "" + visibility + name + sigString + getMethodBodyStub(newlineChar);
}n/a
function getSupportedErrorCodes() {
return Object.keys(codeFixes);
}n/a
function registerCodeFix(action) {
ts.forEach(action.errorCodes, function (error) {
var fixes = codeFixes[error];
if (!fixes) {
fixes = [];
codeFixes[error] = fixes;
}
fixes.push(action);
});
}n/a
function FormattingContext(sourceFile, formattingRequestKind) {
this.sourceFile = sourceFile;
this.formattingRequestKind = formattingRequestKind;
}n/a
function Rule(Descriptor, Operation, Flag) {
if (Flag === void 0) { Flag = 0 /* None */; }
this.Descriptor = Descriptor;
this.Operation = Operation;
this.Flag = Flag;
}n/a
function RuleDescriptor(LeftTokenRange, RightTokenRange) {
this.LeftTokenRange = LeftTokenRange;
this.RightTokenRange = RightTokenRange;
}n/a
function RuleOperation(Context, Action) {
this.Context = Context;
this.Action = Action;
}n/a
function RuleOperationContext() {
var funcs = [];
for (var _i = 0; _i < arguments.length; _i++) {
funcs[_i] = arguments[_i];
}
this.customContextChecks = funcs;
}n/a
function Rules() {
///
/// Common Rules
///
// Leave comments alone
this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting
.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1 /* Ignore */));
this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2 /* SingleLineCommentTrivia */, formatting
.Shared.TokenRange.Any), formatting.RuleOperation.create1(1 /* Ignore */));
// Space after keyword but not before ; or : or ?
this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /*
SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /*
Delete */));
this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* ColonToken
*/), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext
), 8 /* Delete */));
this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /*
QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules
.IsNotBinaryOpContext), 8 /* Delete */));
this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* ColonToken */, formatting.Shared.TokenRange
.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext
), 2 /* Space */));
this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken
*/, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext
, Rules.IsConditionalOperatorContext), 2 /* Space */));
this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken */, formatting.Shared
.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /*
Delete */));
this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* SemicolonToken */, formatting.Shared.
TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /*
Space */));
// Space after }.
this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared
.TokenRange.FromRange(0 /* FirstToken */, 141 /* LastToken */, [19 /* CloseParenToken */])), formatting.RuleOperation.create2(new
formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */));
// Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace
rule not applied
this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 81 /* ElseKeyword
*/), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 105 /*
WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /*
Space */));
this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared
.TokenRange.FromTokens([21 /* CloseBracketToken */, 25 /* CommaToken */, 24 /* SemicolonToken */])), formatting.RuleOperation.create2
(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
// No space for dot
this.NoSpaceBeforeDot = ne ...n/a
function RulesBucket() {
this.rules = [];
}n/a
function RulesBucketConstructionState() {
//// The Rules list contains all the inserted rules into a rulebucket in the following order:
//// 1- Ignore rules with specific token combination
//// 2- Ignore rules with any token combination
//// 3- Context rules with specific token combination
//// 4- Context rules with any token combination
//// 5- Non-context rules with specific token combination
//// 6- Non-context rules with any token combination
////
//// The member rulesInsertionIndexBitmap is used to describe the number of rules
//// in each sub-bucket (above) hence can be used to know the index of where to insert
//// the next rule. It's a bitmap which contains 6 different sections each is given 5 bits.
////
//// Example:
//// In order to insert a rule to the end of sub-bucket (3), we get the index by adding
//// the values in the bitmap segments 3rd, 2nd, and 1st.
this.rulesInsertionIndexBitmap = 0;
}n/a
function RulesMap() {
this.map = [];
this.mapRowLength = 0;
}n/a
function RulesProvider() {
this.globalRules = new formatting.Rules();
}n/a
function formatDocument(sourceFile, rulesProvider, options) {
var span = {
pos: 0,
end: sourceFile.text.length
};
return formatSpan(span, sourceFile, options, rulesProvider, 0 /* FormatDocument */);
}n/a
function formatOnClosingCurly(position, sourceFile, rulesProvider, options) {
return formatOutermostParent(position, 17 /* CloseBraceToken */, sourceFile, options, rulesProvider, 4 /* FormatOnClosingCurlyBrace
*/);
}n/a
function formatOnEnter(position, sourceFile, rulesProvider, options) {
var line = sourceFile.getLineAndCharacterOfPosition(position).line;
if (line === 0) {
return [];
}
// After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters.
// If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as
// trailing whitespaces. So the end of the formatting span should be the later one between:
// 1. the end of the previous line
// 2. the last non-whitespace character in the current line
var endOfFormatSpan = ts.getEndLinePosition(line, sourceFile);
while (ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) {
endOfFormatSpan--;
}
// if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to
// touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the
// previous character before the end of format span is line break character as well.
if (ts.isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
endOfFormatSpan--;
}
var span = {
// get start position for the previous line
pos: ts.getStartPositionOfLine(line - 1, sourceFile),
// end value is exclusive so add 1 to the result
end: endOfFormatSpan + 1
};
return formatSpan(span, sourceFile, options, rulesProvider, 2 /* FormatOnEnter */);
}n/a
function formatOnSemicolon(position, sourceFile, rulesProvider, options) {
return formatOutermostParent(position, 24 /* SemicolonToken */, sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */);
}n/a
function formatSelection(start, end, sourceFile, rulesProvider, options) {
// format from the beginning of the line
var span = {
pos: ts.getLineStartPositionForPosition(start, sourceFile),
end: end
};
return formatSpan(span, sourceFile, options, rulesProvider, 1 /* FormatSelection */);
}n/a
function getFormattingScanner(sourceFile, startPos, endPos) {
ts.Debug.assert(scanner === undefined, "Scanner should be undefined");
scanner = sourceFile.languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner;
scanner.setText(sourceFile.text);
scanner.setTextPos(startPos);
var wasNewLine = true;
var leadingTrivia;
var trailingTrivia;
var savedPos;
var lastScanAction;
var lastTokenInfo;
return {
advance: advance,
readTokenInfo: readTokenInfo,
isOnToken: isOnToken,
getCurrentLeadingTrivia: function () { return leadingTrivia; },
lastTrailingTriviaWasNewLine: function () { return wasNewLine; },
skipToEndOf: skipToEndOf,
close: function () {
ts.Debug.assert(scanner !== undefined);
lastTokenInfo = undefined;
scanner.setText(undefined);
scanner = undefined;
}
};
function advance() {
ts.Debug.assert(scanner !== undefined, "Scanner should be present");
lastTokenInfo = undefined;
var isStarted = scanner.getStartPos() !== startPos;
if (isStarted) {
if (trailingTrivia) {
ts.Debug.assert(trailingTrivia.length !== 0);
wasNewLine = ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */;
}
else {
wasNewLine = false;
}
}
leadingTrivia = undefined;
trailingTrivia = undefined;
if (!isStarted) {
scanner.scan();
}
var pos = scanner.getStartPos();
// Read leading trivia and token
while (pos < endPos) {
var t = scanner.getToken();
if (!ts.isTrivia(t)) {
break;
}
// consume leading trivia
scanner.scan();
var item = {
pos: pos,
end: scanner.getStartPos(),
kind: t
};
pos = scanner.getStartPos();
if (!leadingTrivia) {
leadingTrivia = [];
}
leadingTrivia.push(item);
}
savedPos = scanner.getStartPos();
}
function shouldRescanGreaterThanToken(node) {
if (node) {
switch (node.kind) {
case 30 /* GreaterThanEqualsToken */:
case 65 /* GreaterThanGreaterThanEqualsToken */:
case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
case 46 /* GreaterThanGreaterThanGreaterThanToken */:
case 45 /* GreaterThanGreaterThanToken */:
return true;
}
}
return false;
}
function shouldRescanJsxIdentifier(node) {
if (node.parent) {
switch (node.parent.kind) {
case 252 /* JsxAttribute */:
case 250 /* JsxOpeningElement */:
case 251 /* JsxClosingElement */:
case 249 /* JsxSelfClosingElement */:
return node.kind === 70 /* Identifier */;
}
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 10 /* JsxText */;
}
function shouldRescanSlashToken(container) {
return container.kind === 11 /* RegularExpressionLiteral */;
}
function shouldRescanTemplateToken(container) {
return container.kind === 14 /* TemplateMiddle */ ||
container.kind === 15 /* TemplateTail */;
}
function startsWithSlashToken(t) {
return t === 40 /* SlashToken */ || t === 62 /* SlashEqualsToken */;
}
function readTokenInfo(n) {
ts.Debug.assert(scanner !== undefined);
if (!isOnToken()) {
// scanner is not on the token (either advance was not called yet or scanner is already past the end position)
return {
leadingTrivia: leadingTrivia,
trailingTrivia: undefined,
token: undefined
};
}
// norm ...n/a
function getIndentationString(indentation, options) {
// reset interned strings if FormatCodeOptions were changed
var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options
.indentSize);
if (resetInternedStrings) {
internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize };
internedTabsIndentation = internedSpacesIndentation = undefined;
}
if (!options.convertTabsToSpaces) {
var tabs = Math.floor(indentation / options.tabSize);
var spaces = indentation - tabs * options.tabSize;
var tabString = void 0;
if (!internedTabsIndentation) {
internedTabsIndentation = [];
}
if (internedTabsIndentation[tabs] === undefined) {
internedTabsIndentation[tabs] = tabString = repeat("\t", tabs);
}
else {
tabString = internedTabsIndentation[tabs];
}
return spaces ? tabString + repeat(" ", spaces) : tabString;
}
else {
var spacesString = void 0;
var quotient = Math.floor(indentation / options.indentSize);
var remainder = indentation % options.indentSize;
if (!internedSpacesIndentation) {
internedSpacesIndentation = [];
}
if (internedSpacesIndentation[quotient] === undefined) {
spacesString = repeat(" ", options.indentSize * quotient);
internedSpacesIndentation[quotient] = spacesString;
}
else {
spacesString = internedSpacesIndentation[quotient];
}
return remainder ? spacesString + repeat(" ", remainder) : spacesString;
}
function repeat(value, count) {
var s = "";
for (var i = 0; i < count; i++) {
s += value;
}
return s;
}
}n/a
function FormattingContext(sourceFile, formattingRequestKind) {
this.sourceFile = sourceFile;
this.formattingRequestKind = formattingRequestKind;
}n/a
BlockIsOnOneLine = function (node) {
var openBrace = ts.findChildOfKind(node, 16 /* OpenBraceToken */, this.sourceFile);
var closeBrace = ts.findChildOfKind(node, 17 /* CloseBraceToken */, this.sourceFile);
if (openBrace && closeBrace) {
var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line;
var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line;
return startLine === endLine;
}
return false;
}n/a
ContextNodeAllOnSameLine = function () {
if (this.contextNodeAllOnSameLine === undefined) {
this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode);
}
return this.contextNodeAllOnSameLine;
}n/a
ContextNodeBlockIsOnOneLine = function () {
if (this.contextNodeBlockIsOnOneLine === undefined) {
this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode);
}
return this.contextNodeBlockIsOnOneLine;
}n/a
NextNodeAllOnSameLine = function () {
if (this.nextNodeAllOnSameLine === undefined) {
this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent);
}
return this.nextNodeAllOnSameLine;
}n/a
NextNodeBlockIsOnOneLine = function () {
if (this.nextNodeBlockIsOnOneLine === undefined) {
this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent);
}
return this.nextNodeBlockIsOnOneLine;
}n/a
NodeIsOnOneLine = function (node) {
var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line;
var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
return startLine === endLine;
}n/a
TokensAreOnSameLine = function () {
if (this.tokensAreOnSameLine === undefined) {
var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line;
var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line;
this.tokensAreOnSameLine = (startLine === endLine);
}
return this.tokensAreOnSameLine;
}n/a
updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) {
ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null");
ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null");
ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null");
ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null");
ts.Debug.assert(commonParent !== undefined, "commonParent is null");
this.currentTokenSpan = currentRange;
this.currentTokenParent = currentTokenParent;
this.nextTokenSpan = nextRange;
this.nextTokenParent = nextTokenParent;
this.contextNode = commonParent;
// drop cached results
this.contextNodeAllOnSameLine = undefined;
this.nextNodeAllOnSameLine = undefined;
this.tokensAreOnSameLine = undefined;
this.contextNodeBlockIsOnOneLine = undefined;
this.nextNodeBlockIsOnOneLine = undefined;
}n/a
function Rule(Descriptor, Operation, Flag) {
if (Flag === void 0) { Flag = 0 /* None */; }
this.Descriptor = Descriptor;
this.Operation = Operation;
this.Flag = Flag;
}n/a
toString = function () {
return "[desc=" + this.Descriptor + "," +
"operation=" + this.Operation + "," +
"flag=" + this.Flag + "]";
}n/a
function RuleDescriptor(LeftTokenRange, RightTokenRange) {
this.LeftTokenRange = LeftTokenRange;
this.RightTokenRange = RightTokenRange;
}n/a
create1 = function (left, right) {
return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), formatting.Shared.TokenRange.FromToken(right));
}n/a
create2 = function (left, right) {
return RuleDescriptor.create4(left, formatting.Shared.TokenRange.FromToken(right));
}n/a
create3 = function (left, right) {
return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), right);
}n/a
create4 = function (left, right) {
return new RuleDescriptor(left, right);
}n/a
toString = function () {
return "[leftRange=" + this.LeftTokenRange + "," +
"rightRange=" + this.RightTokenRange + "]";
}n/a
function RuleOperation(Context, Action) {
this.Context = Context;
this.Action = Action;
}n/a
create1 = function (action) {
return RuleOperation.create2(formatting.RuleOperationContext.Any, action);
}n/a
create2 = function (context, action) {
return new RuleOperation(context, action);
}n/a
toString = function () {
return "[context=" + this.Context + "," +
"action=" + this.Action + "]";
}n/a
function RuleOperationContext() {
var funcs = [];
for (var _i = 0; _i < arguments.length; _i++) {
funcs[_i] = arguments[_i];
}
this.customContextChecks = funcs;
}n/a
InContext = function (context) {
if (this.IsAny()) {
return true;
}
for (var _i = 0, _a = this.customContextChecks; _i < _a.length; _i++) {
var check = _a[_i];
if (!check(context)) {
return false;
}
}
return true;
}n/a
IsAny = function () {
return this === RuleOperationContext.Any;
}n/a
function Rules() {
///
/// Common Rules
///
// Leave comments alone
this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting
.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1 /* Ignore */));
this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2 /* SingleLineCommentTrivia */, formatting
.Shared.TokenRange.Any), formatting.RuleOperation.create1(1 /* Ignore */));
// Space after keyword but not before ; or : or ?
this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /*
SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /*
Delete */));
this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* ColonToken
*/), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext
), 8 /* Delete */));
this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /*
QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules
.IsNotBinaryOpContext), 8 /* Delete */));
this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* ColonToken */, formatting.Shared.TokenRange
.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext
), 2 /* Space */));
this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken
*/, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext
, Rules.IsConditionalOperatorContext), 2 /* Space */));
this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken */, formatting.Shared
.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /*
Delete */));
this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* SemicolonToken */, formatting.Shared.
TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /*
Space */));
// Space after }.
this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared
.TokenRange.FromRange(0 /* FirstToken */, 141 /* LastToken */, [19 /* CloseParenToken */])), formatting.RuleOperation.create2(new
formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */));
// Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace
rule not applied
this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 81 /* ElseKeyword
*/), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 105 /*
WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /*
Space */));
this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared
.TokenRange.FromTokens([21 /* CloseBracketToken */, 25 /* CommaToken */, 24 /* SemicolonToken */])), formatting.RuleOperation.create2
(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
// No space for dot
this.NoSpaceBeforeDot = ne ...n/a
IsAfterCodeBlockContext = function (context) {
switch (context.currentTokenParent.kind) {
case 228 /* ClassDeclaration */:
case 232 /* ModuleDeclaration */:
case 231 /* EnumDeclaration */:
case 258 /* CatchClause */:
case 233 /* ModuleBlock */:
case 220 /* SwitchStatement */:
return true;
case 206 /* Block */: {
var blockParent = context.currentTokenParent.parent;
if (blockParent.kind !== 186 /* ArrowFunction */ &&
blockParent.kind !== 185 /* FunctionExpression */) {
return true;
}
}
}
return false;
}n/a
IsArrowFunctionContext = function (context) {
return context.contextNode.kind === 186 /* ArrowFunction */;
}n/a
IsBeforeBlockContext = function (context) {
return Rules.NodeIsBlockContext(context.nextTokenParent);
}n/a
IsBeforeMultilineBlockContext = function (context) {
return Rules.IsBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine());
}n/a
IsBinaryOpContext = function (context) {
switch (context.contextNode.kind) {
case 193 /* BinaryExpression */:
case 194 /* ConditionalExpression */:
case 201 /* AsExpression */:
case 245 /* ExportSpecifier */:
case 241 /* ImportSpecifier */:
case 157 /* TypePredicate */:
case 165 /* UnionType */:
case 166 /* IntersectionType */:
return true;
// equals in binding elements: function foo([[x, y] = [1, 2]])
case 175 /* BindingElement */:
// equals in type X = ...
case 230 /* TypeAliasDeclaration */:
// equal in import a = module('a');
case 236 /* ImportEqualsDeclaration */:
// equal in let a = 0;
case 225 /* VariableDeclaration */:
// equal in p = 0;
case 145 /* Parameter */:
case 262 /* EnumMember */:
case 148 /* PropertyDeclaration */:
case 147 /* PropertySignature */:
return context.currentTokenSpan.kind === 57 /* EqualsToken */ || context.nextTokenSpan.kind === 57 /* EqualsToken */;
// "in" keyword in for (let x in []) { }
case 214 /* ForInStatement */:
// "in" keyword in [P in keyof T]: T[P]
case 144 /* TypeParameter */:
return context.currentTokenSpan.kind === 91 /* InKeyword */ || context.nextTokenSpan.kind === 91 /* InKeyword */;
// Technically, "of" is not a binary operator, but format it the same way as "in"
case 215 /* ForOfStatement */:
return context.currentTokenSpan.kind === 141 /* OfKeyword */ || context.nextTokenSpan.kind === 141 /* OfKeyword */;
}
return false;
}n/a
IsBlockContext = function (context) {
return Rules.NodeIsBlockContext(context.contextNode);
}n/a
IsBraceWrappedContext = function (context) {
return context.contextNode.kind === 173 /* ObjectBindingPattern */ || Rules.IsSingleLineBlockContext(context);
}n/a
IsConditionalOperatorContext = function (context) {
return context.contextNode.kind === 194 /* ConditionalExpression */;
}n/a
IsControlDeclContext = function (context) {
switch (context.contextNode.kind) {
case 210 /* IfStatement */:
case 220 /* SwitchStatement */:
case 213 /* ForStatement */:
case 214 /* ForInStatement */:
case 215 /* ForOfStatement */:
case 212 /* WhileStatement */:
case 223 /* TryStatement */:
case 211 /* DoStatement */:
case 219 /* WithStatement */:
// TODO
// case SyntaxKind.ElseClause:
case 258 /* CatchClause */:
return true;
default:
return false;
}
}n/a
IsEndOfDecoratorContextOnSameLine = function (context) {
return context.TokensAreOnSameLine() &&
context.contextNode.decorators &&
Rules.NodeIsInDecoratorContext(context.currentTokenParent) &&
!Rules.NodeIsInDecoratorContext(context.nextTokenParent);
}n/a
IsForContext = function (context) {
return context.contextNode.kind === 213 /* ForStatement */;
}n/a
IsFunctionCallContext = function (context) {
return context.contextNode.kind === 180 /* CallExpression */;
}n/a
IsFunctionCallOrNewContext = function (context) {
return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context);
}n/a
IsFunctionDeclContext = function (context) {
switch (context.contextNode.kind) {
case 227 /* FunctionDeclaration */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
// case SyntaxKind.MemberFunctionDeclaration:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
// case SyntaxKind.MethodSignature:
case 154 /* CallSignature */:
case 185 /* FunctionExpression */:
case 151 /* Constructor */:
case 186 /* ArrowFunction */:
// case SyntaxKind.ConstructorDeclaration:
// case SyntaxKind.SimpleArrowFunctionExpression:
// case SyntaxKind.ParenthesizedArrowFunctionExpression:
case 229 /* InterfaceDeclaration */:
return true;
}
return false;
}n/a
IsFunctionDeclarationOrFunctionExpressionContext = function (context) {
return context.contextNode.kind === 227 /* FunctionDeclaration */ || context.contextNode.kind === 185 /* FunctionExpression */;
}n/a
IsJsxAttributeContext = function (context) {
return context.contextNode.kind === 252 /* JsxAttribute */;
}n/a
IsJsxExpressionContext = function (context) {
return context.contextNode.kind === 254 /* JsxExpression */;
}n/a
IsJsxSelfClosingElementContext = function (context) {
return context.contextNode.kind === 249 /* JsxSelfClosingElement */;
}n/a
IsModuleDeclContext = function (context) {
return context.contextNode.kind === 232 /* ModuleDeclaration */;
}n/a
IsMultilineBlockContext = function (context) {
return Rules.IsBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
}n/a
IsNewContext = function (context) {
return context.contextNode.kind === 181 /* NewExpression */;
}n/a
IsNextTokenNotCloseBracket = function (context) {
return context.nextTokenSpan.kind !== 21 /* CloseBracketToken */;
}n/a
IsNextTokenParentJsxAttribute = function (context) {
return context.nextTokenParent.kind === 252 /* JsxAttribute */;
}n/a
IsNonJsxElementContext = function (context) {
return context.contextNode.kind !== 248 /* JsxElement */;
}n/a
IsNonJsxSameLineTokenContext = function (context) {
return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */;
}n/a
IsNonNullAssertionContext = function (context) {
return context.contextNode.kind === 202 /* NonNullExpression */;
}n/a
IsNotBeforeBlockInFunctionDeclarationContext = function (context) {
return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context);
}n/a
IsNotBinaryOpContext = function (context) {
return !Rules.IsBinaryOpContext(context);
}n/a
IsNotForContext = function (context) {
return !Rules.IsForContext(context);
}n/a
IsNotFormatOnEnter = function (context) {
return context.formattingRequestKind !== 2 /* FormatOnEnter */;
}n/a
IsObjectContext = function (context) {
return context.contextNode.kind === 177 /* ObjectLiteralExpression */;
}n/a
IsObjectTypeContext = function (context) {
return context.contextNode.kind === 162 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration
;
}n/a
IsPreviousTokenNotComma = function (context) {
return context.currentTokenSpan.kind !== 25 /* CommaToken */;
}n/a
IsSameLineTokenOrBeforeMultilineBlockContext = function (context) {
//// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction.
////
//// Ex:
//// if (1) { ....
//// * ) and { are on the same line so apply the rule. Here we don't care whether it's same or multi block context
////
//// Ex:
//// if (1)
//// { ... }
//// * ) and { are on different lines. We only need to format if the block is multiline context. So in this case we don
't format.
////
//// Ex:
//// if (1)
//// { ...
//// }
//// * ) and { are on different lines. We only need to format if the block is multiline context. So in this case we format
.
return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context);
}n/a
IsSingleLineBlockContext = function (context) {
return Rules.IsBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
}n/a
IsStartOfVariableDeclarationList = function (context) {
return context.currentTokenParent.kind === 226 /* VariableDeclarationList */ &&
context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
}n/a
IsTypeArgumentOrParameterOrAssertion = function (token, parent) {
if (token.kind !== 26 /* LessThanToken */ && token.kind !== 28 /* GreaterThanToken */) {
return false;
}
switch (parent.kind) {
case 158 /* TypeReference */:
case 183 /* TypeAssertionExpression */:
case 230 /* TypeAliasDeclaration */:
case 228 /* ClassDeclaration */:
case 198 /* ClassExpression */:
case 229 /* InterfaceDeclaration */:
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
case 186 /* ArrowFunction */:
case 150 /* MethodDeclaration */:
case 149 /* MethodSignature */:
case 154 /* CallSignature */:
case 155 /* ConstructSignature */:
case 180 /* CallExpression */:
case 181 /* NewExpression */:
case 200 /* ExpressionWithTypeArguments */:
return true;
default:
return false;
}
}n/a
IsTypeArgumentOrParameterOrAssertionContext = function (context) {
return Rules.IsTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) ||
Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent);
}n/a
IsTypeAssertionContext = function (context) {
return context.contextNode.kind === 183 /* TypeAssertionExpression */;
}n/a
IsTypeScriptDeclWithBlockContext = function (context) {
return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode);
}n/a
IsVoidOpContext = function (context) {
return context.currentTokenSpan.kind === 104 /* VoidKeyword */ && context.currentTokenParent.kind === 189 /* VoidExpression */;
}n/a
IsYieldOrYieldStarWithOperand = function (context) {
return context.contextNode.kind === 196 /* YieldExpression */ && context.contextNode.expression !== undefined;
}n/a
NodeIsBlockContext = function (node) {
if (Rules.NodeIsTypeScriptDeclWithBlockContext(node)) {
// This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a
class, module, enum, object type literal, etc).
return true;
}
switch (node.kind) {
case 206 /* Block */:
case 234 /* CaseBlock */:
case 177 /* ObjectLiteralExpression */:
case 233 /* ModuleBlock */:
return true;
}
return false;
}n/a
NodeIsInDecoratorContext = function (node) {
while (ts.isPartOfExpression(node)) {
node = node.parent;
}
return node.kind === 146 /* Decorator */;
}n/a
NodeIsTypeScriptDeclWithBlockContext = function (node) {
switch (node.kind) {
case 228 /* ClassDeclaration */:
case 198 /* ClassExpression */:
case 229 /* InterfaceDeclaration */:
case 231 /* EnumDeclaration */:
case 162 /* TypeLiteral */:
case 232 /* ModuleDeclaration */:
case 243 /* ExportDeclaration */:
case 244 /* NamedExports */:
case 237 /* ImportDeclaration */:
case 240 /* NamedImports */:
return true;
}
return false;
}n/a
getRuleName = function (rule) {
var o = this;
for (var name in o) {
if (o[name] === rule) {
return name;
}
}
throw new Error("Unknown rule");
}n/a
function RulesBucket() {
this.rules = [];
}n/a
AddRule = function (rule, specificTokens, constructionState, rulesBucketIndex) {
var position;
if (rule.Operation.Action === 1 /* Ignore */) {
position = specificTokens ?
RulesPosition.IgnoreRulesSpecific :
RulesPosition.IgnoreRulesAny;
}
else if (!rule.Operation.Context.IsAny()) {
position = specificTokens ?
RulesPosition.ContextRulesSpecific :
RulesPosition.ContextRulesAny;
}
else {
position = specificTokens ?
RulesPosition.NoContextRulesSpecific :
RulesPosition.NoContextRulesAny;
}
var state = constructionState[rulesBucketIndex];
if (state === undefined) {
state = constructionState[rulesBucketIndex] = new RulesBucketConstructionState();
}
var index = state.GetInsertionIndex(position);
this.rules.splice(index, 0, rule);
state.IncreaseInsertionIndex(position);
}n/a
Rules = function () {
return this.rules;
}n/a
function RulesBucketConstructionState() {
//// The Rules list contains all the inserted rules into a rulebucket in the following order:
//// 1- Ignore rules with specific token combination
//// 2- Ignore rules with any token combination
//// 3- Context rules with specific token combination
//// 4- Context rules with any token combination
//// 5- Non-context rules with specific token combination
//// 6- Non-context rules with any token combination
////
//// The member rulesInsertionIndexBitmap is used to describe the number of rules
//// in each sub-bucket (above) hence can be used to know the index of where to insert
//// the next rule. It's a bitmap which contains 6 different sections each is given 5 bits.
////
//// Example:
//// In order to insert a rule to the end of sub-bucket (3), we get the index by adding
//// the values in the bitmap segments 3rd, 2nd, and 1st.
this.rulesInsertionIndexBitmap = 0;
}n/a
GetInsertionIndex = function (maskPosition) {
var index = 0;
var pos = 0;
var indexBitmap = this.rulesInsertionIndexBitmap;
while (pos <= maskPosition) {
index += (indexBitmap & Mask);
indexBitmap >>= MaskBitSize;
pos += MaskBitSize;
}
return index;
}n/a
IncreaseInsertionIndex = function (maskPosition) {
var value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask;
value++;
ts.Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules.");
var temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition);
temp |= value << maskPosition;
this.rulesInsertionIndexBitmap = temp;
}n/a
function RulesMap() {
this.map = [];
this.mapRowLength = 0;
}n/a
create = function (rules) {
var result = new RulesMap();
result.Initialize(rules);
return result;
}n/a
FillRule = function (rule, rulesBucketConstructionStateList) {
var _this = this;
var specificRule = rule.Descriptor.LeftTokenRange !== formatting.Shared.TokenRange.Any &&
rule.Descriptor.RightTokenRange !== formatting.Shared.TokenRange.Any;
rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) {
rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) {
var rulesBucketIndex = _this.GetRuleBucketIndex(left, right);
var rulesBucket = _this.map[rulesBucketIndex];
if (rulesBucket === undefined) {
rulesBucket = _this.map[rulesBucketIndex] = new RulesBucket();
}
rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex);
});
});
}n/a
FillRules = function (rules, rulesBucketConstructionStateList) {
var _this = this;
rules.forEach(function (rule) {
_this.FillRule(rule, rulesBucketConstructionStateList);
});
}n/a
GetRule = function (context) {
var bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind);
var bucket = this.map[bucketIndex];
if (bucket) {
for (var _i = 0, _a = bucket.Rules(); _i < _a.length; _i++) {
var rule = _a[_i];
if (rule.Operation.Context.InContext(context)) {
return rule;
}
}
}
return undefined;
}n/a
GetRuleBucketIndex = function (row, column) {
ts.Debug.assert(row <= 141 /* LastKeyword */ && column <= 141 /* LastKeyword */, "Must compute formatting context from tokens
");
var rulesBucketIndex = (row * this.mapRowLength) + column;
return rulesBucketIndex;
}n/a
Initialize = function (rules) {
this.mapRowLength = 141 /* LastToken */ + 1;
this.map = new Array(this.mapRowLength * this.mapRowLength); // new Array<RulesBucket>(this.mapRowLength * this.mapRowLength
);
// This array is used only during construction of the rulesbucket in the map
var rulesBucketConstructionStateList = new Array(this.map.length); // new Array<RulesBucketConstructionState>(this.map.length
);
this.FillRules(rules, rulesBucketConstructionStateList);
return this.map;
}n/a
function RulesProvider() {
this.globalRules = new formatting.Rules();
}n/a
createActiveRules = function (options) {
var rules = this.globalRules.HighPriorityCommonRules.slice(0);
if (options.insertSpaceAfterConstructor) {
rules.push(this.globalRules.SpaceAfterConstructor);
}
else {
rules.push(this.globalRules.NoSpaceAfterConstructor);
}
if (options.insertSpaceAfterCommaDelimiter) {
rules.push(this.globalRules.SpaceAfterComma);
}
else {
rules.push(this.globalRules.NoSpaceAfterComma);
}
if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) {
rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword);
}
else {
rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword);
}
if (options.insertSpaceAfterKeywordsInControlFlowStatements) {
rules.push(this.globalRules.SpaceAfterKeywordInControl);
}
else {
rules.push(this.globalRules.NoSpaceAfterKeywordInControl);
}
if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) {
rules.push(this.globalRules.SpaceAfterOpenParen);
rules.push(this.globalRules.SpaceBeforeCloseParen);
rules.push(this.globalRules.NoSpaceBetweenParens);
}
else {
rules.push(this.globalRules.NoSpaceAfterOpenParen);
rules.push(this.globalRules.NoSpaceBeforeCloseParen);
rules.push(this.globalRules.NoSpaceBetweenParens);
}
if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) {
rules.push(this.globalRules.SpaceAfterOpenBracket);
rules.push(this.globalRules.SpaceBeforeCloseBracket);
rules.push(this.globalRules.NoSpaceBetweenBrackets);
}
else {
rules.push(this.globalRules.NoSpaceAfterOpenBracket);
rules.push(this.globalRules.NoSpaceBeforeCloseBracket);
rules.push(this.globalRules.NoSpaceBetweenBrackets);
}
// The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true
// so if the option is undefined, we should treat it as true as well
if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) {
rules.push(this.globalRules.SpaceAfterOpenBrace);
rules.push(this.globalRules.SpaceBeforeCloseBrace);
rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets);
}
else {
rules.push(this.globalRules.NoSpaceAfterOpenBrace);
rules.push(this.globalRules.NoSpaceBeforeCloseBrace);
rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets);
}
if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) {
rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail);
}
else {
rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail);
}
if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) {
rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression);
rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression);
}
else {
rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression);
rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression);
}
if (options.insertSpaceAfterSemicolonInForStatements) {
rules.push(this.globalRules.SpaceAfterSemicolonInFor);
}
else {
rules.push(this.globalRules.NoSpaceAfterSemicolonInFor);
}
if (options.insertSpaceBeforeAndAfterBinaryOperators) {
rules.push(this.globalRules.SpaceBeforeBinaryOperator);
rules.push(this.globalRules.SpaceAfterBinaryOperator);
}
else {
rules.push(this.globalRules.NoSpaceBeforeBinaryOperator);
rules.push(this.globalRules.NoSpaceAfterBinaryOperator);
}
if (options.insertSpaceBeforeFunctionParenthesis) {
rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl);
}
else {
rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl);
}
if (options.placeOpenBrace ...n/a
ensureUpToDate = function (options) {
if (!this.options || !ts.compareDataObjects(this.options, options)) {
var activeRules = this.createActiveRules(options);
var rulesMap = formatting.RulesMap.create(activeRules);
this.activeRules = activeRules;
this.rulesMap = rulesMap;
this.options = ts.clone(options);
}
}n/a
getRuleByName = function (name) {
return this.globalRules[name];
}n/a
getRuleName = function (rule) {
return this.globalRules.getRuleName(rule);
}n/a
getRulesMap = function () {
return this.rulesMap;
}n/a
function TokenAllAccess() {
}n/a
function TokenRange(tokenAccess) {
this.tokenAccess = tokenAccess;
}n/a
function TokenRangeAccess(from, to, except) {
this.tokens = [];
for (var token = from; token <= to; token++) {
if (ts.indexOf(except, token) < 0) {
this.tokens.push(token);
}
}
}n/a
function TokenSingleValueAccess(token) {
this.token = token;
}n/a
function TokenValuesAccess(tks) {
this.tokens = tks && tks.length ? tks : [];
}n/a
Contains = function () {
return true;
}n/a
GetTokens = function () {
var result = [];
for (var token = 0 /* FirstToken */; token <= 141 /* LastToken */; token++) {
result.push(token);
}
return result;
}n/a
toString = function () {
return "[allTokens]";
}n/a
Contains = function (token) {
return this.tokenAccess.Contains(token);
}n/a
GetTokens = function () {
return this.tokenAccess.GetTokens();
}n/a
toString = function () {
return this.tokenAccess.toString();
}n/a
Contains = function (token) {
return this.tokens.indexOf(token) >= 0;
}n/a
GetTokens = function () {
return this.tokens;
}n/a
Contains = function (tokenValue) {
return tokenValue === this.token;
}n/a
GetTokens = function () {
return [this.token];
}n/a
Contains = function (token) {
return this.tokens.indexOf(token) >= 0;
}n/a
GetTokens = function () {
return this.tokens;
}n/a
function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) {
if (parent.kind === 210 /* IfStatement */ && parent.elseStatement === child) {
var elseKeyword = ts.findChildOfKind(parent, 81 /* ElseKeyword */, sourceFile);
ts.Debug.assert(elseKeyword !== undefined);
var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line;
return elseKeywordStartLine === childStartLine;
}
return false;
}n/a
function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) {
var character = 0;
var column = 0;
for (var pos = startPos; pos < endPos; pos++) {
var ch = sourceFile.text.charCodeAt(pos);
if (!ts.isWhiteSpaceSingleLine(ch)) {
break;
}
if (ch === 9 /* tab */) {
column += options.tabSize + (column % options.tabSize);
}
else {
column++;
}
character++;
}
return { column: column, character: character };
}n/a
function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) {
return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column;
}n/a
function getBaseIndentation(options) {
return options.baseIndentSize || 0;
}n/a
function getIndentation(position, sourceFile, options) {
if (position > sourceFile.text.length) {
return getBaseIndentation(options); // past EOF
}
// no indentation when the indent style is set to none,
// so we can return fast
if (options.indentStyle === ts.IndentStyle.None) {
return 0;
}
var precedingToken = ts.findPrecedingToken(position, sourceFile);
if (!precedingToken) {
return getBaseIndentation(options);
}
// no indentation in string \regex\template literals
var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind);
if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) {
return 0;
}
var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
// indentation is first non-whitespace character in a previous line
// for block indentation, we should look for a line which contains something that's not
// whitespace.
if (options.indentStyle === ts.IndentStyle.Block) {
// move backwards until we find a line with a non-whitespace character,
// then find the first non-whitespace character for that line.
var current_1 = position;
while (current_1 > 0) {
var char = sourceFile.text.charCodeAt(current_1);
if (!ts.isWhiteSpace(char)) {
break;
}
current_1--;
}
var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile);
return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options);
}
if (precedingToken.kind === 25 /* CommaToken */ && precedingToken.parent.kind !== 193 /* BinaryExpression */) {
// previous token is comma that separates items in list - find the previous item and try to derive indentation from it
var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options);
if (actualIndentation !== -1 /* Unknown */) {
return actualIndentation;
}
}
// try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken'
// if such node is found - compute initial indentation for 'position' inside this node
var previous;
var current = precedingToken;
var currentStart;
var indentationDelta;
while (current) {
if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) {
currentStart = getStartLineAndCharacterForNode(current, sourceFile);
if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) {
indentationDelta = 0;
}
else {
indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0;
}
break;
}
// check if current node is a list item - if yes, take indentation from it
var actualIndentation = getActualIndentationForListItem(current, sourceFile, options);
if (actualIndentation !== -1 /* Unknown */) {
return actualIndentation;
}
actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options);
if (actualIndentation !== -1 /* Unknown */) {
return actualIndentation + options.indentSize;
}
previous = current;
current = current.parent;
}
if (!current) {
// no parent was found - return the base indentation of the SourceFile
return getBaseIndentation(options);
}
return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile
, options);
}n/a
function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) {
var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options);
}n/a
function nodeWillIndentChild(parent, child, indentByDefault) {
var childKind = child ? child.kind : 0 /* Unknown */;
switch (parent.kind) {
case 211 /* DoStatement */:
case 212 /* WhileStatement */:
case 214 /* ForInStatement */:
case 215 /* ForOfStatement */:
case 213 /* ForStatement */:
case 210 /* IfStatement */:
case 227 /* FunctionDeclaration */:
case 185 /* FunctionExpression */:
case 150 /* MethodDeclaration */:
case 186 /* ArrowFunction */:
case 151 /* Constructor */:
case 152 /* GetAccessor */:
case 153 /* SetAccessor */:
return childKind !== 206 /* Block */;
case 243 /* ExportDeclaration */:
return childKind !== 244 /* NamedExports */;
case 237 /* ImportDeclaration */:
return childKind !== 238 /* ImportClause */ ||
(child.namedBindings && child.namedBindings.kind !== 240 /* NamedImports */);
case 248 /* JsxElement */:
return childKind !== 251 /* JsxClosingElement */;
}
// No explicit rule for given nodes so the result will follow the default value argument
return indentByDefault;
}n/a
function shouldIndentChildNode(parent, child) {
return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false);
}n/a
getIdentifierConstructor = function () { return IdentifierObject; }n/a
getNodeConstructor = function () { return NodeObject; }n/a
getSignatureConstructor = function () { return SignatureObject; }n/a
getSourceFileConstructor = function () { return SourceFileObject; }n/a
getSymbolConstructor = function () { return SymbolObject; }n/a
getTokenConstructor = function () { return TokenObject; }n/a
getTypeConstructor = function () { return TypeObject; }n/a
function disable() {
enabled = false;
}n/a
function enable() {
counts = ts.createMap();
marks = ts.createMap();
measures = ts.createMap();
enabled = true;
profilerStart = ts.timestamp();
}n/a
function forEachMeasure(cb) {
measures.forEach(function (measure, key) {
cb(key, measure);
});
}n/a
function getCount(markName) {
return counts && counts.get(markName) || 0;
}n/a
function getDuration(measureName) {
return measures && measures.get(measureName) || 0;
}n/a
function mark(markName) {
if (enabled) {
marks.set(markName, ts.timestamp());
counts.set(markName, (counts.get(markName) || 0) + 1);
profilerEvent(markName);
}
}n/a
function measure(measureName, startMarkName, endMarkName) {
if (enabled) {
var end = endMarkName && marks.get(endMarkName) || ts.timestamp();
var start = startMarkName && marks.get(startMarkName) || profilerStart;
measures.set(measureName, (measures.get(measureName) || 0) + (end - start));
}
}n/a
getStartPos = function () { return startPos; }n/a
function getText() {
return text;
}n/a
getTextPos = function () { return pos; }n/a
getToken = function () { return token; }n/a
getTokenPos = function () { return tokenPos; }n/a
getTokenText = function () { return text.substring(tokenPos, pos); }n/a
getTokenValue = function () { return tokenValue; }n/a
hasExtendedUnicodeEscape = function () { return hasExtendedUnicodeEscape; }n/a
hasPrecedingLineBreak = function () { return precedingLineBreak; }n/a
isIdentifier = function () { return token === 70 /* Identifier */ || token > 106 /* LastReservedWord */; }n/a
isReservedWord = function () { return token >= 71 /* FirstReservedWord */ && token <= 106 /* LastReservedWord */; }n/a
isUnterminated = function () { return tokenIsUnterminated; }n/a
function lookAhead(callback) {
return speculationHelper(callback, /*isLookahead*/ true);
}n/a
function reScanGreaterToken() {
if (token === 28 /* GreaterThanToken */) {
if (text.charCodeAt(pos) === 62 /* greaterThan */) {
if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
if (text.charCodeAt(pos + 2) === 61 /* equals */) {
return pos += 3, token = 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
}
return pos += 2, token = 46 /* GreaterThanGreaterThanGreaterThanToken */;
}
if (text.charCodeAt(pos + 1) === 61 /* equals */) {
return pos += 2, token = 65 /* GreaterThanGreaterThanEqualsToken */;
}
pos++;
return token = 45 /* GreaterThanGreaterThanToken */;
}
if (text.charCodeAt(pos) === 61 /* equals */) {
pos++;
return token = 30 /* GreaterThanEqualsToken */;
}
}
return token;
}n/a
function reScanJsxToken() {
pos = tokenPos = startPos;
return token = scanJsxToken();
}n/a
function reScanSlashToken() {
if (token === 40 /* SlashToken */ || token === 62 /* SlashEqualsToken */) {
var p = tokenPos + 1;
var inEscape = false;
var inCharacterClass = false;
while (true) {
// If we reach the end of a file, or hit a newline, then this is an unterminated
// regex. Report error and return what we have so far.
if (p >= end) {
tokenIsUnterminated = true;
error(ts.Diagnostics.Unterminated_regular_expression_literal);
break;
}
var ch = text.charCodeAt(p);
if (isLineBreak(ch)) {
tokenIsUnterminated = true;
error(ts.Diagnostics.Unterminated_regular_expression_literal);
break;
}
if (inEscape) {
// Parsing an escape character;
// reset the flag and just advance to the next char.
inEscape = false;
}
else if (ch === 47 /* slash */ && !inCharacterClass) {
// A slash within a character class is permissible,
// but in general it signals the end of the regexp literal.
p++;
break;
}
else if (ch === 91 /* openBracket */) {
inCharacterClass = true;
}
else if (ch === 92 /* backslash */) {
inEscape = true;
}
else if (ch === 93 /* closeBracket */) {
inCharacterClass = false;
}
p++;
}
while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
p++;
}
pos = p;
tokenValue = text.substring(tokenPos, pos);
token = 11 /* RegularExpressionLiteral */;
}
return token;
}n/a
function reScanTemplateToken() {
ts.Debug.assert(token === 17 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
pos = tokenPos;
return token = scanTemplateAndSetTokenValue();
}n/a
function scan() {
startPos = pos;
hasExtendedUnicodeEscape = false;
precedingLineBreak = false;
tokenIsUnterminated = false;
while (true) {
tokenPos = pos;
if (pos >= end) {
return token = 1 /* EndOfFileToken */;
}
var ch = text.charCodeAt(pos);
// Special handling for shebang
if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
pos = scanShebangTrivia(text, pos);
if (skipTrivia) {
continue;
}
else {
return token = 6 /* ShebangTrivia */;
}
}
switch (ch) {
case 10 /* lineFeed */:
case 13 /* carriageReturn */:
precedingLineBreak = true;
if (skipTrivia) {
pos++;
continue;
}
else {
if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
// consume both CR and LF
pos += 2;
}
else {
pos++;
}
return token = 4 /* NewLineTrivia */;
}
case 9 /* tab */:
case 11 /* verticalTab */:
case 12 /* formFeed */:
case 32 /* space */:
if (skipTrivia) {
pos++;
continue;
}
else {
while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
pos++;
}
return token = 5 /* WhitespaceTrivia */;
}
case 33 /* exclamation */:
if (text.charCodeAt(pos + 1) === 61 /* equals */) {
if (text.charCodeAt(pos + 2) === 61 /* equals */) {
return pos += 3, token = 34 /* ExclamationEqualsEqualsToken */;
}
return pos += 2, token = 32 /* ExclamationEqualsToken */;
}
pos++;
return token = 50 /* ExclamationToken */;
case 34 /* doubleQuote */:
case 39 /* singleQuote */:
tokenValue = scanString();
return token = 9 /* StringLiteral */;
case 96 /* backtick */:
return token = scanTemplateAndSetTokenValue();
case 37 /* percent */:
if (text.charCodeAt(pos + 1) === 61 /* equals */) {
return pos += 2, token = 63 /* PercentEqualsToken */;
}
pos++;
return token = 41 /* PercentToken */;
case 38 /* ampersand */:
if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
return pos += 2, token = 52 /* AmpersandAmpersandToken */;
}
if (text.charCodeAt(pos + 1) === 61 /* equals */) {
return pos += 2, token = 67 /* AmpersandEqualsToken */;
}
pos++;
return token = 47 /* AmpersandToken */;
case 40 /* openParen */:
pos++;
return token = 18 /* OpenParenToken */;
case 41 /* closeParen */:
pos++;
return token = 19 /* CloseParenToken */;
case 42 /* asterisk */:
if (text.charCodeAt(pos + 1) === 61 /* equals */) {
return pos += 2, token = 60 /* AsteriskEqualsToken */;
}
if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
if (text.charCodeAt(pos + 2) === 61 /* equals */) {
return pos += 3, token = 61 /* AsteriskAsteriskEqualsToken */;
}
return pos += 2, token = 39 /* AsteriskAsteriskToken */;
}
pos++;
return token = 38 /* Aster ...n/a
function scanJSDocToken() {
if (pos >= end) {
return token = 1 /* EndOfFileToken */;
}
startPos = pos;
tokenPos = pos;
var ch = text.charCodeAt(pos);
switch (ch) {
case 9 /* tab */:
case 11 /* verticalTab */:
case 12 /* formFeed */:
case 32 /* space */:
while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
pos++;
}
return token = 5 /* WhitespaceTrivia */;
case 64 /* at */:
pos++;
return token = 56 /* AtToken */;
case 10 /* lineFeed */:
case 13 /* carriageReturn */:
pos++;
return token = 4 /* NewLineTrivia */;
case 42 /* asterisk */:
pos++;
return token = 38 /* AsteriskToken */;
case 123 /* openBrace */:
pos++;
return token = 16 /* OpenBraceToken */;
case 125 /* closeBrace */:
pos++;
return token = 17 /* CloseBraceToken */;
case 91 /* openBracket */:
pos++;
return token = 20 /* OpenBracketToken */;
case 93 /* closeBracket */:
pos++;
return token = 21 /* CloseBracketToken */;
case 61 /* equals */:
pos++;
return token = 57 /* EqualsToken */;
case 44 /* comma */:
pos++;
return token = 25 /* CommaToken */;
case 46 /* dot */:
pos++;
return token = 22 /* DotToken */;
}
if (isIdentifierStart(ch, 5 /* Latest */)) {
pos++;
while (isIdentifierPart(text.charCodeAt(pos), 5 /* Latest */) && pos < end) {
pos++;
}
return token = 70 /* Identifier */;
}
else {
return pos += 1, token = 0 /* Unknown */;
}
}n/a
function scanJsxAttributeValue() {
startPos = pos;
switch (text.charCodeAt(pos)) {
case 34 /* doubleQuote */:
case 39 /* singleQuote */:
tokenValue = scanString(/*allowEscapes*/ false);
return token = 9 /* StringLiteral */;
default:
// If this scans anything other than `{`, it's a parse error.
return scan();
}
}n/a
function scanJsxIdentifier() {
if (tokenIsIdentifierOrKeyword(token)) {
var firstCharPosition = pos;
while (pos < end) {
var ch = text.charCodeAt(pos);
if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart
(ch, languageVersion))) {
pos++;
}
else {
break;
}
}
tokenValue += text.substr(firstCharPosition, pos - firstCharPosition);
}
return token;
}n/a
function scanJsxToken() {
startPos = tokenPos = pos;
if (pos >= end) {
return token = 1 /* EndOfFileToken */;
}
var char = text.charCodeAt(pos);
if (char === 60 /* lessThan */) {
if (text.charCodeAt(pos + 1) === 47 /* slash */) {
pos += 2;
return token = 27 /* LessThanSlashToken */;
}
pos++;
return token = 26 /* LessThanToken */;
}
if (char === 123 /* openBrace */) {
pos++;
return token = 16 /* OpenBraceToken */;
}
while (pos < end) {
pos++;
char = text.charCodeAt(pos);
if ((char === 123 /* openBrace */) || (char === 60 /* lessThan */)) {
break;
}
}
return token = 10 /* JsxText */;
}n/a
function scanRange(start, length, callback) {
var saveEnd = end;
var savePos = pos;
var saveStartPos = startPos;
var saveTokenPos = tokenPos;
var saveToken = token;
var savePrecedingLineBreak = precedingLineBreak;
var saveTokenValue = tokenValue;
var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape;
var saveTokenIsUnterminated = tokenIsUnterminated;
setText(text, start, length);
var result = callback();
end = saveEnd;
pos = savePos;
startPos = saveStartPos;
tokenPos = saveTokenPos;
token = saveToken;
precedingLineBreak = savePrecedingLineBreak;
tokenValue = saveTokenValue;
hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape;
tokenIsUnterminated = saveTokenIsUnterminated;
return result;
}n/a
function setLanguageVariant(variant) {
languageVariant = variant;
}n/a
function setOnError(errorCallback) {
onError = errorCallback;
}n/a
function setScriptTarget(scriptTarget) {
languageVersion = scriptTarget;
}n/a
function setText(newText, start, length) {
text = newText || "";
end = length === undefined ? text.length : start + length;
setTextPos(start || 0);
}n/a
function setTextPos(textPos) {
ts.Debug.assert(textPos >= 0);
pos = textPos;
startPos = textPos;
tokenPos = textPos;
token = 0 /* Unknown */;
precedingLineBreak = false;
tokenValue = undefined;
hasExtendedUnicodeEscape = false;
tokenIsUnterminated = false;
}n/a
function tryScan(callback) {
return speculationHelper(callback, /*isLookahead*/ false);
}n/a
clearTimeout = function (timer) {
if (timer && (timer[kOnTimeout] || timer._onTimeout)) {
timer[kOnTimeout] = timer._onTimeout = null;
if (timer instanceof Timeout) {
timer.close(); // for after === 0
} else {
unenroll(timer);
}
}
}n/a
createDirectory = function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
}n/a
createHash = function (data) {
var hash = _crypto.createHash("md5");
hash.update(data);
return hash.digest("hex");
}n/a
function directoryExists(path) {
return fileSystemEntryExists(path, 1 /* Directory */);
}n/a
exit = function (exitCode) {
process.exit(exitCode);
}n/a
function fileExists(path) {
return fileSystemEntryExists(path, 0 /* File */);
}n/a
getCurrentDirectory = function () {
return process.cwd();
}n/a
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory
*/); });
}n/a
getEnvironmentVariable = function (name) {
return process.env[name] || "";
}n/a
getExecutingFilePath = function () {
return __filename;
}n/a
getFileSize = function (path) {
try {
var stat = _fs.statSync(path);
if (stat.isFile()) {
return stat.size;
}
}
catch (e) { }
return 0;
}n/a
getMemoryUsage = function () {
if (global.gc) {
global.gc();
}
return process.memoryUsage().heapUsed;
}n/a
getModifiedTime = function (path) {
try {
return _fs.statSync(path).mtime;
}
catch (e) {
return undefined;
}
}n/a
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries
);
}n/a
function readFile(fileName, _encoding) {
if (!fileExists(fileName)) {
return undefined;
}
var buffer = _fs.readFileSync(fileName);
var len = buffer.length;
if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
// Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
// flip all byte pairs and treat as little endian.
len &= ~1;
for (var i = 0; i < len; i += 2) {
var temp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
}
return buffer.toString("utf16le", 2);
}
if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
// Little endian UTF-16 byte order mark detected
return buffer.toString("utf16le", 2);
}
if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
// UTF-8 byte order mark detected
return buffer.toString("utf8", 3);
}
// Default is UTF-8 with no byte order mark
return buffer.toString("utf8");
}n/a
realpath = function (path) {
return _fs.realpathSync(path);
}n/a
resolvePath = function (path) {
return _path.resolve(path);
}n/a
setTimeout = function (callback, after, arg1, arg2, arg3) {
if (typeof callback !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args;
if (len === 3) {
args = [arg1];
} else if (len === 4) {
args = [arg1, arg2];
} else if (len > 4) {
args = [arg1, arg2, arg3];
for (var i = 5; i < len; i++)
// extend array dynamically, makes .apply run much faster in v6.0.0
args[i - 2] = arguments[i];
}
return createSingleTimeout(callback, after, args);
}n/a
tryEnableSourceMapsForHost = function () {
try {
require("source-map-support").install();
}
catch (e) {
// Could not enable source maps.
}
}n/a
watchDirectory = function (directoryName, callback, recursive) {
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
var options;
if (!directoryExists(directoryName)) {
// do nothing if target folder does not exist
return noOpFileWatcher;
}
if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) {
options = { persistent: true, recursive: !!recursive };
}
else {
options = { persistent: true };
}
return _fs.watch(directoryName, options, function (eventName, relativeFileName) {
// In watchDirectory we only care about adding and removing files (when event name is
// "rename"); changes made within files are handled by corresponding fileWatchers (when
// event name is "change")
if (eventName === "rename") {
// When deleting a file, the passed baseFileName is null
callback(!relativeFileName ? relativeFileName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
}
;
});
}n/a
watchFile = function (fileName, callback, pollingInterval) {
if (useNonPollingWatchers) {
var watchedFile_1 = watchedFileSet.addFile(fileName, callback);
return {
close: function () { return watchedFileSet.removeFile(watchedFile_1); }
};
}
else {
_fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged);
return {
close: function () { return _fs.unwatchFile(fileName, fileChanged); }
};
}
function fileChanged(curr, prev) {
if (+curr.mtime <= +prev.mtime) {
return;
}
callback(fileName);
}
}n/a
write = function (s) {
process.stdout.write(s);
}n/a
writeFile = function (path, data, writeBom) {
var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path));
if (directoryPath && !sys.directoryExists(directoryPath)) {
recursiveCreateDirectory(directoryPath, sys);
}
originalWriteFile_1.call(sys, path, data, writeBom);
}n/a