diff --git a/lib/tsc.js b/lib/tsc.js
index 719143749d0..aef54c957e6 100644
--- a/lib/tsc.js
+++ b/lib/tsc.js
@@ -145,7 +145,6 @@ var ts;
contains: contains,
remove: remove,
forEachValue: forEachValueInMap,
- getKeys: getKeys,
clear: clear
};
function forEachValueInMap(f) {
@@ -153,13 +152,6 @@ var ts;
f(key, files[key]);
}
}
- function getKeys() {
- var keys = [];
- for (var key in files) {
- keys.push(key);
- }
- return keys;
- }
function get(path) {
return files[toKey(path)];
}
@@ -536,22 +528,16 @@ var ts;
: undefined;
}
ts.lastOrUndefined = lastOrUndefined;
- function binarySearch(array, value, comparer) {
- if (!array || array.length === 0) {
- return -1;
- }
+ function binarySearch(array, value) {
var low = 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) {
+ if (midValue === value) {
return middle;
}
- else if (comparer(midValue, value) > 0) {
+ else if (midValue > value) {
high = middle - 1;
}
else {
@@ -1021,45 +1007,10 @@ var ts;
return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1;
}
ts.isUrl = isUrl;
- function isExternalModuleNameRelative(moduleName) {
- return /^\.\.?($|[\\/])/.test(moduleName);
- }
- ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
- function getEmitScriptTarget(compilerOptions) {
- return compilerOptions.target || 0;
- }
- ts.getEmitScriptTarget = getEmitScriptTarget;
- function getEmitModuleKind(compilerOptions) {
- return typeof compilerOptions.module === "number" ?
- compilerOptions.module :
- getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS;
- }
- ts.getEmitModuleKind = getEmitModuleKind;
- function hasZeroOrOneAsteriskCharacter(str) {
- var seenAsterisk = false;
- for (var i = 0; i < str.length; i++) {
- if (str.charCodeAt(i) === 42) {
- if (!seenAsterisk) {
- seenAsterisk = true;
- }
- else {
- return false;
- }
- }
- }
- return true;
- }
- ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
function isRootedDiskPath(path) {
return getRootLength(path) !== 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
- function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
- return !isRootedDiskPath(absoluteOrRelativePath)
- ? absoluteOrRelativePath
- : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false);
- }
- ts.convertToRelativePath = convertToRelativePath;
function normalizedPathComponents(path, rootLength) {
var normalizedParts = getNormalizedParts(path, rootLength);
return [path.substr(0, rootLength)].concat(normalizedParts);
@@ -1433,14 +1384,6 @@ var ts;
return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
ts.getSupportedExtensions = getSupportedExtensions;
- function hasJavaScriptFileExtension(fileName) {
- return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
- }
- ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
- function hasTypeScriptFileExtension(fileName) {
- return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
- }
- ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension;
function isSupportedSourceFileName(fileName, compilerOptions) {
if (!fileName) {
return false;
@@ -1619,10 +1562,6 @@ var ts;
: (function (fileName) { return fileName.toLowerCase(); });
}
ts.createGetCanonicalFileName = createGetCanonicalFileName;
- function positionIsSynthesized(pos) {
- return !(pos >= 0);
- }
- ts.positionIsSynthesized = positionIsSynthesized;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -2053,37 +1992,18 @@ var ts;
realpath: realpath
};
}
- function recursiveCreateDirectory(directoryPath, sys) {
- var basePath = ts.getDirectoryPath(directoryPath);
- var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath);
- if (shouldCreateParent) {
- recursiveCreateDirectory(basePath, sys);
- }
- if (shouldCreateParent || !sys.directoryExists(directoryPath)) {
- sys.createDirectory(directoryPath);
- }
- }
- var sys;
if (typeof ChakraHost !== "undefined") {
- sys = getChakraSystem();
+ return getChakraSystem();
}
else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
- sys = getWScriptSystem();
+ return getWScriptSystem();
}
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
- sys = getNodeSystem();
+ return getNodeSystem();
}
- if (sys) {
- var originalWriteFile_1 = sys.writeFile;
- sys.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);
- };
+ else {
+ return undefined;
}
- return sys;
})();
})(ts || (ts = {}));
var ts;
@@ -2803,7 +2723,6 @@ var ts;
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." },
Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." },
- Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -5457,6 +5376,10 @@ var ts;
return false;
}
ts.isPartOfExpression = isPartOfExpression;
+ function isExternalModuleNameRelative(moduleName) {
+ return /^\.\.?($|[\\/])/.test(moduleName);
+ }
+ ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
var moduleState = ts.getModuleInstanceState(node);
return moduleState === 1 ||
@@ -6054,10 +5977,14 @@ var ts;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(node) {
- return ts.positionIsSynthesized(node.pos)
- || ts.positionIsSynthesized(node.end);
+ return positionIsSynthesized(node.pos)
+ || positionIsSynthesized(node.end);
}
ts.nodeIsSynthesized = nodeIsSynthesized;
+ function positionIsSynthesized(pos) {
+ return !(pos >= 0);
+ }
+ ts.positionIsSynthesized = positionIsSynthesized;
function getOriginalNode(node) {
if (node) {
while (node.original !== undefined) {
@@ -6493,16 +6420,28 @@ var ts;
function getDeclarationEmitOutputFilePath(sourceFile, host) {
var options = host.getCompilerOptions();
var outputDir = options.declarationDir || options.outDir;
- var path = outputDir
- ? getSourceFilePathInNewDir(sourceFile, host, outputDir)
- : sourceFile.fileName;
- return ts.removeFileExtension(path) + ".d.ts";
+ if (options.declaration) {
+ var path = outputDir
+ ? getSourceFilePathInNewDir(sourceFile, host, outputDir)
+ : sourceFile.fileName;
+ return ts.removeFileExtension(path) + ".d.ts";
+ }
}
ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
+ function getEmitScriptTarget(compilerOptions) {
+ return compilerOptions.target || 0;
+ }
+ ts.getEmitScriptTarget = getEmitScriptTarget;
+ function getEmitModuleKind(compilerOptions) {
+ return typeof compilerOptions.module === "number" ?
+ compilerOptions.module :
+ getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS;
+ }
+ ts.getEmitModuleKind = getEmitModuleKind;
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- var moduleKind = ts.getEmitModuleKind(options);
+ var moduleKind = getEmitModuleKind(options);
var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
var sourceFiles = host.getSourceFiles();
return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule);
@@ -6519,7 +6458,7 @@ var ts;
function isBundleEmitNonExternalModule(sourceFile) {
return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile);
}
- function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) {
+ function forEachTransformedEmitFile(host, sourceFiles, action) {
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
onBundledEmit(host, sourceFiles);
@@ -6546,7 +6485,7 @@ var ts;
}
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && emitOnlyDtsFiles ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
+ var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false);
}
function onBundledEmit(host, sourceFiles) {
@@ -6562,7 +6501,7 @@ var ts;
function getSourceMapFilePath(jsFilePath, options) {
return options.sourceMap ? jsFilePath + ".map" : undefined;
}
- function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) {
+ function forEachExpectedEmitFile(host, action, targetSourceFile) {
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
onBundledEmit(host);
@@ -6589,19 +6528,18 @@ var ts;
}
}
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
var emitFileNames = {
jsFilePath: jsFilePath,
sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
- declarationFilePath: declarationFilePath
+ declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined
};
- action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles);
+ action(emitFileNames, [sourceFile], false);
}
function onBundledEmit(host) {
var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) &&
!host.isSourceFileFromExternalLibrary(sourceFile) &&
(!ts.isExternalModule(sourceFile) ||
- !!ts.getEmitModuleKind(options)); });
+ !!getEmitModuleKind(options)); });
if (bundledSources.length) {
var jsFilePath = options.outFile || options.out;
var emitFileNames = {
@@ -6609,7 +6547,7 @@ var ts;
sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined
};
- action(emitFileNames, bundledSources, true, emitOnlyDtsFiles);
+ action(emitFileNames, bundledSources, true);
}
}
}
@@ -6966,6 +6904,14 @@ var ts;
return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined;
}
ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
+ function hasJavaScriptFileExtension(fileName) {
+ return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
+ function hasTypeScriptFileExtension(fileName) {
+ return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension;
function tryExtractTypeScriptExtension(fileName) {
return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
}
@@ -7056,6 +7002,12 @@ var ts;
return result;
}
ts.convertToBase64 = convertToBase64;
+ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
+ return !ts.isRootedDiskPath(absoluteOrRelativePath)
+ ? absoluteOrRelativePath
+ : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false);
+ }
+ ts.convertToRelativePath = convertToRelativePath;
var carriageReturnLineFeed = "\r\n";
var lineFeed = "\n";
function getNewLineCharacter(options) {
@@ -7156,7 +7108,7 @@ var ts;
}
ts.formatSyntaxKind = formatSyntaxKind;
function movePos(pos, value) {
- return ts.positionIsSynthesized(pos) ? -1 : pos + value;
+ return positionIsSynthesized(pos) ? -1 : pos + value;
}
ts.movePos = movePos;
function createRange(pos, end) {
@@ -7225,7 +7177,7 @@ var ts;
}
ts.positionsAreOnSameLine = positionsAreOnSameLine;
function getStartPositionOfRange(range, sourceFile) {
- return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
+ return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
}
ts.getStartPositionOfRange = getStartPositionOfRange;
function collectExternalModuleInfo(sourceFile, resolver) {
@@ -15250,600 +15202,6 @@ var ts;
})(IncrementalParser || (IncrementalParser = {}));
})(ts || (ts = {}));
var ts;
-(function (ts) {
- function trace(host, message) {
- host.trace(ts.formatMessage.apply(undefined, arguments));
- }
- ts.trace = trace;
- function isTraceEnabled(compilerOptions, host) {
- return compilerOptions.traceResolution && host.trace !== undefined;
- }
- ts.isTraceEnabled = isTraceEnabled;
- function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) {
- return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
- }
- ts.createResolvedModule = createResolvedModule;
- function moduleHasNonRelativeName(moduleName) {
- return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
- }
- function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
- var jsonContent = readJson(packageJsonPath, state.host);
- function tryReadFromField(fieldName) {
- if (ts.hasProperty(jsonContent, fieldName)) {
- var typesFile = jsonContent[fieldName];
- if (typeof typesFile === "string") {
- var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1);
- }
- return typesFilePath_1;
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
- }
- }
- }
- }
- var typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
- if (typesFilePath) {
- return typesFilePath;
- }
- if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main);
- }
- var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main));
- return mainFilePath;
- }
- return undefined;
- }
- function readJson(path, host) {
- try {
- var jsonText = host.readFile(path);
- return jsonText ? JSON.parse(jsonText) : {};
- }
- catch (e) {
- return {};
- }
- }
- var typeReferenceExtensions = [".d.ts"];
- 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();
- }
- return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
- }
- ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
- function getDefaultTypeRoots(currentDirectory, host) {
- if (!host.directoryExists) {
- return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
- }
- var typeRoots;
- while (true) {
- var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes);
- if (host.directoryExists(atTypes)) {
- (typeRoots || (typeRoots = [])).push(atTypes);
- }
- var parent_6 = ts.getDirectoryPath(currentDirectory);
- if (parent_6 === currentDirectory) {
- break;
- }
- currentDirectory = parent_6;
- }
- return typeRoots;
- }
- var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
- function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
- var traceEnabled = isTraceEnabled(options, host);
- var moduleResolutionState = {
- compilerOptions: options,
- host: host,
- skipTsx: true,
- 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 = [];
- if (typeRoots && typeRoots.length) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
- }
- var primarySearchPaths = typeRoots;
- for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) {
- var typeRoot = primarySearchPaths_1[_i];
- var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
- var candidateDirectory = ts.getDirectoryPath(candidate);
- var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState);
- if (resolvedFile_1) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true);
- }
- return {
- resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 },
- failedLookupLocations: failedLookupLocations
- };
- }
- }
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
- }
- }
- var resolvedFile;
- var initialLocationForSecondaryLookup;
- if (containingFile) {
- initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile);
- }
- if (initialLocationForSecondaryLookup !== undefined) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
- }
- resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false);
- if (traceEnabled) {
- if (resolvedFile) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
- }
- else {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
- }
- }
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
- }
- }
- return {
- resolvedTypeReferenceDirective: resolvedFile
- ? { primary: false, resolvedFileName: resolvedFile }
- : undefined,
- failedLookupLocations: failedLookupLocations
- };
- }
- ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
- function getAutomaticTypeDirectiveNames(options, host) {
- if (options.types) {
- return options.types;
- }
- 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));
- var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
- if (!isNotNeededPackage) {
- result.push(ts.getBaseFileName(normalized));
- }
- }
- }
- }
- }
- }
- return result;
- }
- ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
- function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
- }
- 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]);
- }
- }
- var result;
- switch (moduleResolution) {
- case ts.ModuleResolutionKind.NodeJs:
- result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
- case ts.ModuleResolutionKind.Classic:
- result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
- }
- 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;
- }
- ts.resolveModuleName = resolveModuleName;
- function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
- if (moduleHasNonRelativeName(moduleName)) {
- return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
- }
- else {
- return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
- }
- }
- function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
- if (!state.compilerOptions.rootDirs) {
- return undefined;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
- }
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- var matchedRootDir;
- var matchedNormalizedPrefix;
- for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
- var rootDir = _a[_i];
- var normalizedRoot = ts.normalizePath(rootDir);
- if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
- normalizedRoot += ts.directorySeparator;
- }
- var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
- (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
- }
- if (isLongestMatchingPrefix) {
- matchedNormalizedPrefix = normalizedRoot;
- matchedRootDir = rootDir;
- }
- }
- if (matchedNormalizedPrefix) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
- }
- var suffix = candidate.substr(matchedNormalizedPrefix.length);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
- }
- var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
- if (resolvedFileName) {
- return resolvedFileName;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
- }
- for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
- var rootDir = _c[_b];
- if (rootDir === matchedRootDir) {
- continue;
- }
- var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
- }
- var baseDirectory = ts.getDirectoryPath(candidate_1);
- var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
- if (resolvedFileName_1) {
- return resolvedFileName_1;
- }
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
- }
- }
- return undefined;
- }
- function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) {
- if (!state.compilerOptions.baseUrl) {
- return undefined;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
- }
- var matchedPattern = undefined;
- if (state.compilerOptions.paths) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
- }
- matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
- }
- if (matchedPattern) {
- var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
- var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
- }
- for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) {
- var subst = _a[_i];
- var path = matchedStar ? subst.replace("*", matchedStar) : subst;
- var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
- }
- var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- if (resolvedFileName) {
- return resolvedFileName;
- }
- }
- return undefined;
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
- }
- return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- }
- }
- 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) {
- return patternString;
- }
- }
- return findBestPatternMatch(patterns, function (_) { return _; }, candidate);
- }
- function patternText(_a) {
- var prefix = _a.prefix, suffix = _a.suffix;
- return prefix + "*" + suffix;
- }
- function matchedText(pattern, candidate) {
- ts.Debug.assert(isPatternMatch(pattern, candidate));
- return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
- }
- function findBestPatternMatch(values, getPattern, candidate) {
- var matchedValue = undefined;
- 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;
- }
- ts.findBestPatternMatch = findBestPatternMatch;
- function isPatternMatch(_a, candidate) {
- var prefix = _a.prefix, suffix = _a.suffix;
- return candidate.length >= prefix.length + suffix.length &&
- ts.startsWith(candidate, prefix) &&
- ts.endsWith(candidate, suffix);
- }
- function tryParsePattern(pattern) {
- ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern));
- var indexOfStar = pattern.indexOf("*");
- return indexOfStar === -1 ? undefined : {
- prefix: pattern.substr(0, indexOfStar),
- suffix: pattern.substr(indexOfStar + 1)
- };
- }
- ts.tryParsePattern = tryParsePattern;
- function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var failedLookupLocations = [];
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false };
- var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state);
- var isExternalLibraryImport = false;
- if (!resolvedFileName) {
- if (moduleHasNonRelativeName(moduleName)) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
- }
- resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false);
- isExternalLibraryImport = resolvedFileName !== undefined;
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state);
- }
- }
- if (resolvedFileName && host.realpath) {
- var originalFileName = resolvedFileName;
- resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName));
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName);
- }
- }
- return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
- }
- ts.nodeModuleNameResolver = nodeModuleNameResolver;
- function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
- }
- var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
- return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
- }
- function directoryProbablyExists(directoryName, host) {
- return !host.directoryExists || host.directoryExists(directoryName);
- }
- ts.directoryProbablyExists = directoryProbablyExists;
- function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
- var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
- if (resolvedByAddingExtension) {
- return resolvedByAddingExtension;
- }
- if (ts.hasJavaScriptFileExtension(candidate)) {
- var extensionless = ts.removeFileExtension(candidate);
- if (state.traceEnabled) {
- var extension = candidate.substring(extensionless.length);
- trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
- }
- return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
- }
- }
- function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
- if (!onlyRecordFailures) {
- var directory = ts.getDirectoryPath(candidate);
- if (directory) {
- onlyRecordFailures = !directoryProbablyExists(directory, state.host);
- }
- }
- return ts.forEach(extensions, function (ext) {
- return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state);
- });
- }
- function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) {
- if (!onlyRecordFailures && state.host.fileExists(fileName)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
- }
- return fileName;
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
- }
- failedLookupLocation.push(fileName);
- return undefined;
- }
- }
- function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) {
- var packageJsonPath = pathToPackageJson(candidate);
- var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
- if (directoryExists && state.host.fileExists(packageJsonPath)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
- }
- var typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
- if (typesFile) {
- var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host);
- var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) ||
- tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state);
- if (result) {
- return result;
- }
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field);
- }
- }
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
- }
- failedLookupLocation.push(packageJsonPath);
- }
- return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
- }
- function pathToPackageJson(directory) {
- return ts.combinePaths(directory, "package.json");
- }
- function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) {
- var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
- var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
- var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
- var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions);
- var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
- if (result) {
- return result;
- }
- result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
- if (result) {
- return result;
- }
- }
- function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) {
- directory = ts.normalizeSlashes(directory);
- while (true) {
- var baseName = ts.getBaseFileName(directory);
- if (baseName !== "node_modules") {
- var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
- if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
- return packageResult;
- }
- else {
- var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
- if (typesResult || packageResult) {
- return typesResult || packageResult;
- }
- }
- }
- var parentPath = ts.getDirectoryPath(directory);
- if (parentPath === directory || checkOneLevel) {
- break;
- }
- directory = parentPath;
- }
- return undefined;
- }
- ts.loadModuleFromNodeModules = loadModuleFromNodeModules;
- function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
- var failedLookupLocations = [];
- var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
- if (resolvedFileName) {
- return createResolvedModule(resolvedFileName, false, failedLookupLocations);
- }
- var referencedSourceFile;
- if (moduleHasNonRelativeName(moduleName)) {
- while (true) {
- var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state);
- if (referencedSourceFile) {
- break;
- }
- var parentPath = ts.getDirectoryPath(containingDirectory);
- if (parentPath === containingDirectory) {
- break;
- }
- containingDirectory = parentPath;
- }
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state);
- }
- return referencedSourceFile
- ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations }
- : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
- }
- ts.classicNameResolver = classicNameResolver;
-})(ts || (ts = {}));
-var ts;
(function (ts) {
function getModuleInstanceState(node) {
if (node.kind === 222 || node.kind === 223) {
@@ -17369,12 +16727,12 @@ var ts;
return;
}
else {
- var parent_7 = node.parent;
- if (!ts.isExternalModule(parent_7)) {
+ var parent_6 = node.parent;
+ if (!ts.isExternalModule(parent_6)) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files));
return;
}
- if (!parent_7.isDeclarationFile) {
+ if (!parent_6.isDeclarationFile) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files));
return;
}
@@ -19652,9 +19010,9 @@ var ts;
var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2));
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
- var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
- if (parent_8) {
- walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), false);
+ var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
+ if (parent_7) {
+ walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false);
}
}
if (accessibleSymbolChain) {
@@ -19776,12 +19134,12 @@ var ts;
var length_1 = outerTypeParameters.length;
while (i < length_1) {
var start = i;
- var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
+ var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
do {
i++;
- } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9);
+ } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8);
if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
- writeSymbolTypeReference(parent_9, typeArguments, start, i, flags);
+ writeSymbolTypeReference(parent_8, typeArguments, start, i, flags);
writePunctuation(writer, 21);
}
}
@@ -20170,12 +19528,12 @@ var ts;
if (ts.isExternalModuleAugmentation(node)) {
return true;
}
- var parent_10 = getDeclarationContainer(node);
+ var parent_9 = getDeclarationContainer(node);
if (!(ts.getCombinedModifierFlags(node) & 1) &&
- !(node.kind !== 229 && parent_10.kind !== 256 && ts.isInAmbientContext(parent_10))) {
- return isGlobalSourceFile(parent_10);
+ !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) {
+ return isGlobalSourceFile(parent_9);
}
- return isDeclarationVisible(parent_10);
+ return isDeclarationVisible(parent_9);
case 145:
case 144:
case 149:
@@ -26950,19 +26308,19 @@ var ts;
for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
var signature = signatures_2[_i];
var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
- var parent_11 = signature.declaration && signature.declaration.parent;
+ var parent_10 = signature.declaration && signature.declaration.parent;
if (!lastSymbol || symbol === lastSymbol) {
- if (lastParent && parent_11 === lastParent) {
+ if (lastParent && parent_10 === lastParent) {
index++;
}
else {
- lastParent = parent_11;
+ lastParent = parent_10;
index = cutoffIndex;
}
}
else {
index = cutoffIndex = result.length;
- lastParent = parent_11;
+ lastParent = parent_10;
}
lastSymbol = symbol;
if (signature.hasLiteralTypes) {
@@ -28958,9 +28316,9 @@ var ts;
case 156:
case 147:
case 146:
- var parent_12 = node.parent;
- if (node === parent_12.type) {
- return parent_12;
+ var parent_11 = node.parent;
+ if (node === parent_11.type) {
+ return parent_11;
}
}
}
@@ -30191,12 +29549,12 @@ var ts;
if (node.propertyName && node.propertyName.kind === 140) {
checkComputedPropertyName(node.propertyName);
}
- var parent_13 = node.parent.parent;
- var parentType = getTypeForBindingElementParent(parent_13);
+ var parent_12 = node.parent.parent;
+ var parentType = getTypeForBindingElementParent(parent_12);
var name_21 = node.propertyName || node.name;
var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21));
- if (parent_13.initializer && property && getParentOfSymbol(property)) {
- checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property);
+ if (parent_12.initializer && property && getParentOfSymbol(property)) {
+ checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property);
}
}
if (ts.isBindingPattern(node.name)) {
@@ -32554,9 +31912,9 @@ var ts;
}
var location = reference;
if (startInDeclarationContainer) {
- var parent_14 = reference.parent;
- if (ts.isDeclaration(parent_14) && reference === parent_14.name) {
- location = getDeclarationContainer(parent_14);
+ var parent_13 = reference.parent;
+ if (ts.isDeclaration(parent_13) && reference === parent_13.name) {
+ location = getDeclarationContainer(parent_13);
}
}
return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined);
@@ -32665,9 +32023,9 @@ var ts;
}
var current = symbol;
while (true) {
- var parent_15 = getParentOfSymbol(current);
- if (parent_15) {
- current = parent_15;
+ var parent_14 = getParentOfSymbol(current);
+ if (parent_14) {
+ current = parent_14;
}
else {
break;
@@ -42435,11 +41793,11 @@ var ts;
return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);
function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) {
var declarationFilePath = _a.declarationFilePath;
- emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false);
+ emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);
}
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
- function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) {
+ function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) {
var newLine = host.getNewLine();
var compilerOptions = host.getCompilerOptions();
var write;
@@ -42475,7 +41833,7 @@ var ts;
ts.forEach(sourceFile.referencedFiles, function (fileReference) {
var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference);
if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) {
- if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) {
+ if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) {
addedGlobalFileReference = true;
}
emittedReferencedFiles.push(referencedFile);
@@ -42660,7 +42018,7 @@ var ts;
}
else {
errorNameNode = declaration.name;
- resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer);
errorNameNode = undefined;
}
}
@@ -42672,7 +42030,7 @@ var ts;
}
else {
errorNameNode = signature.name;
- resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer);
errorNameNode = undefined;
}
}
@@ -42865,7 +42223,7 @@ var ts;
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic;
- resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer);
write(";");
writeLine();
write(node.isExportEquals ? "export = " : "export default ");
@@ -43271,7 +42629,7 @@ var ts;
}
else {
writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError;
- resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer);
}
function getHeritageClauseVisibilityError(symbolAccessibilityResult) {
var diagnosticMessage;
@@ -43839,14 +43197,14 @@ var ts;
return emitSourceFile(node);
}
}
- function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) {
+ function writeReferencePath(referencedFile, addBundledFileReference) {
var declFileName;
var addedBundledEmitReference = false;
if (ts.isDeclarationFile(referencedFile)) {
declFileName = referencedFile.fileName;
}
else {
- ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles);
+ ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile);
}
if (declFileName) {
declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false);
@@ -43863,8 +43221,8 @@ var ts;
}
}
}
- function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) {
- var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles);
+ function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) {
+ var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit);
var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit;
if (!emitSkipped) {
var declarationOutput = emitDeclarationResult.referencesOutput
@@ -43890,7 +43248,7 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) {
+ function emitFiles(resolver, host, targetSourceFile) {
var delimiters = createDelimiterMap();
var brackets = createBracketsMap();
var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};";
@@ -43937,7 +43295,7 @@ var ts;
ts.performance.measure("transformTime", "beforeTransform");
var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode;
ts.performance.mark("beforePrint");
- ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile, emitOnlyDtsFiles);
+ ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile);
transformed.dispose();
ts.performance.measure("printTime", "beforePrint");
return {
@@ -43954,7 +43312,7 @@ var ts;
emitSkipped = true;
}
if (declarationFilePath) {
- emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped;
+ emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped;
}
if (!emitSkipped && emittedFilesList) {
emittedFilesList.push(jsFilePath);
@@ -45969,7 +45327,7 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- ts.version = "2.0.5";
+ ts.version = "2.1.0";
var emptyArray = [];
function findConfigFile(searchPath, fileExists, configName) {
if (configName === void 0) { configName = "tsconfig.json"; }
@@ -46024,6 +45382,581 @@ var ts;
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}
ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
+ function trace(host, message) {
+ host.trace(ts.formatMessage.apply(undefined, arguments));
+ }
+ function isTraceEnabled(compilerOptions, host) {
+ return compilerOptions.traceResolution && host.trace !== undefined;
+ }
+ function hasZeroOrOneAsteriskCharacter(str) {
+ var seenAsterisk = false;
+ for (var i = 0; i < str.length; i++) {
+ if (str.charCodeAt(i) === 42) {
+ if (!seenAsterisk) {
+ seenAsterisk = true;
+ }
+ else {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+ ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) {
+ return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
+ }
+ function moduleHasNonRelativeName(moduleName) {
+ return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
+ }
+ function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
+ var jsonContent = readJson(packageJsonPath, state.host);
+ function tryReadFromField(fieldName) {
+ if (ts.hasProperty(jsonContent, fieldName)) {
+ var typesFile = jsonContent[fieldName];
+ if (typeof typesFile === "string") {
+ var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1);
+ }
+ return typesFilePath_1;
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
+ }
+ }
+ }
+ }
+ var typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
+ if (typesFilePath) {
+ return typesFilePath;
+ }
+ if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main);
+ }
+ var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main));
+ return mainFilePath;
+ }
+ return undefined;
+ }
+ function readJson(path, host) {
+ try {
+ var jsonText = host.readFile(path);
+ return jsonText ? JSON.parse(jsonText) : {};
+ }
+ catch (e) {
+ return {};
+ }
+ }
+ var typeReferenceExtensions = [".d.ts"];
+ 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();
+ }
+ return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
+ }
+ ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
+ function getDefaultTypeRoots(currentDirectory, host) {
+ if (!host.directoryExists) {
+ return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
+ }
+ var typeRoots;
+ while (true) {
+ var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes);
+ if (host.directoryExists(atTypes)) {
+ (typeRoots || (typeRoots = [])).push(atTypes);
+ }
+ var parent_15 = ts.getDirectoryPath(currentDirectory);
+ if (parent_15 === currentDirectory) {
+ break;
+ }
+ currentDirectory = parent_15;
+ }
+ return typeRoots;
+ }
+ var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
+ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
+ var traceEnabled = isTraceEnabled(options, host);
+ var moduleResolutionState = {
+ compilerOptions: options,
+ host: host,
+ skipTsx: true,
+ 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 = [];
+ if (typeRoots && typeRoots.length) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
+ }
+ var primarySearchPaths = typeRoots;
+ for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) {
+ var typeRoot = primarySearchPaths_1[_i];
+ var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
+ var candidateDirectory = ts.getDirectoryPath(candidate);
+ var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState);
+ if (resolvedFile_1) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true);
+ }
+ return {
+ resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 },
+ failedLookupLocations: failedLookupLocations
+ };
+ }
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
+ }
+ }
+ var resolvedFile;
+ var initialLocationForSecondaryLookup;
+ if (containingFile) {
+ initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile);
+ }
+ if (initialLocationForSecondaryLookup !== undefined) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
+ }
+ resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState);
+ if (traceEnabled) {
+ if (resolvedFile) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
+ }
+ else {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
+ }
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
+ }
+ }
+ return {
+ resolvedTypeReferenceDirective: resolvedFile
+ ? { primary: false, resolvedFileName: resolvedFile }
+ : undefined,
+ failedLookupLocations: failedLookupLocations
+ };
+ }
+ ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
+ function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
+ }
+ 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]);
+ }
+ }
+ var result;
+ switch (moduleResolution) {
+ case ts.ModuleResolutionKind.NodeJs:
+ result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
+ break;
+ case ts.ModuleResolutionKind.Classic:
+ result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
+ break;
+ }
+ 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;
+ }
+ ts.resolveModuleName = resolveModuleName;
+ function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
+ if (moduleHasNonRelativeName(moduleName)) {
+ return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
+ }
+ else {
+ return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
+ }
+ }
+ function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
+ if (!state.compilerOptions.rootDirs) {
+ return undefined;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
+ }
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ var matchedRootDir;
+ var matchedNormalizedPrefix;
+ for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
+ var rootDir = _a[_i];
+ var normalizedRoot = ts.normalizePath(rootDir);
+ if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
+ normalizedRoot += ts.directorySeparator;
+ }
+ var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
+ (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
+ }
+ if (isLongestMatchingPrefix) {
+ matchedNormalizedPrefix = normalizedRoot;
+ matchedRootDir = rootDir;
+ }
+ }
+ if (matchedNormalizedPrefix) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
+ }
+ var suffix = candidate.substr(matchedNormalizedPrefix.length);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
+ }
+ var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
+ if (resolvedFileName) {
+ return resolvedFileName;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
+ }
+ for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
+ var rootDir = _c[_b];
+ if (rootDir === matchedRootDir) {
+ continue;
+ }
+ var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
+ }
+ var baseDirectory = ts.getDirectoryPath(candidate_1);
+ var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
+ if (resolvedFileName_1) {
+ return resolvedFileName_1;
+ }
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
+ }
+ }
+ return undefined;
+ }
+ function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) {
+ if (!state.compilerOptions.baseUrl) {
+ return undefined;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
+ }
+ var matchedPattern = undefined;
+ if (state.compilerOptions.paths) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
+ }
+ matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
+ }
+ if (matchedPattern) {
+ var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
+ var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
+ }
+ for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) {
+ var subst = _a[_i];
+ var path = matchedStar ? subst.replace("*", matchedStar) : subst;
+ var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
+ }
+ var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ if (resolvedFileName) {
+ return resolvedFileName;
+ }
+ }
+ return undefined;
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
+ }
+ return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ }
+ }
+ 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) {
+ return patternString;
+ }
+ }
+ return findBestPatternMatch(patterns, function (_) { return _; }, candidate);
+ }
+ function patternText(_a) {
+ var prefix = _a.prefix, suffix = _a.suffix;
+ return prefix + "*" + suffix;
+ }
+ function matchedText(pattern, candidate) {
+ ts.Debug.assert(isPatternMatch(pattern, candidate));
+ return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
+ }
+ function findBestPatternMatch(values, getPattern, candidate) {
+ var matchedValue = undefined;
+ 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;
+ }
+ ts.findBestPatternMatch = findBestPatternMatch;
+ function isPatternMatch(_a, candidate) {
+ var prefix = _a.prefix, suffix = _a.suffix;
+ return candidate.length >= prefix.length + suffix.length &&
+ ts.startsWith(candidate, prefix) &&
+ ts.endsWith(candidate, suffix);
+ }
+ function tryParsePattern(pattern) {
+ ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
+ var indexOfStar = pattern.indexOf("*");
+ return indexOfStar === -1 ? undefined : {
+ prefix: pattern.substr(0, indexOfStar),
+ suffix: pattern.substr(indexOfStar + 1)
+ };
+ }
+ ts.tryParsePattern = tryParsePattern;
+ function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var failedLookupLocations = [];
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false };
+ var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state);
+ var isExternalLibraryImport = false;
+ if (!resolvedFileName) {
+ if (moduleHasNonRelativeName(moduleName)) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
+ }
+ resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state);
+ isExternalLibraryImport = resolvedFileName !== undefined;
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state);
+ }
+ }
+ if (resolvedFileName && host.realpath) {
+ var originalFileName = resolvedFileName;
+ resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName));
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName);
+ }
+ }
+ return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
+ }
+ ts.nodeModuleNameResolver = nodeModuleNameResolver;
+ function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
+ }
+ var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
+ return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
+ }
+ function directoryProbablyExists(directoryName, host) {
+ return !host.directoryExists || host.directoryExists(directoryName);
+ }
+ ts.directoryProbablyExists = directoryProbablyExists;
+ function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
+ var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
+ if (resolvedByAddingExtension) {
+ return resolvedByAddingExtension;
+ }
+ if (ts.hasJavaScriptFileExtension(candidate)) {
+ var extensionless = ts.removeFileExtension(candidate);
+ if (state.traceEnabled) {
+ var extension = candidate.substring(extensionless.length);
+ trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
+ }
+ return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
+ }
+ }
+ function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
+ if (!onlyRecordFailures) {
+ var directory = ts.getDirectoryPath(candidate);
+ if (directory) {
+ onlyRecordFailures = !directoryProbablyExists(directory, state.host);
+ }
+ }
+ return ts.forEach(extensions, function (ext) {
+ return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state);
+ });
+ }
+ function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) {
+ if (!onlyRecordFailures && state.host.fileExists(fileName)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
+ }
+ return fileName;
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
+ }
+ failedLookupLocation.push(fileName);
+ return undefined;
+ }
+ }
+ function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) {
+ var packageJsonPath = pathToPackageJson(candidate);
+ var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
+ if (directoryExists && state.host.fileExists(packageJsonPath)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
+ }
+ var typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
+ if (typesFile) {
+ var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host);
+ var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) ||
+ tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state);
+ if (result) {
+ return result;
+ }
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field);
+ }
+ }
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
+ }
+ failedLookupLocation.push(packageJsonPath);
+ }
+ return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
+ }
+ function pathToPackageJson(directory) {
+ return ts.combinePaths(directory, "package.json");
+ }
+ function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) {
+ var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
+ var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
+ var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
+ var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions);
+ var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
+ if (result) {
+ return result;
+ }
+ result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
+ if (result) {
+ return result;
+ }
+ }
+ function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) {
+ directory = ts.normalizeSlashes(directory);
+ while (true) {
+ var baseName = ts.getBaseFileName(directory);
+ if (baseName !== "node_modules") {
+ var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
+ if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
+ return packageResult;
+ }
+ else {
+ var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
+ if (typesResult || packageResult) {
+ return typesResult || packageResult;
+ }
+ }
+ }
+ var parentPath = ts.getDirectoryPath(directory);
+ if (parentPath === directory) {
+ break;
+ }
+ directory = parentPath;
+ }
+ return undefined;
+ }
+ function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
+ var failedLookupLocations = [];
+ var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
+ if (resolvedFileName) {
+ return createResolvedModule(resolvedFileName, false, failedLookupLocations);
+ }
+ var referencedSourceFile;
+ if (moduleHasNonRelativeName(moduleName)) {
+ while (true) {
+ var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state);
+ if (referencedSourceFile) {
+ break;
+ }
+ var parentPath = ts.getDirectoryPath(containingDirectory);
+ if (parentPath === containingDirectory) {
+ break;
+ }
+ containingDirectory = parentPath;
+ }
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state);
+ }
+ return referencedSourceFile
+ ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations }
+ : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
+ }
+ ts.classicNameResolver = classicNameResolver;
function createCompilerHost(options, setParentNodes) {
var existingDirectories = ts.createMap();
function getCanonicalFileName(fileName) {
@@ -46193,6 +46126,33 @@ var ts;
}
return resolutions;
}
+ function getAutomaticTypeDirectiveNames(options, host) {
+ if (options.types) {
+ return options.types;
+ }
+ 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));
+ var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
+ if (!isNotNeededPackage) {
+ result.push(ts.getBaseFileName(normalized));
+ }
+ }
+ }
+ }
+ }
+ }
+ return result;
+ }
+ ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
function createProgram(rootNames, options, host, oldProgram) {
var program;
var files = [];
@@ -46218,7 +46178,7 @@ var ts;
resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); };
}
else {
- var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; };
+ var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; };
resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); };
}
var resolveTypeReferenceDirectiveNamesWorker;
@@ -46226,14 +46186,14 @@ var ts;
resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); };
}
else {
- var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; };
+ var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; };
resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); };
}
var filesByName = ts.createFileMap();
var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined;
if (!tryReuseStructureFromOldProgram()) {
ts.forEach(rootNames, function (name) { return processRootFile(name, false); });
- var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host);
+ var typeReferences = getAutomaticTypeDirectiveNames(options, host);
if (typeReferences) {
var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts");
var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
@@ -46276,8 +46236,7 @@ var ts;
getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
- getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
- dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker
+ getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -46424,19 +46383,16 @@ var ts;
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true));
}
- function dropDiagnosticsProducingTypeChecker() {
- diagnosticsProducingTypeChecker = undefined;
- }
function getTypeChecker() {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
- function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
- return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); });
+ function emit(sourceFile, writeFileCallback, cancellationToken) {
+ return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
}
- function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
+ function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) {
var declarationDiagnostics = [];
if (options.noEmit) {
return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
@@ -46457,7 +46413,7 @@ var ts;
}
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
ts.performance.mark("beforeEmit");
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -47054,7 +47010,7 @@ var ts;
if (!ts.hasProperty(options.paths, key)) {
continue;
}
- if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
+ if (!hasZeroOrOneAsteriskCharacter(key)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key));
}
if (ts.isArray(options.paths[key])) {
@@ -47065,7 +47021,7 @@ var ts;
var subst = _a[_i];
var typeOfSubst = typeof subst;
if (typeOfSubst === "string") {
- if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
+ if (!hasZeroOrOneAsteriskCharacter(subst)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key));
}
}
@@ -47180,13 +47136,11 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
ts.optionDeclarations = [
{
name: "charset",
type: "string"
},
- ts.compileOnSaveCommandLineOption,
{
name: "declaration",
shortName: "d",
@@ -47810,11 +47764,10 @@ var ts;
return parseConfigFileTextToJson(fileName, text);
}
ts.readConfigFile = readConfigFile;
- function parseConfigFileTextToJson(fileName, jsonText, stripComments) {
- if (stripComments === void 0) { stripComments = true; }
+ function parseConfigFileTextToJson(fileName, jsonText) {
try {
- var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText;
- return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} };
+ var jsonTextWithoutComments = removeComments(jsonText);
+ return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} };
}
catch (e) {
return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) };
@@ -47948,15 +47901,13 @@ var ts;
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,
typingOptions: typingOptions,
raw: json,
errors: errors,
- wildcardDirectories: wildcardDirectories,
- compileOnSave: compileOnSave
+ wildcardDirectories: wildcardDirectories
};
function tryExtendsName(extendedConfig) {
if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) {
@@ -48034,17 +47985,6 @@ var ts;
var _b;
}
ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
- 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;
- }
- ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson;
function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
var errors = [];
var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
@@ -48058,9 +47998,7 @@ var ts;
}
ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
- var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
- ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true }
- : {};
+ var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {};
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
return options;
}
diff --git a/lib/tsserver.js b/lib/tsserver.js
index dcf9e1a1218..8bb071cf4a1 100644
--- a/lib/tsserver.js
+++ b/lib/tsserver.js
@@ -150,7 +150,6 @@ var ts;
contains: contains,
remove: remove,
forEachValue: forEachValueInMap,
- getKeys: getKeys,
clear: clear
};
function forEachValueInMap(f) {
@@ -158,13 +157,6 @@ var ts;
f(key, files[key]);
}
}
- function getKeys() {
- var keys = [];
- for (var key in files) {
- keys.push(key);
- }
- return keys;
- }
function get(path) {
return files[toKey(path)];
}
@@ -541,22 +533,16 @@ var ts;
: undefined;
}
ts.lastOrUndefined = lastOrUndefined;
- function binarySearch(array, value, comparer) {
- if (!array || array.length === 0) {
- return -1;
- }
+ function binarySearch(array, value) {
var low = 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) {
+ if (midValue === value) {
return middle;
}
- else if (comparer(midValue, value) > 0) {
+ else if (midValue > value) {
high = middle - 1;
}
else {
@@ -1026,45 +1012,10 @@ var ts;
return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1;
}
ts.isUrl = isUrl;
- function isExternalModuleNameRelative(moduleName) {
- return /^\.\.?($|[\\/])/.test(moduleName);
- }
- ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
- function getEmitScriptTarget(compilerOptions) {
- return compilerOptions.target || 0;
- }
- ts.getEmitScriptTarget = getEmitScriptTarget;
- function getEmitModuleKind(compilerOptions) {
- return typeof compilerOptions.module === "number" ?
- compilerOptions.module :
- getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS;
- }
- ts.getEmitModuleKind = getEmitModuleKind;
- function hasZeroOrOneAsteriskCharacter(str) {
- var seenAsterisk = false;
- for (var i = 0; i < str.length; i++) {
- if (str.charCodeAt(i) === 42) {
- if (!seenAsterisk) {
- seenAsterisk = true;
- }
- else {
- return false;
- }
- }
- }
- return true;
- }
- ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
function isRootedDiskPath(path) {
return getRootLength(path) !== 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
- function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
- return !isRootedDiskPath(absoluteOrRelativePath)
- ? absoluteOrRelativePath
- : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false);
- }
- ts.convertToRelativePath = convertToRelativePath;
function normalizedPathComponents(path, rootLength) {
var normalizedParts = getNormalizedParts(path, rootLength);
return [path.substr(0, rootLength)].concat(normalizedParts);
@@ -1438,14 +1389,6 @@ var ts;
return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
ts.getSupportedExtensions = getSupportedExtensions;
- function hasJavaScriptFileExtension(fileName) {
- return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
- }
- ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
- function hasTypeScriptFileExtension(fileName) {
- return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
- }
- ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension;
function isSupportedSourceFileName(fileName, compilerOptions) {
if (!fileName) {
return false;
@@ -1624,10 +1567,6 @@ var ts;
: (function (fileName) { return fileName.toLowerCase(); });
}
ts.createGetCanonicalFileName = createGetCanonicalFileName;
- function positionIsSynthesized(pos) {
- return !(pos >= 0);
- }
- ts.positionIsSynthesized = positionIsSynthesized;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -2058,37 +1997,18 @@ var ts;
realpath: realpath
};
}
- function recursiveCreateDirectory(directoryPath, sys) {
- var basePath = ts.getDirectoryPath(directoryPath);
- var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath);
- if (shouldCreateParent) {
- recursiveCreateDirectory(basePath, sys);
- }
- if (shouldCreateParent || !sys.directoryExists(directoryPath)) {
- sys.createDirectory(directoryPath);
- }
- }
- var sys;
if (typeof ChakraHost !== "undefined") {
- sys = getChakraSystem();
+ return getChakraSystem();
}
else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
- sys = getWScriptSystem();
+ return getWScriptSystem();
}
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
- sys = getNodeSystem();
+ return getNodeSystem();
}
- if (sys) {
- var originalWriteFile_1 = sys.writeFile;
- sys.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);
- };
+ else {
+ return undefined;
}
- return sys;
})();
})(ts || (ts = {}));
var ts;
@@ -2808,7 +2728,6 @@ var ts;
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." },
Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." },
- Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -4415,13 +4334,11 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
ts.optionDeclarations = [
{
name: "charset",
type: "string"
},
- ts.compileOnSaveCommandLineOption,
{
name: "declaration",
shortName: "d",
@@ -5045,11 +4962,10 @@ var ts;
return parseConfigFileTextToJson(fileName, text);
}
ts.readConfigFile = readConfigFile;
- function parseConfigFileTextToJson(fileName, jsonText, stripComments) {
- if (stripComments === void 0) { stripComments = true; }
+ function parseConfigFileTextToJson(fileName, jsonText) {
try {
- var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText;
- return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} };
+ var jsonTextWithoutComments = removeComments(jsonText);
+ return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} };
}
catch (e) {
return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) };
@@ -5183,15 +5099,13 @@ var ts;
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,
typingOptions: typingOptions,
raw: json,
errors: errors,
- wildcardDirectories: wildcardDirectories,
- compileOnSave: compileOnSave
+ wildcardDirectories: wildcardDirectories
};
function tryExtendsName(extendedConfig) {
if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) {
@@ -5269,17 +5183,6 @@ var ts;
var _b;
}
ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
- 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;
- }
- ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson;
function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
var errors = [];
var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
@@ -5293,9 +5196,7 @@ var ts;
}
ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
- var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
- ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true }
- : {};
+ var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {};
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
return options;
}
@@ -5494,381 +5395,6 @@ var ts;
}
})(ts || (ts = {}));
var ts;
-(function (ts) {
- var JsTyping;
- (function (JsTyping) {
- ;
- ;
- var safeList;
- var EmptySafeList = ts.createMap();
- function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) {
- var inferredTypings = ts.createMap();
- if (!typingOptions || !typingOptions.enableAutoDiscovery) {
- return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
- }
- fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) {
- var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f));
- return kind === 1 || kind === 2;
- });
- if (!safeList) {
- var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
- safeList = result.config ? ts.createMap(result.config) : EmptySafeList;
- }
- var filesToWatch = [];
- var searchDirs = [];
- var exclude = [];
- mergeTypings(typingOptions.include);
- exclude = typingOptions.exclude || [];
- var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath);
- if (projectRootPath !== undefined) {
- 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);
- for (var name_7 in packageNameToTypingLocation) {
- if (name_7 in inferredTypings && !inferredTypings[name_7]) {
- inferredTypings[name_7] = packageNameToTypingLocation[name_7];
- }
- }
- for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) {
- var excludeTypingName = exclude_1[_a];
- delete inferredTypings[excludeTypingName];
- }
- var newTypingNames = [];
- var cachedTypingPaths = [];
- for (var typing in inferredTypings) {
- if (inferredTypings[typing] !== undefined) {
- cachedTypingPaths.push(inferredTypings[typing]);
- }
- else {
- newTypingNames.push(typing);
- }
- }
- return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
- function mergeTypings(typingNames) {
- if (!typingNames) {
- return;
- }
- for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) {
- var typing = typingNames_1[_i];
- if (!(typing in inferredTypings)) {
- inferredTypings[typing] = undefined;
- }
- }
- }
- function getTypingNamesFromJson(jsonPath, filesToWatch) {
- var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); });
- if (result.config) {
- var jsonConfig = result.config;
- filesToWatch.push(jsonPath);
- if (jsonConfig.dependencies) {
- mergeTypings(ts.getOwnKeys(jsonConfig.dependencies));
- }
- if (jsonConfig.devDependencies) {
- mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies));
- }
- if (jsonConfig.optionalDependencies) {
- mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies));
- }
- if (jsonConfig.peerDependencies) {
- mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies));
- }
- }
- }
- function getTypingNamesFromSourceFileNames(fileNames) {
- var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension);
- var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); });
- var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); });
- if (safeList !== EmptySafeList) {
- mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; }));
- }
- var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; });
- if (hasJsxFile) {
- mergeTypings(["react"]);
- }
- }
- function getTypingNamesFromNodeModuleFolder(nodeModulesPath) {
- if (!host.directoryExists(nodeModulesPath)) {
- return;
- }
- var typingNames = [];
- var fileNames = host.readDirectory(nodeModulesPath, [".json"], undefined, undefined, 2);
- for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
- var fileName = fileNames_2[_i];
- var normalizedFileName = ts.normalizePath(fileName);
- if (ts.getBaseFileName(normalizedFileName) !== "package.json") {
- continue;
- }
- var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- if (!result.config) {
- continue;
- }
- var packageJson = result.config;
- if (packageJson._requiredBy &&
- ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
- continue;
- }
- if (!packageJson.name) {
- continue;
- }
- if (packageJson.typings) {
- var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName));
- inferredTypings[packageJson.name] = absolutePath;
- }
- else {
- typingNames.push(packageJson.name);
- }
- }
- mergeTypings(typingNames);
- }
- }
- JsTyping.discoverTypings = discoverTypings;
- })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- (function (LogLevel) {
- LogLevel[LogLevel["terse"] = 0] = "terse";
- LogLevel[LogLevel["normal"] = 1] = "normal";
- LogLevel[LogLevel["requestTime"] = 2] = "requestTime";
- LogLevel[LogLevel["verbose"] = 3] = "verbose";
- })(server.LogLevel || (server.LogLevel = {}));
- var LogLevel = server.LogLevel;
- server.emptyArray = [];
- var Msg;
- (function (Msg) {
- Msg.Err = "Err";
- Msg.Info = "Info";
- Msg.Perf = "Perf";
- })(Msg = server.Msg || (server.Msg = {}));
- function getProjectRootPath(project) {
- switch (project.projectKind) {
- case server.ProjectKind.Configured:
- return ts.getDirectoryPath(project.getProjectName());
- case server.ProjectKind.Inferred:
- return "";
- case server.ProjectKind.External:
- var projectName = ts.normalizeSlashes(project.getProjectName());
- return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName;
- }
- }
- function createInstallTypingsRequest(project, typingOptions, cachePath) {
- return {
- projectName: project.getProjectName(),
- fileNames: project.getFileNames(),
- compilerOptions: project.getCompilerOptions(),
- typingOptions: typingOptions,
- projectRootPath: getProjectRootPath(project),
- cachePath: cachePath,
- kind: "discover"
- };
- }
- server.createInstallTypingsRequest = createInstallTypingsRequest;
- var Errors;
- (function (Errors) {
- function ThrowNoProject() {
- throw new Error("No Project.");
- }
- Errors.ThrowNoProject = ThrowNoProject;
- function ThrowProjectLanguageServiceDisabled() {
- throw new Error("The project's language service is disabled.");
- }
- Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled;
- function ThrowProjectDoesNotContainDocument(fileName, project) {
- throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'");
- }
- Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument;
- })(Errors = server.Errors || (server.Errors = {}));
- function getDefaultFormatCodeSettings(host) {
- return {
- indentSize: 4,
- tabSize: 4,
- newLineCharacter: host.newLine || "\n",
- convertTabsToSpaces: true,
- indentStyle: ts.IndentStyle.Smart,
- insertSpaceAfterCommaDelimiter: true,
- insertSpaceAfterSemicolonInForStatements: true,
- insertSpaceBeforeAndAfterBinaryOperators: true,
- insertSpaceAfterKeywordsInControlFlowStatements: true,
- insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
- insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
- insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
- insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
- placeOpenBraceOnNewLineForFunctions: false,
- placeOpenBraceOnNewLineForControlBlocks: false
- };
- }
- server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings;
- function mergeMaps(target, source) {
- for (var key in source) {
- if (ts.hasProperty(source, key)) {
- target[key] = source[key];
- }
- }
- }
- server.mergeMaps = mergeMaps;
- function removeItemFromSet(items, itemToRemove) {
- if (items.length === 0) {
- return;
- }
- var index = items.indexOf(itemToRemove);
- if (index < 0) {
- return;
- }
- if (index === items.length - 1) {
- items.pop();
- }
- else {
- items[index] = items.pop();
- }
- }
- server.removeItemFromSet = removeItemFromSet;
- function toNormalizedPath(fileName) {
- return ts.normalizePath(fileName);
- }
- server.toNormalizedPath = toNormalizedPath;
- function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) {
- var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory);
- return getCanonicalFileName(f);
- }
- server.normalizedPathToPath = normalizedPathToPath;
- function asNormalizedPath(fileName) {
- return fileName;
- }
- server.asNormalizedPath = asNormalizedPath;
- function createNormalizedPathMap() {
- var map = Object.create(null);
- return {
- get: function (path) {
- return map[path];
- },
- set: function (path, value) {
- map[path] = value;
- },
- contains: function (path) {
- return ts.hasProperty(map, path);
- },
- remove: function (path) {
- delete map[path];
- }
- };
- }
- server.createNormalizedPathMap = createNormalizedPathMap;
- function throwLanguageServiceIsDisabledError() {
- throw new Error("LanguageService is disabled");
- }
- server.nullLanguageService = {
- cleanupSemanticCache: function () { return throwLanguageServiceIsDisabledError(); },
- getSyntacticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); },
- getSemanticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); },
- getCompilerOptionsDiagnostics: function () { return throwLanguageServiceIsDisabledError(); },
- getSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); },
- getEncodedSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); },
- getSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); },
- getEncodedSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); },
- getCompletionsAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- findReferences: function () { return throwLanguageServiceIsDisabledError(); },
- getCompletionEntryDetails: function () { return throwLanguageServiceIsDisabledError(); },
- getQuickInfoAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- findRenameLocations: function () { return throwLanguageServiceIsDisabledError(); },
- getNameOrDottedNameSpan: function () { return throwLanguageServiceIsDisabledError(); },
- getBreakpointStatementAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getBraceMatchingAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getSignatureHelpItems: function () { return throwLanguageServiceIsDisabledError(); },
- getDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getRenameInfo: function () { return throwLanguageServiceIsDisabledError(); },
- getTypeDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getReferencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getDocumentHighlights: function () { return throwLanguageServiceIsDisabledError(); },
- getOccurrencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getNavigateToItems: function () { return throwLanguageServiceIsDisabledError(); },
- getNavigationBarItems: function () { return throwLanguageServiceIsDisabledError(); },
- getOutliningSpans: function () { return throwLanguageServiceIsDisabledError(); },
- getTodoComments: function () { return throwLanguageServiceIsDisabledError(); },
- getIndentationAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getFormattingEditsForRange: function () { return throwLanguageServiceIsDisabledError(); },
- getFormattingEditsForDocument: function () { return throwLanguageServiceIsDisabledError(); },
- getFormattingEditsAfterKeystroke: function () { return throwLanguageServiceIsDisabledError(); },
- getDocCommentTemplateAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- isValidBraceCompletionAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getEmitOutput: function () { return throwLanguageServiceIsDisabledError(); },
- getProgram: function () { return throwLanguageServiceIsDisabledError(); },
- getNonBoundSourceFile: function () { return throwLanguageServiceIsDisabledError(); },
- dispose: function () { return throwLanguageServiceIsDisabledError(); },
- getCompletionEntrySymbol: function () { return throwLanguageServiceIsDisabledError(); },
- getImplementationAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getSourceFile: function () { return throwLanguageServiceIsDisabledError(); }
- };
- server.nullLanguageServiceHost = {
- setCompilationSettings: function () { return undefined; },
- notifyFileRemoved: function () { return undefined; }
- };
- function isInferredProjectName(name) {
- return /dev\/null\/inferredProject\d+\*/.test(name);
- }
- server.isInferredProjectName = isInferredProjectName;
- function makeInferredProjectName(counter) {
- return "/dev/null/inferredProject" + counter + "*";
- }
- server.makeInferredProjectName = makeInferredProjectName;
- var ThrottledOperations = (function () {
- function ThrottledOperations(host) {
- this.host = host;
- this.pendingTimeouts = ts.createMap();
- }
- ThrottledOperations.prototype.schedule = function (operationId, delay, cb) {
- if (ts.hasProperty(this.pendingTimeouts, operationId)) {
- this.host.clearTimeout(this.pendingTimeouts[operationId]);
- }
- this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb);
- };
- ThrottledOperations.run = function (self, operationId, cb) {
- delete self.pendingTimeouts[operationId];
- cb();
- };
- return ThrottledOperations;
- }());
- server.ThrottledOperations = ThrottledOperations;
- var GcTimer = (function () {
- function GcTimer(host, delay, logger) {
- this.host = host;
- this.delay = delay;
- this.logger = logger;
- }
- GcTimer.prototype.scheduleCollect = function () {
- if (!this.host.gc || this.timerId != undefined) {
- return;
- }
- this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this);
- };
- GcTimer.run = function (self) {
- self.timerId = undefined;
- var log = self.logger.hasLevel(LogLevel.requestTime);
- var before = log && self.host.getMemoryUsage();
- self.host.gc();
- if (log) {
- var after = self.host.getMemoryUsage();
- self.logger.perftrc("GC::before " + before + ", after " + after);
- }
- };
- return GcTimer;
- }());
- server.GcTimer = GcTimer;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
(function (ts) {
ts.externalHelpersModuleNameText = "tslib";
function getDeclarationOfKind(symbol, kind) {
@@ -6504,9 +6030,9 @@ var ts;
return;
default:
if (isFunctionLike(node)) {
- var name_8 = node.name;
- if (name_8 && name_8.kind === 140) {
- traverse(name_8.expression);
+ var name_7 = node.name;
+ if (name_7 && name_7.kind === 140) {
+ traverse(name_7.expression);
return;
}
}
@@ -6917,6 +6443,10 @@ var ts;
return false;
}
ts.isPartOfExpression = isPartOfExpression;
+ function isExternalModuleNameRelative(moduleName) {
+ return /^\.\.?($|[\\/])/.test(moduleName);
+ }
+ ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
var moduleState = ts.getModuleInstanceState(node);
return moduleState === 1 ||
@@ -7163,8 +6693,8 @@ var ts;
}
}
else if (param.name.kind === 69) {
- var name_9 = param.name.text;
- var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_9; });
+ var name_8 = param.name.text;
+ var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_8; });
if (paramTags) {
return paramTags;
}
@@ -7514,10 +7044,14 @@ var ts;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(node) {
- return ts.positionIsSynthesized(node.pos)
- || ts.positionIsSynthesized(node.end);
+ return positionIsSynthesized(node.pos)
+ || positionIsSynthesized(node.end);
}
ts.nodeIsSynthesized = nodeIsSynthesized;
+ function positionIsSynthesized(pos) {
+ return !(pos >= 0);
+ }
+ ts.positionIsSynthesized = positionIsSynthesized;
function getOriginalNode(node) {
if (node) {
while (node.original !== undefined) {
@@ -7953,16 +7487,28 @@ var ts;
function getDeclarationEmitOutputFilePath(sourceFile, host) {
var options = host.getCompilerOptions();
var outputDir = options.declarationDir || options.outDir;
- var path = outputDir
- ? getSourceFilePathInNewDir(sourceFile, host, outputDir)
- : sourceFile.fileName;
- return ts.removeFileExtension(path) + ".d.ts";
+ if (options.declaration) {
+ var path = outputDir
+ ? getSourceFilePathInNewDir(sourceFile, host, outputDir)
+ : sourceFile.fileName;
+ return ts.removeFileExtension(path) + ".d.ts";
+ }
}
ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
+ function getEmitScriptTarget(compilerOptions) {
+ return compilerOptions.target || 0;
+ }
+ ts.getEmitScriptTarget = getEmitScriptTarget;
+ function getEmitModuleKind(compilerOptions) {
+ return typeof compilerOptions.module === "number" ?
+ compilerOptions.module :
+ getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS;
+ }
+ ts.getEmitModuleKind = getEmitModuleKind;
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- var moduleKind = ts.getEmitModuleKind(options);
+ var moduleKind = getEmitModuleKind(options);
var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
var sourceFiles = host.getSourceFiles();
return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule);
@@ -7979,7 +7525,7 @@ var ts;
function isBundleEmitNonExternalModule(sourceFile) {
return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile);
}
- function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) {
+ function forEachTransformedEmitFile(host, sourceFiles, action) {
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
onBundledEmit(host, sourceFiles);
@@ -8006,7 +7552,7 @@ var ts;
}
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && emitOnlyDtsFiles ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
+ var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false);
}
function onBundledEmit(host, sourceFiles) {
@@ -8022,7 +7568,7 @@ var ts;
function getSourceMapFilePath(jsFilePath, options) {
return options.sourceMap ? jsFilePath + ".map" : undefined;
}
- function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) {
+ function forEachExpectedEmitFile(host, action, targetSourceFile) {
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
onBundledEmit(host);
@@ -8049,19 +7595,18 @@ var ts;
}
}
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
var emitFileNames = {
jsFilePath: jsFilePath,
sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
- declarationFilePath: declarationFilePath
+ declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined
};
- action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles);
+ action(emitFileNames, [sourceFile], false);
}
function onBundledEmit(host) {
var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) &&
!host.isSourceFileFromExternalLibrary(sourceFile) &&
(!ts.isExternalModule(sourceFile) ||
- !!ts.getEmitModuleKind(options)); });
+ !!getEmitModuleKind(options)); });
if (bundledSources.length) {
var jsFilePath = options.outFile || options.out;
var emitFileNames = {
@@ -8069,7 +7614,7 @@ var ts;
sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined
};
- action(emitFileNames, bundledSources, true, emitOnlyDtsFiles);
+ action(emitFileNames, bundledSources, true);
}
}
}
@@ -8426,6 +7971,14 @@ var ts;
return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined;
}
ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
+ function hasJavaScriptFileExtension(fileName) {
+ return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
+ function hasTypeScriptFileExtension(fileName) {
+ return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension;
function tryExtractTypeScriptExtension(fileName) {
return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
}
@@ -8516,6 +8069,12 @@ var ts;
return result;
}
ts.convertToBase64 = convertToBase64;
+ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
+ return !ts.isRootedDiskPath(absoluteOrRelativePath)
+ ? absoluteOrRelativePath
+ : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false);
+ }
+ ts.convertToRelativePath = convertToRelativePath;
var carriageReturnLineFeed = "\r\n";
var lineFeed = "\n";
function getNewLineCharacter(options) {
@@ -8604,9 +8163,9 @@ var ts;
if (syntaxKindCache[kind]) {
return syntaxKindCache[kind];
}
- for (var name_10 in syntaxKindEnum) {
- if (syntaxKindEnum[name_10] === kind) {
- return syntaxKindCache[kind] = kind.toString() + " (" + name_10 + ")";
+ for (var name_9 in syntaxKindEnum) {
+ if (syntaxKindEnum[name_9] === kind) {
+ return syntaxKindCache[kind] = kind.toString() + " (" + name_9 + ")";
}
}
}
@@ -8616,7 +8175,7 @@ var ts;
}
ts.formatSyntaxKind = formatSyntaxKind;
function movePos(pos, value) {
- return ts.positionIsSynthesized(pos) ? -1 : pos + value;
+ return positionIsSynthesized(pos) ? -1 : pos + value;
}
ts.movePos = movePos;
function createRange(pos, end) {
@@ -8685,7 +8244,7 @@ var ts;
}
ts.positionsAreOnSameLine = positionsAreOnSameLine;
function getStartPositionOfRange(range, sourceFile) {
- return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
+ return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
}
ts.getStartPositionOfRange = getStartPositionOfRange;
function collectExternalModuleInfo(sourceFile, resolver) {
@@ -8722,8 +8281,8 @@ var ts;
else {
for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) {
var specifier = _c[_b];
- var name_11 = (specifier.propertyName || specifier.name).text;
- (exportSpecifiers[name_11] || (exportSpecifiers[name_11] = [])).push(specifier);
+ var name_10 = (specifier.propertyName || specifier.name).text;
+ (exportSpecifiers[name_10] || (exportSpecifiers[name_10] = [])).push(specifier);
}
}
break;
@@ -9443,600 +9002,6 @@ var ts;
ts.getCombinedNodeFlags = getCombinedNodeFlags;
})(ts || (ts = {}));
var ts;
-(function (ts) {
- function trace(host, message) {
- host.trace(ts.formatMessage.apply(undefined, arguments));
- }
- ts.trace = trace;
- function isTraceEnabled(compilerOptions, host) {
- return compilerOptions.traceResolution && host.trace !== undefined;
- }
- ts.isTraceEnabled = isTraceEnabled;
- function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) {
- return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
- }
- ts.createResolvedModule = createResolvedModule;
- function moduleHasNonRelativeName(moduleName) {
- return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
- }
- function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
- var jsonContent = readJson(packageJsonPath, state.host);
- function tryReadFromField(fieldName) {
- if (ts.hasProperty(jsonContent, fieldName)) {
- var typesFile = jsonContent[fieldName];
- if (typeof typesFile === "string") {
- var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1);
- }
- return typesFilePath_1;
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
- }
- }
- }
- }
- var typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
- if (typesFilePath) {
- return typesFilePath;
- }
- if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main);
- }
- var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main));
- return mainFilePath;
- }
- return undefined;
- }
- function readJson(path, host) {
- try {
- var jsonText = host.readFile(path);
- return jsonText ? JSON.parse(jsonText) : {};
- }
- catch (e) {
- return {};
- }
- }
- var typeReferenceExtensions = [".d.ts"];
- 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();
- }
- return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
- }
- ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
- function getDefaultTypeRoots(currentDirectory, host) {
- if (!host.directoryExists) {
- return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
- }
- var typeRoots;
- while (true) {
- var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes);
- if (host.directoryExists(atTypes)) {
- (typeRoots || (typeRoots = [])).push(atTypes);
- }
- var parent_6 = ts.getDirectoryPath(currentDirectory);
- if (parent_6 === currentDirectory) {
- break;
- }
- currentDirectory = parent_6;
- }
- return typeRoots;
- }
- var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
- function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
- var traceEnabled = isTraceEnabled(options, host);
- var moduleResolutionState = {
- compilerOptions: options,
- host: host,
- skipTsx: true,
- 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 = [];
- if (typeRoots && typeRoots.length) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
- }
- var primarySearchPaths = typeRoots;
- for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) {
- var typeRoot = primarySearchPaths_1[_i];
- var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
- var candidateDirectory = ts.getDirectoryPath(candidate);
- var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState);
- if (resolvedFile_1) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true);
- }
- return {
- resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 },
- failedLookupLocations: failedLookupLocations
- };
- }
- }
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
- }
- }
- var resolvedFile;
- var initialLocationForSecondaryLookup;
- if (containingFile) {
- initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile);
- }
- if (initialLocationForSecondaryLookup !== undefined) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
- }
- resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false);
- if (traceEnabled) {
- if (resolvedFile) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
- }
- else {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
- }
- }
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
- }
- }
- return {
- resolvedTypeReferenceDirective: resolvedFile
- ? { primary: false, resolvedFileName: resolvedFile }
- : undefined,
- failedLookupLocations: failedLookupLocations
- };
- }
- ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
- function getAutomaticTypeDirectiveNames(options, host) {
- if (options.types) {
- return options.types;
- }
- 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));
- var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
- if (!isNotNeededPackage) {
- result.push(ts.getBaseFileName(normalized));
- }
- }
- }
- }
- }
- }
- return result;
- }
- ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
- function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
- }
- 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]);
- }
- }
- var result;
- switch (moduleResolution) {
- case ts.ModuleResolutionKind.NodeJs:
- result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
- case ts.ModuleResolutionKind.Classic:
- result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
- }
- 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;
- }
- ts.resolveModuleName = resolveModuleName;
- function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
- if (moduleHasNonRelativeName(moduleName)) {
- return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
- }
- else {
- return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
- }
- }
- function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
- if (!state.compilerOptions.rootDirs) {
- return undefined;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
- }
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- var matchedRootDir;
- var matchedNormalizedPrefix;
- for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
- var rootDir = _a[_i];
- var normalizedRoot = ts.normalizePath(rootDir);
- if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
- normalizedRoot += ts.directorySeparator;
- }
- var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
- (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
- }
- if (isLongestMatchingPrefix) {
- matchedNormalizedPrefix = normalizedRoot;
- matchedRootDir = rootDir;
- }
- }
- if (matchedNormalizedPrefix) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
- }
- var suffix = candidate.substr(matchedNormalizedPrefix.length);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
- }
- var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
- if (resolvedFileName) {
- return resolvedFileName;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
- }
- for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
- var rootDir = _c[_b];
- if (rootDir === matchedRootDir) {
- continue;
- }
- var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
- }
- var baseDirectory = ts.getDirectoryPath(candidate_1);
- var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
- if (resolvedFileName_1) {
- return resolvedFileName_1;
- }
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
- }
- }
- return undefined;
- }
- function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) {
- if (!state.compilerOptions.baseUrl) {
- return undefined;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
- }
- var matchedPattern = undefined;
- if (state.compilerOptions.paths) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
- }
- matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
- }
- if (matchedPattern) {
- var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
- var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
- }
- for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) {
- var subst = _a[_i];
- var path = matchedStar ? subst.replace("*", matchedStar) : subst;
- var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
- }
- var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- if (resolvedFileName) {
- return resolvedFileName;
- }
- }
- return undefined;
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
- }
- return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- }
- }
- 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) {
- return patternString;
- }
- }
- return findBestPatternMatch(patterns, function (_) { return _; }, candidate);
- }
- function patternText(_a) {
- var prefix = _a.prefix, suffix = _a.suffix;
- return prefix + "*" + suffix;
- }
- function matchedText(pattern, candidate) {
- ts.Debug.assert(isPatternMatch(pattern, candidate));
- return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
- }
- function findBestPatternMatch(values, getPattern, candidate) {
- var matchedValue = undefined;
- 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;
- }
- ts.findBestPatternMatch = findBestPatternMatch;
- function isPatternMatch(_a, candidate) {
- var prefix = _a.prefix, suffix = _a.suffix;
- return candidate.length >= prefix.length + suffix.length &&
- ts.startsWith(candidate, prefix) &&
- ts.endsWith(candidate, suffix);
- }
- function tryParsePattern(pattern) {
- ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern));
- var indexOfStar = pattern.indexOf("*");
- return indexOfStar === -1 ? undefined : {
- prefix: pattern.substr(0, indexOfStar),
- suffix: pattern.substr(indexOfStar + 1)
- };
- }
- ts.tryParsePattern = tryParsePattern;
- function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var failedLookupLocations = [];
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false };
- var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state);
- var isExternalLibraryImport = false;
- if (!resolvedFileName) {
- if (moduleHasNonRelativeName(moduleName)) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
- }
- resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false);
- isExternalLibraryImport = resolvedFileName !== undefined;
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state);
- }
- }
- if (resolvedFileName && host.realpath) {
- var originalFileName = resolvedFileName;
- resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName));
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName);
- }
- }
- return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
- }
- ts.nodeModuleNameResolver = nodeModuleNameResolver;
- function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
- }
- var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
- return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
- }
- function directoryProbablyExists(directoryName, host) {
- return !host.directoryExists || host.directoryExists(directoryName);
- }
- ts.directoryProbablyExists = directoryProbablyExists;
- function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
- var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
- if (resolvedByAddingExtension) {
- return resolvedByAddingExtension;
- }
- if (ts.hasJavaScriptFileExtension(candidate)) {
- var extensionless = ts.removeFileExtension(candidate);
- if (state.traceEnabled) {
- var extension = candidate.substring(extensionless.length);
- trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
- }
- return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
- }
- }
- function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
- if (!onlyRecordFailures) {
- var directory = ts.getDirectoryPath(candidate);
- if (directory) {
- onlyRecordFailures = !directoryProbablyExists(directory, state.host);
- }
- }
- return ts.forEach(extensions, function (ext) {
- return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state);
- });
- }
- function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) {
- if (!onlyRecordFailures && state.host.fileExists(fileName)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
- }
- return fileName;
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
- }
- failedLookupLocation.push(fileName);
- return undefined;
- }
- }
- function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) {
- var packageJsonPath = pathToPackageJson(candidate);
- var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
- if (directoryExists && state.host.fileExists(packageJsonPath)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
- }
- var typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
- if (typesFile) {
- var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host);
- var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) ||
- tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state);
- if (result) {
- return result;
- }
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field);
- }
- }
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
- }
- failedLookupLocation.push(packageJsonPath);
- }
- return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
- }
- function pathToPackageJson(directory) {
- return ts.combinePaths(directory, "package.json");
- }
- function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) {
- var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
- var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
- var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
- var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions);
- var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
- if (result) {
- return result;
- }
- result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
- if (result) {
- return result;
- }
- }
- function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) {
- directory = ts.normalizeSlashes(directory);
- while (true) {
- var baseName = ts.getBaseFileName(directory);
- if (baseName !== "node_modules") {
- var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
- if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
- return packageResult;
- }
- else {
- var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
- if (typesResult || packageResult) {
- return typesResult || packageResult;
- }
- }
- }
- var parentPath = ts.getDirectoryPath(directory);
- if (parentPath === directory || checkOneLevel) {
- break;
- }
- directory = parentPath;
- }
- return undefined;
- }
- ts.loadModuleFromNodeModules = loadModuleFromNodeModules;
- function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
- var failedLookupLocations = [];
- var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
- if (resolvedFileName) {
- return createResolvedModule(resolvedFileName, false, failedLookupLocations);
- }
- var referencedSourceFile;
- if (moduleHasNonRelativeName(moduleName)) {
- while (true) {
- var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state);
- if (referencedSourceFile) {
- break;
- }
- var parentPath = ts.getDirectoryPath(containingDirectory);
- if (parentPath === containingDirectory) {
- break;
- }
- containingDirectory = parentPath;
- }
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state);
- }
- return referencedSourceFile
- ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations }
- : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
- }
- ts.classicNameResolver = classicNameResolver;
-})(ts || (ts = {}));
-var ts;
(function (ts) {
var NodeConstructor;
var SourceFileConstructor;
@@ -12157,8 +11122,8 @@ var ts;
function getLocalNameForExternalImport(node, sourceFile) {
var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !ts.isDefaultImport(node)) {
- var name_12 = namespaceDeclaration.name;
- return ts.isGeneratedIdentifier(name_12) ? name_12 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name));
+ var name_11 = namespaceDeclaration.name;
+ return ts.isGeneratedIdentifier(name_11) ? name_11 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name));
}
if (node.kind === 230 && node.importClause) {
return getGeneratedNameForNode(node);
@@ -15857,8 +14822,8 @@ var ts;
return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers);
}
if (decorators || modifiers) {
- var name_13 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected);
- return parsePropertyDeclaration(fullStart, decorators, modifiers, name_13, undefined);
+ var name_12 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected);
+ return parsePropertyDeclaration(fullStart, decorators, modifiers, name_12, undefined);
}
ts.Debug.fail("Should not have attempted to parse class member declaration.");
}
@@ -16882,8 +15847,8 @@ var ts;
if (typeExpression.type.kind === 267) {
var jsDocTypeReference = typeExpression.type;
if (jsDocTypeReference.name.kind === 69) {
- var name_14 = jsDocTypeReference.name;
- if (name_14.text === "Object") {
+ var name_13 = jsDocTypeReference.name;
+ if (name_13.text === "Object") {
typedefTag.jsDocTypeLiteral = scanChildTags();
}
}
@@ -16969,14 +15934,14 @@ var ts;
}
var typeParameters = createNodeArray();
while (true) {
- var name_15 = parseJSDocIdentifierName();
+ var name_14 = parseJSDocIdentifierName();
skipWhitespace();
- if (!name_15) {
+ if (!name_14) {
parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected);
return undefined;
}
- var typeParameter = createNode(141, name_15.pos);
- typeParameter.name = name_15;
+ var typeParameter = createNode(141, name_14.pos);
+ typeParameter.name = name_14;
finishNode(typeParameter);
typeParameters.push(typeParameter);
if (token() === 24) {
@@ -18829,12 +17794,12 @@ var ts;
return;
}
else {
- var parent_7 = node.parent;
- if (!ts.isExternalModule(parent_7)) {
+ var parent_6 = node.parent;
+ if (!ts.isExternalModule(parent_6)) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files));
return;
}
- if (!parent_7.isDeclarationFile) {
+ if (!parent_6.isDeclarationFile) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files));
return;
}
@@ -20370,28 +19335,28 @@ var ts;
var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier);
if (targetSymbol) {
- var name_16 = specifier.propertyName || specifier.name;
- if (name_16.text) {
+ var name_15 = specifier.propertyName || specifier.name;
+ if (name_15.text) {
if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
return moduleSymbol;
}
var symbolFromVariable = void 0;
if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) {
- symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_16.text);
+ symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_15.text);
}
else {
- symbolFromVariable = getPropertyOfVariable(targetSymbol, name_16.text);
+ symbolFromVariable = getPropertyOfVariable(targetSymbol, name_15.text);
}
symbolFromVariable = resolveSymbol(symbolFromVariable);
- var symbolFromModule = getExportOfModule(targetSymbol, name_16.text);
- if (!symbolFromModule && allowSyntheticDefaultImports && name_16.text === "default") {
+ var symbolFromModule = getExportOfModule(targetSymbol, name_15.text);
+ if (!symbolFromModule && allowSyntheticDefaultImports && name_15.text === "default") {
symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol);
}
var symbol = symbolFromModule && symbolFromVariable ?
combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
symbolFromModule || symbolFromVariable;
if (!symbol) {
- error(name_16, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_16));
+ error(name_15, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_15));
}
return symbol;
}
@@ -21112,9 +20077,9 @@ var ts;
var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2));
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
- var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
- if (parent_8) {
- walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), false);
+ var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
+ if (parent_7) {
+ walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false);
}
}
if (accessibleSymbolChain) {
@@ -21236,12 +20201,12 @@ var ts;
var length_1 = outerTypeParameters.length;
while (i < length_1) {
var start = i;
- var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
+ var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
do {
i++;
- } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9);
+ } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8);
if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
- writeSymbolTypeReference(parent_9, typeArguments, start, i, flags);
+ writeSymbolTypeReference(parent_8, typeArguments, start, i, flags);
writePunctuation(writer, 21);
}
}
@@ -21630,12 +20595,12 @@ var ts;
if (ts.isExternalModuleAugmentation(node)) {
return true;
}
- var parent_10 = getDeclarationContainer(node);
+ var parent_9 = getDeclarationContainer(node);
if (!(ts.getCombinedModifierFlags(node) & 1) &&
- !(node.kind !== 229 && parent_10.kind !== 256 && ts.isInAmbientContext(parent_10))) {
- return isGlobalSourceFile(parent_10);
+ !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) {
+ return isGlobalSourceFile(parent_9);
}
- return isDeclarationVisible(parent_10);
+ return isDeclarationVisible(parent_9);
case 145:
case 144:
case 149:
@@ -21822,19 +20787,19 @@ var ts;
}
var type;
if (pattern.kind === 167) {
- var name_17 = declaration.propertyName || declaration.name;
- if (isComputedNonLiteralName(name_17)) {
+ var name_16 = declaration.propertyName || declaration.name;
+ if (isComputedNonLiteralName(name_16)) {
return anyType;
}
if (declaration.initializer) {
getContextualType(declaration.initializer);
}
- var text = getTextOfPropertyName(name_17);
+ var text = getTextOfPropertyName(name_16);
type = getTypeOfPropertyOfType(parentType, text) ||
isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) ||
getIndexTypeOfType(parentType, 0);
if (!type) {
- error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_17));
+ error(name_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_16));
return unknownType;
}
}
@@ -27257,11 +26222,11 @@ var ts;
}
if (ts.isBindingPattern(declaration.parent)) {
var parentDeclaration = declaration.parent.parent;
- var name_18 = declaration.propertyName || declaration.name;
+ var name_17 = declaration.propertyName || declaration.name;
if (ts.isVariableLike(parentDeclaration) &&
parentDeclaration.type &&
- !ts.isBindingPattern(name_18)) {
- var text = getTextOfPropertyName(name_18);
+ !ts.isBindingPattern(name_17)) {
+ var text = getTextOfPropertyName(name_17);
if (text) {
return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text);
}
@@ -28301,15 +27266,15 @@ var ts;
return unknownType;
}
if (node.argumentExpression) {
- var name_19 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType);
- if (name_19 !== undefined) {
- var prop = getPropertyOfType(objectType, name_19);
+ var name_18 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType);
+ if (name_18 !== undefined) {
+ var prop = getPropertyOfType(objectType, name_18);
if (prop) {
getNodeLinks(node).resolvedSymbol = prop;
return getTypeOfSymbol(prop);
}
else if (isConstEnum) {
- error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_19, symbolToString(objectType.symbol));
+ error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_18, symbolToString(objectType.symbol));
return unknownType;
}
}
@@ -28410,19 +27375,19 @@ var ts;
for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
var signature = signatures_2[_i];
var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
- var parent_11 = signature.declaration && signature.declaration.parent;
+ var parent_10 = signature.declaration && signature.declaration.parent;
if (!lastSymbol || symbol === lastSymbol) {
- if (lastParent && parent_11 === lastParent) {
+ if (lastParent && parent_10 === lastParent) {
index++;
}
else {
- lastParent = parent_11;
+ lastParent = parent_10;
index = cutoffIndex;
}
}
else {
index = cutoffIndex = result.length;
- lastParent = parent_11;
+ lastParent = parent_10;
}
lastSymbol = symbol;
if (signature.hasLiteralTypes) {
@@ -29725,14 +28690,14 @@ var ts;
}
function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) {
if (property.kind === 253 || property.kind === 254) {
- var name_20 = property.name;
- if (name_20.kind === 140) {
- checkComputedPropertyName(name_20);
+ var name_19 = property.name;
+ if (name_19.kind === 140) {
+ checkComputedPropertyName(name_19);
}
- if (isComputedNonLiteralName(name_20)) {
+ if (isComputedNonLiteralName(name_19)) {
return undefined;
}
- var text = getTextOfPropertyName(name_20);
+ var text = getTextOfPropertyName(name_19);
var type = isTypeAny(objectLiteralType)
? objectLiteralType
: getTypeOfPropertyOfType(objectLiteralType, text) ||
@@ -29747,7 +28712,7 @@ var ts;
}
}
else {
- error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_20));
+ error(name_19, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_19));
}
}
else {
@@ -30396,9 +29361,9 @@ var ts;
else if (parameterName) {
var hasReportedError = false;
for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
- var name_21 = _a[_i].name;
- if (ts.isBindingPattern(name_21) &&
- checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, parameterName, typePredicate.parameterName)) {
+ var name_20 = _a[_i].name;
+ if (ts.isBindingPattern(name_20) &&
+ checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_20, parameterName, typePredicate.parameterName)) {
hasReportedError = true;
break;
}
@@ -30418,9 +29383,9 @@ var ts;
case 156:
case 147:
case 146:
- var parent_12 = node.parent;
- if (node === parent_12.type) {
- return parent_12;
+ var parent_11 = node.parent;
+ if (node === parent_11.type) {
+ return parent_11;
}
}
}
@@ -30430,15 +29395,15 @@ var ts;
if (ts.isOmittedExpression(element)) {
continue;
}
- var name_22 = element.name;
- if (name_22.kind === 69 &&
- name_22.text === predicateVariableName) {
+ var name_21 = element.name;
+ if (name_21.kind === 69 &&
+ name_21.text === predicateVariableName) {
error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
return true;
}
- else if (name_22.kind === 168 ||
- name_22.kind === 167) {
- if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_22, predicateVariableNode, predicateVariableName)) {
+ else if (name_21.kind === 168 ||
+ name_21.kind === 167) {
+ if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, predicateVariableNode, predicateVariableName)) {
return true;
}
}
@@ -31582,8 +30547,8 @@ var ts;
container.kind === 225 ||
container.kind === 256);
if (!namesShareScope) {
- var name_23 = symbolToString(localDeclarationSymbol);
- error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_23, name_23);
+ var name_22 = symbolToString(localDeclarationSymbol);
+ error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_22, name_22);
}
}
}
@@ -31651,12 +30616,12 @@ var ts;
if (node.propertyName && node.propertyName.kind === 140) {
checkComputedPropertyName(node.propertyName);
}
- var parent_13 = node.parent.parent;
- var parentType = getTypeForBindingElementParent(parent_13);
- var name_24 = node.propertyName || node.name;
- var property = getPropertyOfType(parentType, getTextOfPropertyName(name_24));
- if (parent_13.initializer && property && getParentOfSymbol(property)) {
- checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property);
+ var parent_12 = node.parent.parent;
+ var parentType = getTypeForBindingElementParent(parent_12);
+ var name_23 = node.propertyName || node.name;
+ var property = getPropertyOfType(parentType, getTextOfPropertyName(name_23));
+ if (parent_12.initializer && property && getParentOfSymbol(property)) {
+ checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property);
}
}
if (ts.isBindingPattern(node.name)) {
@@ -32853,9 +31818,9 @@ var ts;
break;
case 169:
case 218:
- var name_25 = node.name;
- if (ts.isBindingPattern(name_25)) {
- for (var _b = 0, _c = name_25.elements; _b < _c.length; _b++) {
+ var name_24 = node.name;
+ if (ts.isBindingPattern(name_24)) {
+ for (var _b = 0, _c = name_24.elements; _b < _c.length; _b++) {
var el = _c[_b];
checkModuleAugmentationElement(el, isGlobalAugmentation);
}
@@ -33705,9 +32670,9 @@ var ts;
function getRootSymbols(symbol) {
if (symbol.flags & 268435456) {
var symbols_3 = [];
- var name_26 = symbol.name;
+ var name_25 = symbol.name;
ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) {
- var symbol = getPropertyOfType(t, name_26);
+ var symbol = getPropertyOfType(t, name_25);
if (symbol) {
symbols_3.push(symbol);
}
@@ -34014,9 +32979,9 @@ var ts;
}
var location = reference;
if (startInDeclarationContainer) {
- var parent_14 = reference.parent;
- if (ts.isDeclaration(parent_14) && reference === parent_14.name) {
- location = getDeclarationContainer(parent_14);
+ var parent_13 = reference.parent;
+ if (ts.isDeclaration(parent_13) && reference === parent_13.name) {
+ location = getDeclarationContainer(parent_13);
}
}
return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined);
@@ -34125,9 +33090,9 @@ var ts;
}
var current = symbol;
while (true) {
- var parent_15 = getParentOfSymbol(current);
- if (parent_15) {
- current = parent_15;
+ var parent_14 = getParentOfSymbol(current);
+ if (parent_14) {
+ current = parent_14;
}
else {
break;
@@ -34796,10 +33761,10 @@ var ts;
var GetOrSetAccessor = GetAccessor | SetAccessor;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var prop = _a[_i];
- var name_27 = prop.name;
+ var name_26 = prop.name;
if (prop.kind === 193 ||
- name_27.kind === 140) {
- checkGrammarComputedPropertyName(name_27);
+ name_26.kind === 140) {
+ checkGrammarComputedPropertyName(name_26);
}
if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) {
return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
@@ -34815,8 +33780,8 @@ var ts;
var currentKind = void 0;
if (prop.kind === 253 || prop.kind === 254) {
checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
- if (name_27.kind === 8) {
- checkGrammarNumericLiteral(name_27);
+ if (name_26.kind === 8) {
+ checkGrammarNumericLiteral(name_26);
}
currentKind = Property;
}
@@ -34832,7 +33797,7 @@ var ts;
else {
ts.Debug.fail("Unexpected syntax kind:" + prop.kind);
}
- var effectiveName = ts.getPropertyNameForPropertyNameNode(name_27);
+ var effectiveName = ts.getPropertyNameForPropertyNameNode(name_26);
if (effectiveName === undefined) {
continue;
}
@@ -34842,18 +33807,18 @@ var ts;
else {
var existingKind = seen[effectiveName];
if (currentKind === Property && existingKind === Property) {
- grammarErrorOnNode(name_27, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_27));
+ grammarErrorOnNode(name_26, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_26));
}
else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) {
if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) {
seen[effectiveName] = currentKind | existingKind;
}
else {
- return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
+ return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
}
}
else {
- return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
+ return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
}
}
}
@@ -34866,12 +33831,12 @@ var ts;
continue;
}
var jsxAttr = attr;
- var name_28 = jsxAttr.name;
- if (!seen[name_28.text]) {
- seen[name_28.text] = true;
+ var name_27 = jsxAttr.name;
+ if (!seen[name_27.text]) {
+ seen[name_27.text] = true;
}
else {
- return grammarErrorOnNode(name_28, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
+ return grammarErrorOnNode(name_27, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
}
var initializer = jsxAttr.initializer;
if (initializer && initializer.kind === 248 && !initializer.expression) {
@@ -36232,10 +35197,10 @@ var ts;
emitArrayLiteralAssignment(target, value, location);
}
else {
- var name_29 = ts.getMutableClone(target);
- context.setSourceMapRange(name_29, target);
- context.setCommentRange(name_29, target);
- emitAssignment(name_29, value, location, undefined);
+ var name_28 = ts.getMutableClone(target);
+ context.setSourceMapRange(name_28, target);
+ context.setCommentRange(name_28, target);
+ emitAssignment(name_28, value, location, undefined);
}
}
function emitObjectLiteralAssignment(target, value, location) {
@@ -37152,14 +36117,14 @@ var ts;
function serializeEntityNameAsExpression(node, useFallback) {
switch (node.kind) {
case 69:
- var name_30 = ts.getMutableClone(node);
- name_30.flags &= ~8;
- name_30.original = undefined;
- name_30.parent = currentScope;
+ var name_29 = ts.getMutableClone(node);
+ name_29.flags &= ~8;
+ name_29.original = undefined;
+ name_29.parent = currentScope;
if (useFallback) {
- return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_30), ts.createLiteral("undefined")), name_30);
+ return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_29), ts.createLiteral("undefined")), name_29);
}
- return name_30;
+ return name_29;
case 139:
return serializeQualifiedNameAsExpression(node, useFallback);
}
@@ -37674,7 +36639,7 @@ var ts;
}
function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) {
if (node.name) {
- var name_31 = ts.getMutableClone(node.name);
+ var name_30 = ts.getMutableClone(node.name);
emitFlags |= getNodeEmitFlags(node.name);
if (!allowSourceMaps) {
emitFlags |= 1536;
@@ -37683,9 +36648,9 @@ var ts;
emitFlags |= 49152;
}
if (emitFlags) {
- setNodeEmitFlags(name_31, emitFlags);
+ setNodeEmitFlags(name_30, emitFlags);
}
- return name_31;
+ return name_30;
}
else {
return ts.getGeneratedNameForNode(node);
@@ -37775,14 +36740,14 @@ var ts;
}
function substituteShorthandPropertyAssignment(node) {
if (enabledSubstitutions & 2) {
- var name_32 = node.name;
- var exportedName = trySubstituteNamespaceExportedName(name_32);
+ var name_31 = node.name;
+ var exportedName = trySubstituteNamespaceExportedName(name_31);
if (exportedName) {
if (node.objectAssignmentInitializer) {
var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
- return ts.createPropertyAssignment(name_32, initializer, node);
+ return ts.createPropertyAssignment(name_31, initializer, node);
}
- return ts.createPropertyAssignment(name_32, exportedName, node);
+ return ts.createPropertyAssignment(name_31, exportedName, node);
}
}
return node;
@@ -38053,12 +37018,12 @@ var ts;
return getTagName(node.openingElement);
}
else {
- var name_33 = node.tagName;
- if (ts.isIdentifier(name_33) && ts.isIntrinsicJsxName(name_33.text)) {
- return ts.createLiteral(name_33.text);
+ var name_32 = node.tagName;
+ if (ts.isIdentifier(name_32) && ts.isIntrinsicJsxName(name_32.text)) {
+ return ts.createLiteral(name_32.text);
}
else {
- return ts.createExpressionFromEntityName(name_33);
+ return ts.createExpressionFromEntityName(name_32);
}
}
}
@@ -38828,15 +37793,15 @@ var ts;
}
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
- var name_34 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
+ var name_33 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
if (dotDotDotToken) {
continue;
}
- if (ts.isBindingPattern(name_34)) {
- addDefaultValueAssignmentForBindingPattern(statements, parameter, name_34, initializer);
+ if (ts.isBindingPattern(name_33)) {
+ addDefaultValueAssignmentForBindingPattern(statements, parameter, name_33, initializer);
}
else if (initializer) {
- addDefaultValueAssignmentForInitializer(statements, parameter, name_34, initializer);
+ addDefaultValueAssignmentForInitializer(statements, parameter, name_33, initializer);
}
}
}
@@ -39401,8 +38366,8 @@ var ts;
if (!extraVariableDeclarations) {
extraVariableDeclarations = [];
}
- for (var name_35 in currentState.hoistedLocalVariables) {
- var identifier = currentState.hoistedLocalVariables[name_35];
+ for (var name_34 in currentState.hoistedLocalVariables) {
+ var identifier = currentState.hoistedLocalVariables[name_34];
extraVariableDeclarations.push(ts.createVariableDeclaration(identifier));
}
}
@@ -39818,7 +38783,7 @@ var ts;
}
function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) {
if (node.name && !ts.isGeneratedIdentifier(node.name)) {
- var name_36 = ts.getMutableClone(node.name);
+ var name_35 = ts.getMutableClone(node.name);
emitFlags |= getNodeEmitFlags(node.name);
if (!allowSourceMaps) {
emitFlags |= 1536;
@@ -39827,9 +38792,9 @@ var ts;
emitFlags |= 49152;
}
if (emitFlags) {
- setNodeEmitFlags(name_36, emitFlags);
+ setNodeEmitFlags(name_35, emitFlags);
}
- return name_36;
+ return name_35;
}
return ts.getGeneratedNameForNode(node);
}
@@ -40801,9 +39766,9 @@ var ts;
if (ts.isIdentifier(original) && original.parent) {
var declaration = resolver.getReferencedValueDeclaration(original);
if (declaration) {
- var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration)));
- if (name_37) {
- var clone_8 = ts.getMutableClone(name_37);
+ var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration)));
+ if (name_36) {
+ var clone_8 = ts.getMutableClone(name_36);
setSourceMapRange(clone_8, node);
setCommentRange(clone_8, node);
return clone_8;
@@ -41726,16 +40691,16 @@ var ts;
else {
var names = ts.reduceEachChild(node, collectExportMembers, []);
for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
- var name_38 = names_1[_i];
- addExportMemberAssignments(statements, name_38);
+ var name_37 = names_1[_i];
+ addExportMemberAssignments(statements, name_37);
}
}
}
function collectExportMembers(names, node) {
if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) {
- var name_39 = node.name;
- if (ts.isIdentifier(name_39)) {
- names.push(name_39);
+ var name_38 = node.name;
+ if (ts.isIdentifier(name_38)) {
+ names.push(name_38);
}
}
return ts.reduceEachChild(node, collectExportMembers, names);
@@ -41990,12 +40955,12 @@ var ts;
}
}
else if (ts.isImportSpecifier(declaration)) {
- var name_40 = declaration.propertyName || declaration.name;
- if (name_40.originalKeywordKind === 77 && languageVersion <= 0) {
- return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_40.text), node);
+ var name_39 = declaration.propertyName || declaration.name;
+ if (name_39.originalKeywordKind === 77 && languageVersion <= 0) {
+ return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_39.text), node);
}
else {
- return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_40), node);
+ return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_39), node);
}
}
}
@@ -42377,11 +41342,11 @@ var ts;
}
function visitFunctionDeclaration(node) {
if (ts.hasModifier(node, 1)) {
- var name_41 = node.name || ts.getGeneratedNameForNode(node);
- var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_41, undefined, node.parameters, undefined, node.body, node);
+ var name_40 = node.name || ts.getGeneratedNameForNode(node);
+ var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_40, undefined, node.parameters, undefined, node.body, node);
recordExportedFunctionDeclaration(node);
if (!ts.hasModifier(node, 512)) {
- recordExportName(name_41);
+ recordExportName(name_40);
}
ts.setOriginalNode(newNode, node);
node = newNode;
@@ -42392,13 +41357,13 @@ var ts;
function visitExpressionStatement(node) {
var originalNode = ts.getOriginalNode(node);
if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) {
- var name_42 = getDeclarationName(originalNode);
+ var name_41 = getDeclarationName(originalNode);
if (originalNode.kind === 224) {
- hoistVariableDeclaration(name_42);
+ hoistVariableDeclaration(name_41);
}
return [
node,
- createExportStatement(name_42, name_42)
+ createExportStatement(name_41, name_41)
];
}
return node;
@@ -43237,11 +42202,11 @@ var ts;
return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);
function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) {
var declarationFilePath = _a.declarationFilePath;
- emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false);
+ emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);
}
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
- function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) {
+ function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) {
var newLine = host.getNewLine();
var compilerOptions = host.getCompilerOptions();
var write;
@@ -43277,7 +42242,7 @@ var ts;
ts.forEach(sourceFile.referencedFiles, function (fileReference) {
var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference);
if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) {
- if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) {
+ if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) {
addedGlobalFileReference = true;
}
emittedReferencedFiles.push(referencedFile);
@@ -43462,7 +42427,7 @@ var ts;
}
else {
errorNameNode = declaration.name;
- resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer);
errorNameNode = undefined;
}
}
@@ -43474,7 +42439,7 @@ var ts;
}
else {
errorNameNode = signature.name;
- resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer);
errorNameNode = undefined;
}
}
@@ -43647,9 +42612,9 @@ var ts;
var count = 0;
while (true) {
count++;
- var name_43 = baseName + "_" + count;
- if (!(name_43 in currentIdentifiers)) {
- return name_43;
+ var name_42 = baseName + "_" + count;
+ if (!(name_42 in currentIdentifiers)) {
+ return name_42;
}
}
}
@@ -43667,7 +42632,7 @@ var ts;
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic;
- resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer);
write(";");
writeLine();
write(node.isExportEquals ? "export = " : "export default ");
@@ -44073,7 +43038,7 @@ var ts;
}
else {
writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError;
- resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer);
}
function getHeritageClauseVisibilityError(symbolAccessibilityResult) {
var diagnosticMessage;
@@ -44641,14 +43606,14 @@ var ts;
return emitSourceFile(node);
}
}
- function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) {
+ function writeReferencePath(referencedFile, addBundledFileReference) {
var declFileName;
var addedBundledEmitReference = false;
if (ts.isDeclarationFile(referencedFile)) {
declFileName = referencedFile.fileName;
}
else {
- ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles);
+ ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile);
}
if (declFileName) {
declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false);
@@ -44665,8 +43630,8 @@ var ts;
}
}
}
- function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) {
- var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles);
+ function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) {
+ var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit);
var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit;
if (!emitSkipped) {
var declarationOutput = emitDeclarationResult.referencesOutput
@@ -45346,7 +44311,7 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) {
+ function emitFiles(resolver, host, targetSourceFile) {
var delimiters = createDelimiterMap();
var brackets = createBracketsMap();
var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};";
@@ -45393,7 +44358,7 @@ var ts;
ts.performance.measure("transformTime", "beforeTransform");
var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode;
ts.performance.mark("beforePrint");
- ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile, emitOnlyDtsFiles);
+ ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile);
transformed.dispose();
ts.performance.measure("printTime", "beforePrint");
return {
@@ -45410,7 +44375,7 @@ var ts;
emitSkipped = true;
}
if (declarationFilePath) {
- emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped;
+ emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped;
}
if (!emitSkipped && emittedFilesList) {
emittedFilesList.push(jsFilePath);
@@ -47290,21 +46255,21 @@ var ts;
}
function makeTempVariableName(flags) {
if (flags && !(tempFlags & flags)) {
- var name_44 = flags === 268435456 ? "_i" : "_n";
- if (isUniqueName(name_44)) {
+ var name_43 = flags === 268435456 ? "_i" : "_n";
+ if (isUniqueName(name_43)) {
tempFlags |= flags;
- return name_44;
+ return name_43;
}
}
while (true) {
var count = tempFlags & 268435455;
tempFlags++;
if (count !== 8 && count !== 13) {
- var name_45 = count < 26
+ var name_44 = count < 26
? "_" + String.fromCharCode(97 + count)
: "_" + (count - 26);
- if (isUniqueName(name_45)) {
- return name_45;
+ if (isUniqueName(name_44)) {
+ return name_44;
}
}
}
@@ -47425,7 +46390,7 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- ts.version = "2.0.5";
+ ts.version = "2.1.0";
var emptyArray = [];
function findConfigFile(searchPath, fileExists, configName) {
if (configName === void 0) { configName = "tsconfig.json"; }
@@ -47480,6 +46445,581 @@ var ts;
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}
ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
+ function trace(host, message) {
+ host.trace(ts.formatMessage.apply(undefined, arguments));
+ }
+ function isTraceEnabled(compilerOptions, host) {
+ return compilerOptions.traceResolution && host.trace !== undefined;
+ }
+ function hasZeroOrOneAsteriskCharacter(str) {
+ var seenAsterisk = false;
+ for (var i = 0; i < str.length; i++) {
+ if (str.charCodeAt(i) === 42) {
+ if (!seenAsterisk) {
+ seenAsterisk = true;
+ }
+ else {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+ ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) {
+ return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
+ }
+ function moduleHasNonRelativeName(moduleName) {
+ return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
+ }
+ function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
+ var jsonContent = readJson(packageJsonPath, state.host);
+ function tryReadFromField(fieldName) {
+ if (ts.hasProperty(jsonContent, fieldName)) {
+ var typesFile = jsonContent[fieldName];
+ if (typeof typesFile === "string") {
+ var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1);
+ }
+ return typesFilePath_1;
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
+ }
+ }
+ }
+ }
+ var typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
+ if (typesFilePath) {
+ return typesFilePath;
+ }
+ if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main);
+ }
+ var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main));
+ return mainFilePath;
+ }
+ return undefined;
+ }
+ function readJson(path, host) {
+ try {
+ var jsonText = host.readFile(path);
+ return jsonText ? JSON.parse(jsonText) : {};
+ }
+ catch (e) {
+ return {};
+ }
+ }
+ var typeReferenceExtensions = [".d.ts"];
+ 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();
+ }
+ return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
+ }
+ ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
+ function getDefaultTypeRoots(currentDirectory, host) {
+ if (!host.directoryExists) {
+ return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
+ }
+ var typeRoots;
+ while (true) {
+ var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes);
+ if (host.directoryExists(atTypes)) {
+ (typeRoots || (typeRoots = [])).push(atTypes);
+ }
+ var parent_15 = ts.getDirectoryPath(currentDirectory);
+ if (parent_15 === currentDirectory) {
+ break;
+ }
+ currentDirectory = parent_15;
+ }
+ return typeRoots;
+ }
+ var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
+ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
+ var traceEnabled = isTraceEnabled(options, host);
+ var moduleResolutionState = {
+ compilerOptions: options,
+ host: host,
+ skipTsx: true,
+ 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 = [];
+ if (typeRoots && typeRoots.length) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
+ }
+ var primarySearchPaths = typeRoots;
+ for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) {
+ var typeRoot = primarySearchPaths_1[_i];
+ var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
+ var candidateDirectory = ts.getDirectoryPath(candidate);
+ var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState);
+ if (resolvedFile_1) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true);
+ }
+ return {
+ resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 },
+ failedLookupLocations: failedLookupLocations
+ };
+ }
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
+ }
+ }
+ var resolvedFile;
+ var initialLocationForSecondaryLookup;
+ if (containingFile) {
+ initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile);
+ }
+ if (initialLocationForSecondaryLookup !== undefined) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
+ }
+ resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState);
+ if (traceEnabled) {
+ if (resolvedFile) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
+ }
+ else {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
+ }
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
+ }
+ }
+ return {
+ resolvedTypeReferenceDirective: resolvedFile
+ ? { primary: false, resolvedFileName: resolvedFile }
+ : undefined,
+ failedLookupLocations: failedLookupLocations
+ };
+ }
+ ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
+ function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
+ }
+ 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]);
+ }
+ }
+ var result;
+ switch (moduleResolution) {
+ case ts.ModuleResolutionKind.NodeJs:
+ result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
+ break;
+ case ts.ModuleResolutionKind.Classic:
+ result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
+ break;
+ }
+ 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;
+ }
+ ts.resolveModuleName = resolveModuleName;
+ function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
+ if (moduleHasNonRelativeName(moduleName)) {
+ return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
+ }
+ else {
+ return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
+ }
+ }
+ function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
+ if (!state.compilerOptions.rootDirs) {
+ return undefined;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
+ }
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ var matchedRootDir;
+ var matchedNormalizedPrefix;
+ for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
+ var rootDir = _a[_i];
+ var normalizedRoot = ts.normalizePath(rootDir);
+ if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
+ normalizedRoot += ts.directorySeparator;
+ }
+ var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
+ (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
+ }
+ if (isLongestMatchingPrefix) {
+ matchedNormalizedPrefix = normalizedRoot;
+ matchedRootDir = rootDir;
+ }
+ }
+ if (matchedNormalizedPrefix) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
+ }
+ var suffix = candidate.substr(matchedNormalizedPrefix.length);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
+ }
+ var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
+ if (resolvedFileName) {
+ return resolvedFileName;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
+ }
+ for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
+ var rootDir = _c[_b];
+ if (rootDir === matchedRootDir) {
+ continue;
+ }
+ var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
+ }
+ var baseDirectory = ts.getDirectoryPath(candidate_1);
+ var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
+ if (resolvedFileName_1) {
+ return resolvedFileName_1;
+ }
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
+ }
+ }
+ return undefined;
+ }
+ function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) {
+ if (!state.compilerOptions.baseUrl) {
+ return undefined;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
+ }
+ var matchedPattern = undefined;
+ if (state.compilerOptions.paths) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
+ }
+ matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
+ }
+ if (matchedPattern) {
+ var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
+ var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
+ }
+ for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) {
+ var subst = _a[_i];
+ var path = matchedStar ? subst.replace("*", matchedStar) : subst;
+ var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
+ }
+ var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ if (resolvedFileName) {
+ return resolvedFileName;
+ }
+ }
+ return undefined;
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
+ }
+ return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ }
+ }
+ 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) {
+ return patternString;
+ }
+ }
+ return findBestPatternMatch(patterns, function (_) { return _; }, candidate);
+ }
+ function patternText(_a) {
+ var prefix = _a.prefix, suffix = _a.suffix;
+ return prefix + "*" + suffix;
+ }
+ function matchedText(pattern, candidate) {
+ ts.Debug.assert(isPatternMatch(pattern, candidate));
+ return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
+ }
+ function findBestPatternMatch(values, getPattern, candidate) {
+ var matchedValue = undefined;
+ 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;
+ }
+ ts.findBestPatternMatch = findBestPatternMatch;
+ function isPatternMatch(_a, candidate) {
+ var prefix = _a.prefix, suffix = _a.suffix;
+ return candidate.length >= prefix.length + suffix.length &&
+ ts.startsWith(candidate, prefix) &&
+ ts.endsWith(candidate, suffix);
+ }
+ function tryParsePattern(pattern) {
+ ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
+ var indexOfStar = pattern.indexOf("*");
+ return indexOfStar === -1 ? undefined : {
+ prefix: pattern.substr(0, indexOfStar),
+ suffix: pattern.substr(indexOfStar + 1)
+ };
+ }
+ ts.tryParsePattern = tryParsePattern;
+ function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var failedLookupLocations = [];
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false };
+ var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state);
+ var isExternalLibraryImport = false;
+ if (!resolvedFileName) {
+ if (moduleHasNonRelativeName(moduleName)) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
+ }
+ resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state);
+ isExternalLibraryImport = resolvedFileName !== undefined;
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state);
+ }
+ }
+ if (resolvedFileName && host.realpath) {
+ var originalFileName = resolvedFileName;
+ resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName));
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName);
+ }
+ }
+ return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
+ }
+ ts.nodeModuleNameResolver = nodeModuleNameResolver;
+ function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
+ }
+ var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
+ return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
+ }
+ function directoryProbablyExists(directoryName, host) {
+ return !host.directoryExists || host.directoryExists(directoryName);
+ }
+ ts.directoryProbablyExists = directoryProbablyExists;
+ function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
+ var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
+ if (resolvedByAddingExtension) {
+ return resolvedByAddingExtension;
+ }
+ if (ts.hasJavaScriptFileExtension(candidate)) {
+ var extensionless = ts.removeFileExtension(candidate);
+ if (state.traceEnabled) {
+ var extension = candidate.substring(extensionless.length);
+ trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
+ }
+ return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
+ }
+ }
+ function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
+ if (!onlyRecordFailures) {
+ var directory = ts.getDirectoryPath(candidate);
+ if (directory) {
+ onlyRecordFailures = !directoryProbablyExists(directory, state.host);
+ }
+ }
+ return ts.forEach(extensions, function (ext) {
+ return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state);
+ });
+ }
+ function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) {
+ if (!onlyRecordFailures && state.host.fileExists(fileName)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
+ }
+ return fileName;
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
+ }
+ failedLookupLocation.push(fileName);
+ return undefined;
+ }
+ }
+ function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) {
+ var packageJsonPath = pathToPackageJson(candidate);
+ var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
+ if (directoryExists && state.host.fileExists(packageJsonPath)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
+ }
+ var typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
+ if (typesFile) {
+ var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host);
+ var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) ||
+ tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state);
+ if (result) {
+ return result;
+ }
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field);
+ }
+ }
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
+ }
+ failedLookupLocation.push(packageJsonPath);
+ }
+ return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
+ }
+ function pathToPackageJson(directory) {
+ return ts.combinePaths(directory, "package.json");
+ }
+ function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) {
+ var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
+ var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
+ var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
+ var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions);
+ var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
+ if (result) {
+ return result;
+ }
+ result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
+ if (result) {
+ return result;
+ }
+ }
+ function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) {
+ directory = ts.normalizeSlashes(directory);
+ while (true) {
+ var baseName = ts.getBaseFileName(directory);
+ if (baseName !== "node_modules") {
+ var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
+ if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
+ return packageResult;
+ }
+ else {
+ var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
+ if (typesResult || packageResult) {
+ return typesResult || packageResult;
+ }
+ }
+ }
+ var parentPath = ts.getDirectoryPath(directory);
+ if (parentPath === directory) {
+ break;
+ }
+ directory = parentPath;
+ }
+ return undefined;
+ }
+ function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
+ var failedLookupLocations = [];
+ var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
+ if (resolvedFileName) {
+ return createResolvedModule(resolvedFileName, false, failedLookupLocations);
+ }
+ var referencedSourceFile;
+ if (moduleHasNonRelativeName(moduleName)) {
+ while (true) {
+ var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state);
+ if (referencedSourceFile) {
+ break;
+ }
+ var parentPath = ts.getDirectoryPath(containingDirectory);
+ if (parentPath === containingDirectory) {
+ break;
+ }
+ containingDirectory = parentPath;
+ }
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state);
+ }
+ return referencedSourceFile
+ ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations }
+ : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
+ }
+ ts.classicNameResolver = classicNameResolver;
function createCompilerHost(options, setParentNodes) {
var existingDirectories = ts.createMap();
function getCanonicalFileName(fileName) {
@@ -47641,14 +47181,41 @@ var ts;
var resolutions = [];
var cache = ts.createMap();
for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
- var name_46 = names_2[_i];
- var result = name_46 in cache
- ? cache[name_46]
- : cache[name_46] = loader(name_46, containingFile);
+ var name_45 = names_2[_i];
+ var result = name_45 in cache
+ ? cache[name_45]
+ : cache[name_45] = loader(name_45, containingFile);
resolutions.push(result);
}
return resolutions;
}
+ function getAutomaticTypeDirectiveNames(options, host) {
+ if (options.types) {
+ return options.types;
+ }
+ 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));
+ var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
+ if (!isNotNeededPackage) {
+ result.push(ts.getBaseFileName(normalized));
+ }
+ }
+ }
+ }
+ }
+ }
+ return result;
+ }
+ ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
function createProgram(rootNames, options, host, oldProgram) {
var program;
var files = [];
@@ -47674,7 +47241,7 @@ var ts;
resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); };
}
else {
- var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; };
+ var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; };
resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); };
}
var resolveTypeReferenceDirectiveNamesWorker;
@@ -47682,14 +47249,14 @@ var ts;
resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); };
}
else {
- var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; };
+ var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; };
resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); };
}
var filesByName = ts.createFileMap();
var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined;
if (!tryReuseStructureFromOldProgram()) {
ts.forEach(rootNames, function (name) { return processRootFile(name, false); });
- var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host);
+ var typeReferences = getAutomaticTypeDirectiveNames(options, host);
if (typeReferences) {
var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts");
var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
@@ -47732,8 +47299,7 @@ var ts;
getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
- getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
- dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker
+ getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -47880,19 +47446,16 @@ var ts;
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true));
}
- function dropDiagnosticsProducingTypeChecker() {
- diagnosticsProducingTypeChecker = undefined;
- }
function getTypeChecker() {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
- function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
- return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); });
+ function emit(sourceFile, writeFileCallback, cancellationToken) {
+ return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
}
- function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
+ function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) {
var declarationDiagnostics = [];
if (options.noEmit) {
return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
@@ -47913,7 +47476,7 @@ var ts;
}
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
ts.performance.mark("beforeEmit");
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -48510,7 +48073,7 @@ var ts;
if (!ts.hasProperty(options.paths, key)) {
continue;
}
- if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
+ if (!hasZeroOrOneAsteriskCharacter(key)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key));
}
if (ts.isArray(options.paths[key])) {
@@ -48521,7 +48084,7 @@ var ts;
var subst = _a[_i];
var typeOfSubst = typeof subst;
if (typeOfSubst === "string") {
- if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
+ if (!hasZeroOrOneAsteriskCharacter(subst)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key));
}
}
@@ -49918,7 +49481,7 @@ var ts;
return ts.ensureScriptKind(fileName, scriptKind);
}
ts.getScriptKind = getScriptKind;
- function sanitizeConfigFile(configFileName, content) {
+ function parseAndReEmitConfigJSONFile(content) {
var options = {
fileName: "config.js",
compilerOptions: {
@@ -49929,17 +49492,14 @@ var ts;
};
var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics;
var trimmedOutput = outputText.trim();
+ var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2));
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), false), config = _b.config, error = _b.error;
- return {
- configJsonObject: config || {},
- diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics
- };
+ return { configJsonObject: configJsonObject, diagnostics: diagnostics };
}
- ts.sanitizeConfigFile = sanitizeConfigFile;
+ ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -51217,13 +50777,13 @@ var ts;
function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) {
var entries = [];
var nameTable = ts.getNameTable(sourceFile);
- for (var name_47 in nameTable) {
- if (nameTable[name_47] === position) {
+ for (var name_46 in nameTable) {
+ if (nameTable[name_46] === position) {
continue;
}
- if (!uniqueNames[name_47]) {
- uniqueNames[name_47] = name_47;
- var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_47), compilerOptions.target, true);
+ if (!uniqueNames[name_46]) {
+ uniqueNames[name_46] = name_46;
+ var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, true);
if (displayName) {
var entry = {
name: displayName,
@@ -52282,8 +51842,8 @@ var ts;
if (element.getStart() <= position && position <= element.getEnd()) {
continue;
}
- var name_48 = element.propertyName || element.name;
- existingImportsOrExports[name_48.text] = true;
+ var name_47 = element.propertyName || element.name;
+ existingImportsOrExports[name_47.text] = true;
}
if (!ts.someProperties(existingImportsOrExports)) {
return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; });
@@ -54404,18 +53964,155 @@ var ts;
})(JsDoc = ts.JsDoc || (ts.JsDoc = {}));
})(ts || (ts = {}));
var ts;
+(function (ts) {
+ var JsTyping;
+ (function (JsTyping) {
+ ;
+ ;
+ var safeList;
+ function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) {
+ var inferredTypings = ts.createMap();
+ if (!typingOptions || !typingOptions.enableAutoDiscovery) {
+ return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
+ }
+ fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, undefined, 1, 2); });
+ if (!safeList) {
+ var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
+ safeList = ts.createMap(result.config);
+ }
+ var filesToWatch = [];
+ var searchDirs = [];
+ var exclude = [];
+ mergeTypings(typingOptions.include);
+ exclude = typingOptions.exclude || [];
+ var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath);
+ if (projectRootPath !== undefined) {
+ 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);
+ for (var name_48 in packageNameToTypingLocation) {
+ if (name_48 in inferredTypings && !inferredTypings[name_48]) {
+ inferredTypings[name_48] = packageNameToTypingLocation[name_48];
+ }
+ }
+ for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) {
+ var excludeTypingName = exclude_1[_a];
+ delete inferredTypings[excludeTypingName];
+ }
+ var newTypingNames = [];
+ var cachedTypingPaths = [];
+ for (var typing in inferredTypings) {
+ if (inferredTypings[typing] !== undefined) {
+ cachedTypingPaths.push(inferredTypings[typing]);
+ }
+ else {
+ newTypingNames.push(typing);
+ }
+ }
+ return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
+ function mergeTypings(typingNames) {
+ if (!typingNames) {
+ return;
+ }
+ for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) {
+ var typing = typingNames_1[_i];
+ if (!(typing in inferredTypings)) {
+ inferredTypings[typing] = undefined;
+ }
+ }
+ }
+ function getTypingNamesFromJson(jsonPath, filesToWatch) {
+ var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); });
+ if (result.config) {
+ var jsonConfig = result.config;
+ filesToWatch.push(jsonPath);
+ if (jsonConfig.dependencies) {
+ mergeTypings(ts.getOwnKeys(jsonConfig.dependencies));
+ }
+ if (jsonConfig.devDependencies) {
+ mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies));
+ }
+ if (jsonConfig.optionalDependencies) {
+ mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies));
+ }
+ if (jsonConfig.peerDependencies) {
+ mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies));
+ }
+ }
+ }
+ function getTypingNamesFromSourceFileNames(fileNames) {
+ var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension);
+ var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); });
+ var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); });
+ if (safeList === undefined) {
+ mergeTypings(cleanedTypingNames);
+ }
+ else {
+ mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; }));
+ }
+ var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, undefined, 2); });
+ if (hasJsxFile) {
+ mergeTypings(["react"]);
+ }
+ }
+ function getTypingNamesFromNodeModuleFolder(nodeModulesPath) {
+ if (!host.directoryExists(nodeModulesPath)) {
+ return;
+ }
+ var typingNames = [];
+ var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2);
+ for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
+ var fileName = fileNames_2[_i];
+ var normalizedFileName = ts.normalizePath(fileName);
+ if (ts.getBaseFileName(normalizedFileName) !== "package.json") {
+ continue;
+ }
+ var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ if (!result.config) {
+ continue;
+ }
+ var packageJson = result.config;
+ if (packageJson._requiredBy &&
+ ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
+ continue;
+ }
+ if (!packageJson.name) {
+ continue;
+ }
+ if (packageJson.typings) {
+ var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName));
+ inferredTypings[packageJson.name] = absolutePath;
+ }
+ else {
+ typingNames.push(packageJson.name);
+ }
+ }
+ mergeTypings(typingNames);
+ }
+ }
+ JsTyping.discoverTypings = discoverTypings;
+ })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
+})(ts || (ts = {}));
+var ts;
(function (ts) {
var NavigateTo;
(function (NavigateTo) {
- function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) {
+ function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) {
var patternMatcher = ts.createPatternMatcher(searchValue);
var rawItems = [];
var baseSensitivity = { sensitivity: "base" };
ts.forEach(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) {
- return;
- }
var nameToDeclarations = sourceFile.getNamedDeclarations();
for (var name_49 in nameToDeclarations) {
var declarations = nameToDeclarations[name_49];
@@ -57992,25 +57689,25 @@ var ts;
};
RulesProvider.prototype.createActiveRules = function (options) {
var rules = this.globalRules.HighPriorityCommonRules.slice(0);
- if (options.insertSpaceAfterCommaDelimiter) {
+ if (options.InsertSpaceAfterCommaDelimiter) {
rules.push(this.globalRules.SpaceAfterComma);
}
else {
rules.push(this.globalRules.NoSpaceAfterComma);
}
- if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) {
+ if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) {
rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword);
}
else {
rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword);
}
- if (options.insertSpaceAfterKeywordsInControlFlowStatements) {
+ if (options.InsertSpaceAfterKeywordsInControlFlowStatements) {
rules.push(this.globalRules.SpaceAfterKeywordInControl);
}
else {
rules.push(this.globalRules.NoSpaceAfterKeywordInControl);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) {
rules.push(this.globalRules.SpaceAfterOpenParen);
rules.push(this.globalRules.SpaceBeforeCloseParen);
rules.push(this.globalRules.NoSpaceBetweenParens);
@@ -58020,7 +57717,7 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeCloseParen);
rules.push(this.globalRules.NoSpaceBetweenParens);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) {
rules.push(this.globalRules.SpaceAfterOpenBracket);
rules.push(this.globalRules.SpaceBeforeCloseBracket);
rules.push(this.globalRules.NoSpaceBetweenBrackets);
@@ -58030,7 +57727,7 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeCloseBracket);
rules.push(this.globalRules.NoSpaceBetweenBrackets);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) {
rules.push(this.globalRules.SpaceAfterOpenBrace);
rules.push(this.globalRules.SpaceBeforeCloseBrace);
rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets);
@@ -58040,7 +57737,7 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeCloseBrace);
rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) {
rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail);
}
@@ -58048,7 +57745,7 @@ var ts;
rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) {
rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression);
rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression);
}
@@ -58056,13 +57753,13 @@ var ts;
rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression);
rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression);
}
- if (options.insertSpaceAfterSemicolonInForStatements) {
+ if (options.InsertSpaceAfterSemicolonInForStatements) {
rules.push(this.globalRules.SpaceAfterSemicolonInFor);
}
else {
rules.push(this.globalRules.NoSpaceAfterSemicolonInFor);
}
- if (options.insertSpaceBeforeAndAfterBinaryOperators) {
+ if (options.InsertSpaceBeforeAndAfterBinaryOperators) {
rules.push(this.globalRules.SpaceBeforeBinaryOperator);
rules.push(this.globalRules.SpaceAfterBinaryOperator);
}
@@ -58070,14 +57767,14 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeBinaryOperator);
rules.push(this.globalRules.NoSpaceAfterBinaryOperator);
}
- if (options.placeOpenBraceOnNewLineForControlBlocks) {
+ if (options.PlaceOpenBraceOnNewLineForControlBlocks) {
rules.push(this.globalRules.NewLineBeforeOpenBraceInControl);
}
- if (options.placeOpenBraceOnNewLineForFunctions) {
+ if (options.PlaceOpenBraceOnNewLineForFunctions) {
rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction);
rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock);
}
- if (options.insertSpaceAfterTypeAssertion) {
+ if (options.InsertSpaceAfterTypeAssertion) {
rules.push(this.globalRules.SpaceAfterTypeAssertion);
}
else {
@@ -58248,7 +57945,7 @@ var ts;
break;
}
if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) {
- return options.indentSize;
+ return options.IndentSize;
}
previousLine = line;
child = n;
@@ -58308,12 +58005,12 @@ var ts;
}
function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) {
var indentation = inheritedIndentation;
- var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0;
+ var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0;
if (effectiveParentStartLine === startLine) {
indentation = startLine === lastIndentedLine
? indentationOnLastIndentedLine
: parentDynamicIndentation.getIndentation();
- delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta);
+ delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta);
}
else if (indentation === -1) {
if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
@@ -58385,13 +58082,13 @@ var ts;
recomputeIndentation: function (lineAdded) {
if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) {
if (lineAdded) {
- indentation += options.indentSize;
+ indentation += options.IndentSize;
}
else {
- indentation -= options.indentSize;
+ indentation -= options.IndentSize;
}
if (formatting.SmartIndenter.shouldIndentChildNode(node)) {
- delta = options.indentSize;
+ delta = options.IndentSize;
}
else {
delta = 0;
@@ -58751,7 +58448,7 @@ var ts;
}
var lineDelta = currentStartLine - previousStartLine;
if (lineDelta !== 1) {
- recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter);
+ recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter);
}
break;
case 2:
@@ -58810,14 +58507,14 @@ var ts;
var internedTabsIndentation;
var internedSpacesIndentation;
function getIndentationString(indentation, options) {
- var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize);
+ var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize);
if (resetInternedStrings) {
- internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize };
+ 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;
+ if (!options.ConvertTabsToSpaces) {
+ var tabs = Math.floor(indentation / options.TabSize);
+ var spaces = indentation - tabs * options.TabSize;
var tabString = void 0;
if (!internedTabsIndentation) {
internedTabsIndentation = [];
@@ -58832,13 +58529,13 @@ var ts;
}
else {
var spacesString = void 0;
- var quotient = Math.floor(indentation / options.indentSize);
- var remainder = indentation % options.indentSize;
+ var quotient = Math.floor(indentation / options.IndentSize);
+ var remainder = indentation % options.IndentSize;
if (!internedSpacesIndentation) {
internedSpacesIndentation = [];
}
if (internedSpacesIndentation[quotient] === undefined) {
- spacesString = repeat(" ", options.indentSize * quotient);
+ spacesString = repeat(" ", options.IndentSize * quotient);
internedSpacesIndentation[quotient] = spacesString;
}
else {
@@ -58867,7 +58564,7 @@ var ts;
if (position > sourceFile.text.length) {
return getBaseIndentation(options);
}
- if (options.indentStyle === ts.IndentStyle.None) {
+ if (options.IndentStyle === ts.IndentStyle.None) {
return 0;
}
var precedingToken = ts.findPrecedingToken(position, sourceFile);
@@ -58879,7 +58576,7 @@ var ts;
return 0;
}
var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
- if (options.indentStyle === ts.IndentStyle.Block) {
+ if (options.IndentStyle === ts.IndentStyle.Block) {
var current_1 = position;
while (current_1 > 0) {
var char = sourceFile.text.charCodeAt(current_1);
@@ -58908,7 +58605,7 @@ var ts;
indentationDelta = 0;
}
else {
- indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0;
+ indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0;
}
break;
}
@@ -58918,7 +58615,7 @@ var ts;
}
actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options);
if (actualIndentation !== -1) {
- return actualIndentation + options.indentSize;
+ return actualIndentation + options.IndentSize;
}
previous = current;
current = current.parent;
@@ -58929,15 +58626,15 @@ var ts;
return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options);
}
SmartIndenter.getIndentation = getIndentation;
+ function getBaseIndentation(options) {
+ return options.BaseIndentSize || 0;
+ }
+ SmartIndenter.getBaseIndentation = getBaseIndentation;
function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) {
var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options);
}
SmartIndenter.getIndentationForNode = getIndentationForNode;
- function getBaseIndentation(options) {
- return options.baseIndentSize || 0;
- }
- SmartIndenter.getBaseIndentation = getBaseIndentation;
function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) {
var parent = current.parent;
var parentStart;
@@ -58967,7 +58664,7 @@ var ts;
}
}
if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) {
- indentationDelta += options.indentSize;
+ indentationDelta += options.IndentSize;
}
current = parent;
currentStart = parentStart;
@@ -59145,7 +58842,7 @@ var ts;
break;
}
if (ch === 9) {
- column += options.tabSize + (column % options.tabSize);
+ column += options.TabSize + (column % options.TabSize);
}
else {
column++;
@@ -59709,30 +59406,6 @@ var ts;
getSignatureConstructor: function () { return SignatureObject; }
};
}
- 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;
- }
- ts.toEditorSettings = toEditorSettings;
- function isCamelCase(s) {
- return !s.length || s.charAt(0) === s.charAt(0).toLowerCase();
- }
function displayPartsToString(displayParts) {
if (displayParts) {
return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join("");
@@ -60205,12 +59878,12 @@ var ts;
synchronizeHostData();
return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments);
}
- function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) {
+ function getNavigateToItems(searchValue, maxResultCount, fileName) {
synchronizeHostData();
var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles();
- return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles);
+ return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount);
}
- function getEmitOutput(fileName, emitOnlyDtsFiles) {
+ function getEmitOutput(fileName) {
synchronizeHostData();
var sourceFile = getValidSourceFile(fileName);
var outputFiles = [];
@@ -60221,7 +59894,7 @@ var ts;
text: data
});
}
- var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles);
+ var emitOutput = program.emit(sourceFile, writeFile, cancellationToken);
return {
outputFiles: outputFiles,
emitSkipped: emitOutput.emitSkipped
@@ -60347,35 +60020,31 @@ var ts;
}
function getIndentationAtPosition(fileName, position, editorOptions) {
var start = ts.timestamp();
- var settings = toEditorSettings(editorOptions);
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start));
start = ts.timestamp();
- var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings);
+ var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions);
log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start));
return result;
}
function getFormattingEditsForRange(fileName, start, end, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
- return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options);
}
function getFormattingEditsForDocument(fileName, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
- return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options);
}
function getFormattingEditsAfterKeystroke(fileName, position, key, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
if (key === "}") {
- return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options);
}
else if (key === ";") {
- return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options);
}
else if (key === "\n") {
- return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options);
}
return [];
}
@@ -60564,2279 +60233,43 @@ var ts;
(function (ts) {
var server;
(function (server) {
- var ScriptInfo = (function () {
- function ScriptInfo(host, fileName, content, scriptKind, isOpen, hasMixedContent) {
- if (isOpen === void 0) { isOpen = false; }
- if (hasMixedContent === void 0) { hasMixedContent = false; }
- this.host = host;
- this.fileName = fileName;
- this.scriptKind = scriptKind;
- this.isOpen = isOpen;
- this.hasMixedContent = hasMixedContent;
- this.containingProjects = [];
- this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
- this.svc = server.ScriptVersionCache.fromString(host, content);
- this.scriptKind = scriptKind
- ? scriptKind
- : ts.getScriptKindFromFileName(fileName);
- }
- ScriptInfo.prototype.getFormatCodeSettings = function () {
- return this.formatCodeSettings;
- };
- ScriptInfo.prototype.attachToProject = function (project) {
- var isNew = !this.isAttached(project);
- if (isNew) {
- this.containingProjects.push(project);
- }
- return isNew;
- };
- ScriptInfo.prototype.isAttached = function (project) {
- switch (this.containingProjects.length) {
- case 0: return false;
- case 1: return this.containingProjects[0] === project;
- case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project;
- default: return ts.contains(this.containingProjects, project);
- }
- };
- ScriptInfo.prototype.detachFromProject = function (project) {
- switch (this.containingProjects.length) {
- case 0:
- return;
- case 1:
- if (this.containingProjects[0] === project) {
- this.containingProjects.pop();
- }
- break;
- case 2:
- if (this.containingProjects[0] === project) {
- this.containingProjects[0] = this.containingProjects.pop();
- }
- else if (this.containingProjects[1] === project) {
- this.containingProjects.pop();
- }
- break;
- default:
- server.removeItemFromSet(this.containingProjects, project);
- break;
- }
- };
- ScriptInfo.prototype.detachAllProjects = function () {
- for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) {
- var p = _a[_i];
- p.removeFile(this, false);
- }
- this.containingProjects.length = 0;
- };
- ScriptInfo.prototype.getDefaultProject = function () {
- if (this.containingProjects.length === 0) {
- return server.Errors.ThrowNoProject();
- }
- ts.Debug.assert(this.containingProjects.length !== 0);
- return this.containingProjects[0];
- };
- ScriptInfo.prototype.setFormatOptions = function (formatSettings) {
- if (formatSettings) {
- if (!this.formatCodeSettings) {
- this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host);
- }
- server.mergeMaps(this.formatCodeSettings, formatSettings);
- }
- };
- ScriptInfo.prototype.setWatcher = function (watcher) {
- this.stopWatcher();
- this.fileWatcher = watcher;
- };
- ScriptInfo.prototype.stopWatcher = function () {
- if (this.fileWatcher) {
- this.fileWatcher.close();
- this.fileWatcher = undefined;
- }
- };
- ScriptInfo.prototype.getLatestVersion = function () {
- return this.svc.latestVersion().toString();
- };
- ScriptInfo.prototype.reload = function (script) {
- this.svc.reload(script);
- this.markContainingProjectsAsDirty();
- };
- ScriptInfo.prototype.saveTo = function (fileName) {
- var snap = this.snap();
- this.host.writeFile(fileName, snap.getText(0, snap.getLength()));
- };
- ScriptInfo.prototype.reloadFromFile = function () {
- if (this.hasMixedContent) {
- this.reload("");
- }
- else {
- this.svc.reloadFromFile(this.fileName);
- this.markContainingProjectsAsDirty();
- }
- };
- ScriptInfo.prototype.snap = function () {
- return this.svc.getSnapshot();
- };
- ScriptInfo.prototype.getLineInfo = function (line) {
- var snap = this.snap();
- return snap.index.lineNumberToInfo(line);
- };
- ScriptInfo.prototype.editContent = function (start, end, newText) {
- this.svc.edit(start, end - start, newText);
- this.markContainingProjectsAsDirty();
- };
- ScriptInfo.prototype.markContainingProjectsAsDirty = function () {
- for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) {
- var p = _a[_i];
- p.markAsDirty();
- }
- };
- ScriptInfo.prototype.lineToTextSpan = function (line) {
- var index = this.snap().index;
- var lineInfo = index.lineNumberToInfo(line + 1);
- var len;
- if (lineInfo.leaf) {
- len = lineInfo.leaf.text.length;
- }
- else {
- var nextLineInfo = index.lineNumberToInfo(line + 2);
- len = nextLineInfo.offset - lineInfo.offset;
- }
- return ts.createTextSpan(lineInfo.offset, len);
- };
- ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) {
- var index = this.snap().index;
- var lineInfo = index.lineNumberToInfo(line);
- return (lineInfo.offset + offset - 1);
- };
- ScriptInfo.prototype.positionToLineOffset = function (position) {
- var index = this.snap().index;
- var lineOffset = index.charOffsetToLineNumberAndPos(position);
- return { line: lineOffset.line, offset: lineOffset.offset + 1 };
- };
- return ScriptInfo;
- }());
- server.ScriptInfo = ScriptInfo;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- var LSHost = (function () {
- function LSHost(host, project, cancellationToken) {
- var _this = this;
- this.host = host;
- this.project = project;
- this.cancellationToken = cancellationToken;
- this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames);
- this.resolvedModuleNames = ts.createFileMap();
- this.resolvedTypeReferenceDirectives = ts.createFileMap();
- if (host.trace) {
- this.trace = function (s) { return host.trace(s); };
- }
- this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) {
- var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host);
- if (primaryResult.resolvedModule) {
- if (ts.fileExtensionIsAny(primaryResult.resolvedModule.resolvedFileName, ts.supportedTypeScriptExtensions)) {
- return primaryResult;
- }
- }
- var secondaryLookupFailedLookupLocations = [];
- var globalCache = _this.project.projectService.typingsInstaller.globalTypingsCacheLocation;
- if (_this.project.getTypingOptions().enableAutoDiscovery && globalCache) {
- var traceEnabled = ts.isTraceEnabled(compilerOptions, host);
- if (traceEnabled) {
- ts.trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, _this.project.getProjectName(), moduleName, globalCache);
- }
- var state = { compilerOptions: compilerOptions, host: host, skipTsx: false, traceEnabled: traceEnabled };
- var resolvedName = ts.loadModuleFromNodeModules(moduleName, globalCache, secondaryLookupFailedLookupLocations, state, true);
- if (resolvedName) {
- return ts.createResolvedModule(resolvedName, true, primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations));
- }
- }
- if (!primaryResult.resolvedModule && secondaryLookupFailedLookupLocations.length) {
- primaryResult.failedLookupLocations = primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations);
- }
- return primaryResult;
- };
- }
- LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) {
- var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName);
- var currentResolutionsInFile = cache.get(path);
- var newResolutions = ts.createMap();
- var resolvedModules = [];
- var compilerOptions = this.getCompilationSettings();
- for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
- var name_52 = names_3[_i];
- var resolution = newResolutions[name_52];
- if (!resolution) {
- var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_52];
- if (moduleResolutionIsValid(existingResolution)) {
- resolution = existingResolution;
- }
- else {
- newResolutions[name_52] = resolution = loader(name_52, containingFile, compilerOptions, this);
- }
- }
- ts.Debug.assert(resolution !== undefined);
- resolvedModules.push(getResult(resolution));
- }
- cache.set(path, newResolutions);
- return resolvedModules;
- function moduleResolutionIsValid(resolution) {
- if (!resolution) {
- return false;
- }
- if (getResult(resolution)) {
- return true;
- }
- return resolution.failedLookupLocations.length === 0;
- }
- };
- LSHost.prototype.getProjectVersion = function () {
- return this.project.getProjectVersion();
- };
- LSHost.prototype.getCompilationSettings = function () {
- return this.compilationSettings;
- };
- LSHost.prototype.useCaseSensitiveFileNames = function () {
- return this.host.useCaseSensitiveFileNames;
- };
- LSHost.prototype.getCancellationToken = function () {
- return this.cancellationToken;
- };
- LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
- return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; });
- };
- LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) {
- return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; });
- };
- LSHost.prototype.getDefaultLibFileName = function () {
- var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath()));
- return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings));
- };
- LSHost.prototype.getScriptSnapshot = function (filename) {
- var scriptInfo = this.project.getScriptInfoLSHost(filename);
- if (scriptInfo) {
- return scriptInfo.snap();
- }
- };
- LSHost.prototype.getScriptFileNames = function () {
- return this.project.getRootFilesLSHost();
- };
- LSHost.prototype.getTypeRootsVersion = function () {
- return this.project.typesVersion;
- };
- LSHost.prototype.getScriptKind = function (fileName) {
- var info = this.project.getScriptInfoLSHost(fileName);
- return info && info.scriptKind;
- };
- LSHost.prototype.getScriptVersion = function (filename) {
- var info = this.project.getScriptInfoLSHost(filename);
- return info && info.getLatestVersion();
- };
- LSHost.prototype.getCurrentDirectory = function () {
- return this.host.getCurrentDirectory();
- };
- LSHost.prototype.resolvePath = function (path) {
- return this.host.resolvePath(path);
- };
- LSHost.prototype.fileExists = function (path) {
- return this.host.fileExists(path);
- };
- LSHost.prototype.directoryExists = function (path) {
- return this.host.directoryExists(path);
- };
- LSHost.prototype.readFile = function (fileName) {
- return this.host.readFile(fileName);
- };
- LSHost.prototype.getDirectories = function (path) {
- return this.host.getDirectories(path);
- };
- LSHost.prototype.notifyFileRemoved = function (info) {
- this.resolvedModuleNames.remove(info.path);
- this.resolvedTypeReferenceDirectives.remove(info.path);
- };
- LSHost.prototype.setCompilationSettings = function (opt) {
- this.compilationSettings = opt;
- this.resolvedModuleNames.clear();
- this.resolvedTypeReferenceDirectives.clear();
- };
- return LSHost;
- }());
- server.LSHost = LSHost;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- server.nullTypingsInstaller = {
- enqueueInstallTypingsRequest: function () { },
- attach: function (projectService) { },
- onProjectClosed: function (p) { },
- globalTypingsCacheLocation: undefined
- };
- var TypingsCacheEntry = (function () {
- function TypingsCacheEntry() {
- }
- return TypingsCacheEntry;
- }());
- function setIsEqualTo(arr1, arr2) {
- if (arr1 === arr2) {
- return true;
- }
- if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) {
- return true;
- }
- var set = ts.createMap();
- var unique = 0;
- for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) {
- var v = arr1_1[_i];
- if (set[v] !== true) {
- set[v] = true;
- unique++;
- }
- }
- for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) {
- var v = arr2_1[_a];
- if (!ts.hasProperty(set, v)) {
- return false;
- }
- if (set[v] === true) {
- set[v] = false;
- unique--;
- }
- }
- return unique === 0;
- }
- function typingOptionsChanged(opt1, opt2) {
- return opt1.enableAutoDiscovery !== opt2.enableAutoDiscovery ||
- !setIsEqualTo(opt1.include, opt2.include) ||
- !setIsEqualTo(opt1.exclude, opt2.exclude);
- }
- function compilerOptionsChanged(opt1, opt2) {
- return opt1.allowJs != opt2.allowJs;
- }
- function toTypingsArray(arr) {
- arr.sort();
- return arr;
- }
- var TypingsCache = (function () {
- function TypingsCache(installer) {
- this.installer = installer;
- this.perProjectCache = ts.createMap();
- }
- TypingsCache.prototype.getTypingsForProject = function (project, forceRefresh) {
- var typingOptions = project.getTypingOptions();
- if (!typingOptions || !typingOptions.enableAutoDiscovery) {
- return server.emptyArray;
- }
- var entry = this.perProjectCache[project.getProjectName()];
- var result = entry ? entry.typings : server.emptyArray;
- if (forceRefresh || !entry || typingOptionsChanged(typingOptions, entry.typingOptions) || compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions)) {
- this.perProjectCache[project.getProjectName()] = {
- compilerOptions: project.getCompilerOptions(),
- typingOptions: typingOptions,
- typings: result,
- poisoned: true
- };
- this.installer.enqueueInstallTypingsRequest(project, typingOptions);
- }
- return result;
- };
- TypingsCache.prototype.invalidateCachedTypingsForProject = function (project) {
- var typingOptions = project.getTypingOptions();
- if (!typingOptions.enableAutoDiscovery) {
- return;
- }
- this.installer.enqueueInstallTypingsRequest(project, typingOptions);
- };
- TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typingOptions, newTypings) {
- this.perProjectCache[projectName] = {
- compilerOptions: compilerOptions,
- typingOptions: typingOptions,
- typings: toTypingsArray(newTypings),
- poisoned: false
- };
- };
- TypingsCache.prototype.onProjectClosed = function (project) {
- delete this.perProjectCache[project.getProjectName()];
- this.installer.onProjectClosed(project);
- };
- return TypingsCache;
- }());
- server.TypingsCache = TypingsCache;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- var crypto = require("crypto");
- function shouldEmitFile(scriptInfo) {
- return !scriptInfo.hasMixedContent;
- }
- server.shouldEmitFile = shouldEmitFile;
- var BuilderFileInfo = (function () {
- function BuilderFileInfo(scriptInfo, project) {
- this.scriptInfo = scriptInfo;
- this.project = project;
- }
- BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () {
- var sourceFile = this.getSourceFile();
- return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile);
- };
- BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) {
- for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
- var statement = _a[_i];
- if (statement.kind !== 225 || statement.name.kind !== 9) {
- return false;
- }
- }
- return true;
- };
- BuilderFileInfo.prototype.computeHash = function (text) {
- return crypto.createHash("md5")
- .update(text)
- .digest("base64");
- };
- BuilderFileInfo.prototype.getSourceFile = function () {
- return this.project.getSourceFile(this.scriptInfo.path);
- };
- BuilderFileInfo.prototype.updateShapeSignature = function () {
- var sourceFile = this.getSourceFile();
- if (!sourceFile) {
- return true;
- }
- var lastSignature = this.lastCheckedShapeSignature;
- if (sourceFile.isDeclarationFile) {
- this.lastCheckedShapeSignature = this.computeHash(sourceFile.text);
- }
- else {
- var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true);
- if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) {
- this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text);
- }
- }
- return !lastSignature || this.lastCheckedShapeSignature !== lastSignature;
- };
- return BuilderFileInfo;
- }());
- server.BuilderFileInfo = BuilderFileInfo;
- var AbstractBuilder = (function () {
- function AbstractBuilder(project, ctor) {
- this.project = project;
- this.ctor = ctor;
- this.fileInfos = ts.createFileMap();
- }
- AbstractBuilder.prototype.getFileInfo = function (path) {
- return this.fileInfos.get(path);
- };
- AbstractBuilder.prototype.getOrCreateFileInfo = function (path) {
- var fileInfo = this.getFileInfo(path);
- if (!fileInfo) {
- var scriptInfo = this.project.getScriptInfo(path);
- fileInfo = new this.ctor(scriptInfo, this.project);
- this.setFileInfo(path, fileInfo);
- }
- return fileInfo;
- };
- AbstractBuilder.prototype.getFileInfoPaths = function () {
- return this.fileInfos.getKeys();
- };
- AbstractBuilder.prototype.setFileInfo = function (path, info) {
- this.fileInfos.set(path, info);
- };
- AbstractBuilder.prototype.removeFileInfo = function (path) {
- this.fileInfos.remove(path);
- };
- AbstractBuilder.prototype.forEachFileInfo = function (action) {
- this.fileInfos.forEachValue(function (path, value) { return action(value); });
- };
- AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) {
- var fileInfo = this.getFileInfo(scriptInfo.path);
- if (!fileInfo) {
- return false;
- }
- var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles;
- if (!emitSkipped) {
- var projectRootPath = this.project.getProjectRootPath();
- for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) {
- var outputFile = outputFiles_1[_i];
- var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName));
- writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark);
- }
- }
- return !emitSkipped;
- };
- return AbstractBuilder;
- }());
- var NonModuleBuilder = (function (_super) {
- __extends(NonModuleBuilder, _super);
- function NonModuleBuilder(project) {
- _super.call(this, project, BuilderFileInfo);
- this.project = project;
- }
- NonModuleBuilder.prototype.onProjectUpdateGraph = function () {
- };
- NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) {
- var info = this.getOrCreateFileInfo(scriptInfo.path);
- var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName];
- if (info.updateShapeSignature()) {
- var options = this.project.getCompilerOptions();
- if (options && (options.out || options.outFile)) {
- return singleFileResult;
- }
- return this.project.getAllEmittableFiles();
- }
- return singleFileResult;
- };
- return NonModuleBuilder;
- }(AbstractBuilder));
- var ModuleBuilderFileInfo = (function (_super) {
- __extends(ModuleBuilderFileInfo, _super);
- function ModuleBuilderFileInfo() {
- _super.apply(this, arguments);
- this.references = [];
- this.referencedBy = [];
- }
- ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) {
- var l = lf.scriptInfo.fileName;
- var r = rf.scriptInfo.fileName;
- return (l < r ? -1 : (l > r ? 1 : 0));
- };
- ;
- ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) {
- if (array.length === 0) {
- array.push(fileInfo);
- return;
- }
- var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos);
- if (insertIndex < 0) {
- array.splice(~insertIndex, 0, fileInfo);
- }
- };
- ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) {
- if (!array || array.length === 0) {
- return;
- }
- if (array[0] === fileInfo) {
- array.splice(0, 1);
- return;
- }
- var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos);
- if (removeIndex >= 0) {
- array.splice(removeIndex, 1);
- }
- };
- ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) {
- ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo);
- };
- ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) {
- ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo);
- };
- ModuleBuilderFileInfo.prototype.removeFileReferences = function () {
- for (var _i = 0, _a = this.references; _i < _a.length; _i++) {
- var reference = _a[_i];
- reference.removeReferencedBy(this);
- }
- this.references = [];
- };
- return ModuleBuilderFileInfo;
- }(BuilderFileInfo));
- var ModuleBuilder = (function (_super) {
- __extends(ModuleBuilder, _super);
- function ModuleBuilder(project) {
- _super.call(this, project, ModuleBuilderFileInfo);
- this.project = project;
- }
- ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) {
- var _this = this;
- if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) {
- return [];
- }
- var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path);
- if (referencedFilePaths.length > 0) {
- return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos);
- }
- return [];
- };
- ModuleBuilder.prototype.onProjectUpdateGraph = function () {
- this.ensureProjectDependencyGraphUpToDate();
- };
- ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () {
- var _this = this;
- if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) {
- var currentScriptInfos = this.project.getScriptInfos();
- for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) {
- var scriptInfo = currentScriptInfos_1[_i];
- var fileInfo = this.getOrCreateFileInfo(scriptInfo.path);
- this.updateFileReferences(fileInfo);
- }
- this.forEachFileInfo(function (fileInfo) {
- if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) {
- fileInfo.removeFileReferences();
- _this.removeFileInfo(fileInfo.scriptInfo.path);
- }
- });
- this.projectVersionForDependencyGraph = this.project.getProjectVersion();
- }
- };
- ModuleBuilder.prototype.updateFileReferences = function (fileInfo) {
- if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) {
- return;
- }
- var newReferences = this.getReferencedFileInfos(fileInfo);
- var oldReferences = fileInfo.references;
- var oldIndex = 0;
- var newIndex = 0;
- while (oldIndex < oldReferences.length && newIndex < newReferences.length) {
- var oldReference = oldReferences[oldIndex];
- var newReference = newReferences[newIndex];
- var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference);
- if (compare < 0) {
- oldReference.removeReferencedBy(fileInfo);
- oldIndex++;
- }
- else if (compare > 0) {
- newReference.addReferencedBy(fileInfo);
- newIndex++;
- }
- else {
- oldIndex++;
- newIndex++;
- }
- }
- for (var i = oldIndex; i < oldReferences.length; i++) {
- oldReferences[i].removeReferencedBy(fileInfo);
- }
- for (var i = newIndex; i < newReferences.length; i++) {
- newReferences[i].addReferencedBy(fileInfo);
- }
- fileInfo.references = newReferences;
- fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion();
- };
- ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) {
- this.ensureProjectDependencyGraphUpToDate();
- var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName];
- var fileInfo = this.getFileInfo(scriptInfo.path);
- if (!fileInfo || !fileInfo.updateShapeSignature()) {
- return singleFileResult;
- }
- if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) {
- return this.project.getAllEmittableFiles();
- }
- var options = this.project.getCompilerOptions();
- if (options && (options.isolatedModules || options.out || options.outFile)) {
- return singleFileResult;
- }
- var queue = fileInfo.referencedBy.slice(0);
- var fileNameSet = ts.createMap();
- fileNameSet[scriptInfo.fileName] = scriptInfo;
- while (queue.length > 0) {
- var processingFileInfo = queue.pop();
- if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) {
- for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) {
- var potentialFileInfo = _a[_i];
- if (!fileNameSet[potentialFileInfo.scriptInfo.fileName]) {
- queue.push(potentialFileInfo);
- }
- }
- }
- fileNameSet[processingFileInfo.scriptInfo.fileName] = processingFileInfo.scriptInfo;
- }
- var result = [];
- for (var fileName in fileNameSet) {
- if (shouldEmitFile(fileNameSet[fileName])) {
- result.push(fileName);
- }
- }
- return result;
- };
- return ModuleBuilder;
- }(AbstractBuilder));
- function createBuilder(project) {
- var moduleKind = project.getCompilerOptions().module;
- switch (moduleKind) {
- case ts.ModuleKind.None:
- return new NonModuleBuilder(project);
- default:
- return new ModuleBuilder(project);
- }
- }
- server.createBuilder = createBuilder;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- (function (ProjectKind) {
- ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred";
- ProjectKind[ProjectKind["Configured"] = 1] = "Configured";
- ProjectKind[ProjectKind["External"] = 2] = "External";
- })(server.ProjectKind || (server.ProjectKind = {}));
- var ProjectKind = server.ProjectKind;
- function remove(items, item) {
- var index = items.indexOf(item);
- if (index >= 0) {
- items.splice(index, 1);
- }
- }
- function isJsOrDtsFile(info) {
- return info.scriptKind === 1 || info.scriptKind == 2 || ts.fileExtensionIs(info.fileName, ".d.ts");
- }
- function allRootFilesAreJsOrDts(project) {
- return project.getRootScriptInfos().every(isJsOrDtsFile);
- }
- server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts;
- function allFilesAreJsOrDts(project) {
- return project.getScriptInfos().every(isJsOrDtsFile);
- }
- server.allFilesAreJsOrDts = allFilesAreJsOrDts;
- var Project = (function () {
- function Project(projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) {
- this.projectKind = projectKind;
- this.projectService = projectService;
- this.documentRegistry = documentRegistry;
- this.languageServiceEnabled = languageServiceEnabled;
- this.compilerOptions = compilerOptions;
- this.compileOnSaveEnabled = compileOnSaveEnabled;
- this.rootFiles = [];
- this.rootFilesMap = ts.createFileMap();
- this.lastReportedVersion = 0;
- this.projectStructureVersion = 0;
- this.projectStateVersion = 0;
- this.typesVersion = 0;
- if (!this.compilerOptions) {
- this.compilerOptions = ts.getDefaultCompilerOptions();
- this.compilerOptions.allowNonTsExtensions = true;
- this.compilerOptions.allowJs = true;
- }
- else if (hasExplicitListOfFiles) {
- this.compilerOptions.allowNonTsExtensions = true;
- }
- if (languageServiceEnabled) {
- this.enableLanguageService();
- }
- else {
- this.disableLanguageService();
- }
- this.builder = server.createBuilder(this);
- this.markAsDirty();
- }
- Project.prototype.isJsOnlyProject = function () {
- this.updateGraph();
- return allFilesAreJsOrDts(this);
- };
- Project.prototype.getProjectErrors = function () {
- return this.projectErrors;
- };
- Project.prototype.getLanguageService = function (ensureSynchronized) {
- if (ensureSynchronized === void 0) { ensureSynchronized = true; }
- if (ensureSynchronized) {
- this.updateGraph();
- }
- return this.languageService;
- };
- Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) {
- if (!this.languageServiceEnabled) {
- return [];
- }
- this.updateGraph();
- return this.builder.getFilesAffectedBy(scriptInfo);
- };
- Project.prototype.getProjectVersion = function () {
- return this.projectStateVersion.toString();
- };
- Project.prototype.enableLanguageService = function () {
- var lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken);
- lsHost.setCompilationSettings(this.compilerOptions);
- this.languageService = ts.createLanguageService(lsHost, this.documentRegistry);
- this.lsHost = lsHost;
- this.languageServiceEnabled = true;
- };
- Project.prototype.disableLanguageService = function () {
- this.languageService = server.nullLanguageService;
- this.lsHost = server.nullLanguageServiceHost;
- this.languageServiceEnabled = false;
- };
- Project.prototype.getSourceFile = function (path) {
- if (!this.program) {
- return undefined;
- }
- return this.program.getSourceFileByPath(path);
- };
- Project.prototype.updateTypes = function () {
- this.typesVersion++;
- this.markAsDirty();
- this.updateGraph();
- };
- Project.prototype.close = function () {
- if (this.program) {
- for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) {
- var f = _a[_i];
- var info = this.projectService.getScriptInfo(f.fileName);
- info.detachFromProject(this);
- }
- }
- else {
- for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) {
- var root = _c[_b];
- root.detachFromProject(this);
- }
- }
- this.rootFiles = undefined;
- this.rootFilesMap = undefined;
- this.program = undefined;
- this.languageService.dispose();
- };
- Project.prototype.getCompilerOptions = function () {
- return this.compilerOptions;
- };
- Project.prototype.hasRoots = function () {
- return this.rootFiles && this.rootFiles.length > 0;
- };
- Project.prototype.getRootFiles = function () {
- return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; });
- };
- Project.prototype.getRootFilesLSHost = function () {
- var result = [];
- if (this.rootFiles) {
- for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) {
- var f = _a[_i];
- result.push(f.fileName);
- }
- if (this.typingFiles) {
- for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) {
- var f = _c[_b];
- result.push(f);
- }
- }
- }
- return result;
- };
- Project.prototype.getRootScriptInfos = function () {
- return this.rootFiles;
- };
- Project.prototype.getScriptInfos = function () {
- var _this = this;
- return ts.map(this.program.getSourceFiles(), function (sourceFile) { return _this.getScriptInfoLSHost(sourceFile.path); });
- };
- Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) {
- if (!this.languageServiceEnabled) {
- return undefined;
- }
- return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles);
- };
- Project.prototype.getFileNames = function () {
- if (!this.program) {
- return [];
- }
- if (!this.languageServiceEnabled) {
- var rootFiles = this.getRootFiles();
- if (this.compilerOptions) {
- var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions);
- if (defaultLibrary) {
- (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary));
- }
- }
- return rootFiles;
- }
- var sourceFiles = this.program.getSourceFiles();
- return sourceFiles.map(function (sourceFile) { return server.asNormalizedPath(sourceFile.fileName); });
- };
- Project.prototype.getAllEmittableFiles = function () {
- if (!this.languageServiceEnabled) {
- return [];
- }
- var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions);
- var infos = this.getScriptInfos();
- var result = [];
- for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
- var info = infos_1[_i];
- if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) {
- result.push(info.fileName);
- }
- }
- return result;
- };
- Project.prototype.containsScriptInfo = function (info) {
- return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined);
- };
- Project.prototype.containsFile = function (filename, requireOpen) {
- var info = this.projectService.getScriptInfoForNormalizedPath(filename);
- if (info && (info.isOpen || !requireOpen)) {
- return this.containsScriptInfo(info);
- }
- };
- Project.prototype.isRoot = function (info) {
- return this.rootFilesMap && this.rootFilesMap.contains(info.path);
- };
- Project.prototype.addRoot = function (info) {
- if (!this.isRoot(info)) {
- this.rootFiles.push(info);
- this.rootFilesMap.set(info.path, info);
- info.attachToProject(this);
- this.markAsDirty();
- }
- };
- Project.prototype.removeFile = function (info, detachFromProject) {
- if (detachFromProject === void 0) { detachFromProject = true; }
- this.removeRootFileIfNecessary(info);
- this.lsHost.notifyFileRemoved(info);
- if (detachFromProject) {
- info.detachFromProject(this);
- }
- this.markAsDirty();
- };
- Project.prototype.markAsDirty = function () {
- this.projectStateVersion++;
- };
- Project.prototype.updateGraph = function () {
- if (!this.languageServiceEnabled) {
- return true;
- }
- var hasChanges = this.updateGraphWorker();
- var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, hasChanges);
- if (this.setTypings(cachedTypings)) {
- hasChanges = this.updateGraphWorker() || hasChanges;
- }
- if (hasChanges) {
- this.projectStructureVersion++;
- }
- return !hasChanges;
- };
- Project.prototype.setTypings = function (typings) {
- if (ts.arrayIsEqualTo(this.typingFiles, typings)) {
- return false;
- }
- this.typingFiles = typings;
- this.markAsDirty();
- return true;
- };
- Project.prototype.updateGraphWorker = function () {
- var oldProgram = this.program;
- this.program = this.languageService.getProgram();
- var hasChanges = false;
- if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) {
- hasChanges = true;
- if (oldProgram) {
- for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) {
- var f = _a[_i];
- if (this.program.getSourceFileByPath(f.path)) {
- continue;
- }
- var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName);
- if (scriptInfoToDetach) {
- scriptInfoToDetach.detachFromProject(this);
- }
- }
- }
- }
- this.builder.onProjectUpdateGraph();
- return hasChanges;
- };
- Project.prototype.getScriptInfoLSHost = function (fileName) {
- var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false);
- if (scriptInfo) {
- scriptInfo.attachToProject(this);
- }
- return scriptInfo;
- };
- Project.prototype.getScriptInfoForNormalizedPath = function (fileName) {
- var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false);
- if (scriptInfo && !scriptInfo.isAttached(this)) {
- return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this);
- }
- return scriptInfo;
- };
- Project.prototype.getScriptInfo = function (uncheckedFileName) {
- return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
- };
- Project.prototype.filesToString = function () {
- if (!this.program) {
- return "";
- }
+ var spaceCache = [];
+ function generateSpaces(n) {
+ if (!spaceCache[n]) {
var strBuilder = "";
- for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) {
- var file = _a[_i];
- strBuilder += file.fileName + "\n";
+ for (var i = 0; i < n; i++) {
+ strBuilder += " ";
}
- return strBuilder;
- };
- Project.prototype.setCompilerOptions = function (compilerOptions) {
- if (compilerOptions) {
- if (this.projectKind === ProjectKind.Inferred) {
- compilerOptions.allowJs = true;
- }
- compilerOptions.allowNonTsExtensions = true;
- this.compilerOptions = compilerOptions;
- this.lsHost.setCompilationSettings(compilerOptions);
- this.markAsDirty();
- }
- };
- Project.prototype.reloadScript = function (filename) {
- var script = this.projectService.getScriptInfoForNormalizedPath(filename);
- if (script) {
- ts.Debug.assert(script.isAttached(this));
- script.reloadFromFile();
- return true;
- }
- return false;
- };
- Project.prototype.getChangesSinceVersion = function (lastKnownVersion) {
- this.updateGraph();
- var info = {
- projectName: this.getProjectName(),
- version: this.projectStructureVersion,
- isInferred: this.projectKind === ProjectKind.Inferred,
- options: this.getCompilerOptions()
- };
- if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
- if (this.projectStructureVersion == this.lastReportedVersion) {
- return { info: info, projectErrors: this.projectErrors };
- }
- var lastReportedFileNames = this.lastReportedFileNames;
- var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; });
- var added = [];
- var removed = [];
- for (var id in currentFiles) {
- if (!ts.hasProperty(lastReportedFileNames, id)) {
- added.push(id);
- }
- }
- for (var id in lastReportedFileNames) {
- if (!ts.hasProperty(currentFiles, id)) {
- removed.push(id);
- }
- }
- this.lastReportedFileNames = currentFiles;
- this.lastReportedVersion = this.projectStructureVersion;
- return { info: info, changes: { added: added, removed: removed }, projectErrors: this.projectErrors };
- }
- else {
- var projectFileNames = this.getFileNames();
- this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; });
- this.lastReportedVersion = this.projectStructureVersion;
- return { info: info, files: projectFileNames, projectErrors: this.projectErrors };
- }
- };
- Project.prototype.getReferencedFiles = function (path) {
- var _this = this;
- if (!this.languageServiceEnabled) {
- return [];
- }
- var sourceFile = this.getSourceFile(path);
- if (!sourceFile) {
- return [];
- }
- var referencedFiles = ts.createMap();
- if (sourceFile.imports && sourceFile.imports.length > 0) {
- var checker = this.program.getTypeChecker();
- for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
- var importName = _a[_i];
- var symbol = checker.getSymbolAtLocation(importName);
- if (symbol && symbol.declarations && symbol.declarations[0]) {
- var declarationSourceFile = symbol.declarations[0].getSourceFile();
- if (declarationSourceFile) {
- referencedFiles[declarationSourceFile.path] = true;
- }
- }
- }
- }
- var currentDirectory = ts.getDirectoryPath(path);
- var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames);
- if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
- for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
- var referencedFile = _c[_b];
- var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName);
- referencedFiles[referencedPath] = true;
- }
- }
- if (sourceFile.resolvedTypeReferenceDirectiveNames) {
- for (var typeName in sourceFile.resolvedTypeReferenceDirectiveNames) {
- var resolvedTypeReferenceDirective = sourceFile.resolvedTypeReferenceDirectiveNames[typeName];
- if (!resolvedTypeReferenceDirective) {
- continue;
- }
- var fileName = resolvedTypeReferenceDirective.resolvedFileName;
- var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
- referencedFiles[typeFilePath] = true;
- }
- }
- var allFileNames = ts.map(Object.keys(referencedFiles), function (key) { return key; });
- return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); });
- };
- Project.prototype.removeRootFileIfNecessary = function (info) {
- if (this.isRoot(info)) {
- remove(this.rootFiles, info);
- this.rootFilesMap.remove(info.path);
- }
- };
- return Project;
- }());
- server.Project = Project;
- var InferredProject = (function (_super) {
- __extends(InferredProject, _super);
- function InferredProject(projectService, documentRegistry, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) {
- _super.call(this, ProjectKind.Inferred, projectService, documentRegistry, undefined, languageServiceEnabled, compilerOptions, compileOnSaveEnabled);
- this.compileOnSaveEnabled = compileOnSaveEnabled;
- this.directoriesWatchedForTsconfig = [];
- this.inferredProjectName = server.makeInferredProjectName(InferredProject.NextId);
- InferredProject.NextId++;
+ spaceCache[n] = strBuilder;
}
- InferredProject.prototype.getProjectName = function () {
- return this.inferredProjectName;
- };
- InferredProject.prototype.getProjectRootPath = function () {
- if (this.projectService.useSingleInferredProject) {
- return undefined;
- }
- var rootFiles = this.getRootFiles();
- return ts.getDirectoryPath(rootFiles[0]);
- };
- InferredProject.prototype.close = function () {
- _super.prototype.close.call(this);
- for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) {
- var directory = _a[_i];
- this.projectService.stopWatchingDirectory(directory);
- }
- };
- InferredProject.prototype.getTypingOptions = function () {
- return {
- enableAutoDiscovery: allRootFilesAreJsOrDts(this),
- include: [],
- exclude: []
- };
- };
- return InferredProject;
- }(Project));
- InferredProject.NextId = 1;
- server.InferredProject = InferredProject;
- var ConfiguredProject = (function (_super) {
- __extends(ConfiguredProject, _super);
- function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) {
- _super.call(this, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled);
- this.configFileName = configFileName;
- this.wildcardDirectories = wildcardDirectories;
- this.compileOnSaveEnabled = compileOnSaveEnabled;
- this.openRefCount = 0;
- }
- ConfiguredProject.prototype.getProjectRootPath = function () {
- return ts.getDirectoryPath(this.configFileName);
- };
- ConfiguredProject.prototype.setProjectErrors = function (projectErrors) {
- this.projectErrors = projectErrors;
- };
- ConfiguredProject.prototype.setTypingOptions = function (newTypingOptions) {
- this.typingOptions = newTypingOptions;
- };
- ConfiguredProject.prototype.getTypingOptions = function () {
- return this.typingOptions;
- };
- ConfiguredProject.prototype.getProjectName = function () {
- return this.configFileName;
- };
- ConfiguredProject.prototype.watchConfigFile = function (callback) {
- var _this = this;
- this.projectFileWatcher = this.projectService.host.watchFile(this.configFileName, function (_) { return callback(_this); });
- };
- ConfiguredProject.prototype.watchTypeRoots = function (callback) {
- var _this = this;
- var roots = this.getEffectiveTypeRoots();
- var watchers = [];
- for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
- var root = roots_1[_i];
- this.projectService.logger.info("Add type root watcher for: " + root);
- watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false));
- }
- this.typeRootsWatchers = watchers;
- };
- ConfiguredProject.prototype.watchConfigDirectory = function (callback) {
- var _this = this;
- if (this.directoryWatcher) {
- return;
- }
- var directoryToWatch = ts.getDirectoryPath(this.configFileName);
- this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch);
- this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true);
- };
- ConfiguredProject.prototype.watchWildcards = function (callback) {
- var _this = this;
- if (!this.wildcardDirectories) {
- return;
- }
- var configDirectoryPath = ts.getDirectoryPath(this.configFileName);
- this.directoriesWatchedForWildcards = ts.reduceProperties(this.wildcardDirectories, function (watchers, flag, directory) {
- if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) {
- var recursive = (flag & 1) !== 0;
- _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory);
- watchers[directory] = _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive);
- }
- return watchers;
- }, {});
- };
- ConfiguredProject.prototype.stopWatchingDirectory = function () {
- if (this.directoryWatcher) {
- this.directoryWatcher.close();
- this.directoryWatcher = undefined;
- }
- };
- ConfiguredProject.prototype.close = function () {
- _super.prototype.close.call(this);
- if (this.projectFileWatcher) {
- this.projectFileWatcher.close();
- }
- if (this.typeRootsWatchers) {
- for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) {
- var watcher = _a[_i];
- watcher.close();
- }
- this.typeRootsWatchers = undefined;
- }
- for (var id in this.directoriesWatchedForWildcards) {
- this.directoriesWatchedForWildcards[id].close();
- }
- this.directoriesWatchedForWildcards = undefined;
- this.stopWatchingDirectory();
- };
- ConfiguredProject.prototype.addOpenRef = function () {
- this.openRefCount++;
- };
- ConfiguredProject.prototype.deleteOpenRef = function () {
- this.openRefCount--;
- return this.openRefCount;
- };
- ConfiguredProject.prototype.getEffectiveTypeRoots = function () {
- return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || [];
- };
- return ConfiguredProject;
- }(Project));
- server.ConfiguredProject = ConfiguredProject;
- var ExternalProject = (function (_super) {
- __extends(ExternalProject, _super);
- function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) {
- _super.call(this, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled);
- this.externalProjectName = externalProjectName;
- this.compileOnSaveEnabled = compileOnSaveEnabled;
- this.projectFilePath = projectFilePath;
- }
- ExternalProject.prototype.getProjectRootPath = function () {
- if (this.projectFilePath) {
- return ts.getDirectoryPath(this.projectFilePath);
- }
- return ts.getDirectoryPath(ts.normalizeSlashes(this.externalProjectName));
- };
- ExternalProject.prototype.getTypingOptions = function () {
- return this.typingOptions;
- };
- ExternalProject.prototype.setProjectErrors = function (projectErrors) {
- this.projectErrors = projectErrors;
- };
- ExternalProject.prototype.setTypingOptions = function (newTypingOptions) {
- if (!newTypingOptions) {
- newTypingOptions = {
- enableAutoDiscovery: allRootFilesAreJsOrDts(this),
- include: [],
- exclude: []
- };
- }
- else {
- if (newTypingOptions.enableAutoDiscovery === undefined) {
- newTypingOptions.enableAutoDiscovery = allRootFilesAreJsOrDts(this);
- }
- if (!newTypingOptions.include) {
- newTypingOptions.include = [];
- }
- if (!newTypingOptions.exclude) {
- newTypingOptions.exclude = [];
- }
- }
- this.typingOptions = newTypingOptions;
- };
- ExternalProject.prototype.getProjectName = function () {
- return this.externalProjectName;
- };
- return ExternalProject;
- }(Project));
- server.ExternalProject = ExternalProject;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
- function combineProjectOutput(projects, action, comparer, areEqual) {
- var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer);
- return projects.length > 1 ? ts.deduplicate(result, areEqual) : result;
+ return spaceCache[n];
}
- server.combineProjectOutput = combineProjectOutput;
- var fileNamePropertyReader = {
- getFileName: function (x) { return x; },
- getScriptKind: function (_) { return undefined; },
- hasMixedContent: function (_) { return false; }
- };
- var externalFilePropertyReader = {
- getFileName: function (x) { return x.fileName; },
- getScriptKind: function (x) { return x.scriptKind; },
- hasMixedContent: function (x) { return x.hasMixedContent; }
- };
- function findProjectByName(projectName, projects) {
- for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) {
- var proj = projects_1[_i];
- if (proj.getProjectName() === projectName) {
- return proj;
+ server.generateSpaces = generateSpaces;
+ function generateIndentString(n, editorOptions) {
+ if (editorOptions.ConvertTabsToSpaces) {
+ return generateSpaces(n);
+ }
+ else {
+ var result = "";
+ for (var i = 0; i < Math.floor(n / editorOptions.TabSize); i++) {
+ result += "\t";
}
+ for (var i = 0; i < n % editorOptions.TabSize; i++) {
+ result += " ";
+ }
+ return result;
}
}
- function createFileNotFoundDiagnostic(fileName) {
- return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName);
- }
- function isRootFileInInferredProject(info) {
- if (info.containingProjects.length === 0) {
- return false;
- }
- return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info);
- }
- var DirectoryWatchers = (function () {
- function DirectoryWatchers(projectService) {
- this.projectService = projectService;
- this.directoryWatchersForTsconfig = ts.createMap();
- this.directoryWatchersRefCount = ts.createMap();
- }
- DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) {
- this.directoryWatchersRefCount[directory]--;
- if (this.directoryWatchersRefCount[directory] === 0) {
- this.projectService.logger.info("Close directory watcher for: " + directory);
- this.directoryWatchersForTsconfig[directory].close();
- delete this.directoryWatchersForTsconfig[directory];
- }
- };
- DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) {
- var currentPath = ts.getDirectoryPath(fileName);
- var parentPath = ts.getDirectoryPath(currentPath);
- while (currentPath != parentPath) {
- if (!this.directoryWatchersForTsconfig[currentPath]) {
- this.projectService.logger.info("Add watcher for: " + currentPath);
- this.directoryWatchersForTsconfig[currentPath] = this.projectService.host.watchDirectory(currentPath, callback);
- this.directoryWatchersRefCount[currentPath] = 1;
- }
- else {
- this.directoryWatchersRefCount[currentPath] += 1;
- }
- project.directoriesWatchedForTsconfig.push(currentPath);
- currentPath = parentPath;
- parentPath = ts.getDirectoryPath(parentPath);
- }
- };
- return DirectoryWatchers;
- }());
- var ProjectService = (function () {
- function ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler) {
- if (typingsInstaller === void 0) { typingsInstaller = server.nullTypingsInstaller; }
- this.host = host;
- this.logger = logger;
- this.cancellationToken = cancellationToken;
- this.useSingleInferredProject = useSingleInferredProject;
- this.typingsInstaller = typingsInstaller;
- this.eventHandler = eventHandler;
- this.filenameToScriptInfo = ts.createFileMap();
- this.externalProjectToConfiguredProjectMap = ts.createMap();
- this.externalProjects = [];
- this.inferredProjects = [];
- this.configuredProjects = [];
- this.openFiles = [];
- this.toCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
- this.directoryWatchers = new DirectoryWatchers(this);
- this.throttledOperations = new server.ThrottledOperations(host);
- this.typingsInstaller.attach(this);
- this.typingsCache = new server.TypingsCache(this.typingsInstaller);
- this.hostConfiguration = {
- formatCodeOptions: server.getDefaultFormatCodeSettings(this.host),
- hostInfo: "Unknown host"
- };
- this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory());
- }
- ProjectService.prototype.getChangedFiles_TestOnly = function () {
- return this.changedFiles;
- };
- ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () {
- this.ensureInferredProjectsUpToDate();
- };
- ProjectService.prototype.updateTypingsForProject = function (response) {
- var project = this.findProject(response.projectName);
- if (!project) {
- return;
- }
- switch (response.kind) {
- case "set":
- this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.typings);
- project.updateGraph();
- break;
- case "invalidate":
- this.typingsCache.invalidateCachedTypingsForProject(project);
- break;
- }
- };
- ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) {
- this.compilerOptionsForInferredProjects = projectCompilerOptions;
- this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave;
- for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
- var proj = _a[_i];
- proj.setCompilerOptions(projectCompilerOptions);
- proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave;
- }
- this.updateProjectGraphs(this.inferredProjects);
- };
- ProjectService.prototype.stopWatchingDirectory = function (directory) {
- this.directoryWatchers.stopWatchingDirectory(directory);
- };
- ProjectService.prototype.findProject = function (projectName) {
- if (projectName === undefined) {
- return undefined;
- }
- if (server.isInferredProjectName(projectName)) {
- this.ensureInferredProjectsUpToDate();
- return findProjectByName(projectName, this.inferredProjects);
- }
- return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName));
- };
- ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) {
- if (refreshInferredProjects) {
- this.ensureInferredProjectsUpToDate();
- }
- var scriptInfo = this.getScriptInfoForNormalizedPath(fileName);
- return scriptInfo && scriptInfo.getDefaultProject();
- };
- ProjectService.prototype.ensureInferredProjectsUpToDate = function () {
- if (this.changedFiles) {
- var projectsToUpdate = void 0;
- if (this.changedFiles.length === 1) {
- projectsToUpdate = this.changedFiles[0].containingProjects;
- }
- else {
- projectsToUpdate = [];
- for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) {
- var f = _a[_i];
- projectsToUpdate = projectsToUpdate.concat(f.containingProjects);
- }
- }
- this.updateProjectGraphs(projectsToUpdate);
- this.changedFiles = undefined;
- }
- };
- ProjectService.prototype.findContainingExternalProject = function (fileName) {
- for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) {
- var proj = _a[_i];
- if (proj.containsFile(fileName)) {
- return proj;
- }
- }
- return undefined;
- };
- ProjectService.prototype.getFormatCodeOptions = function (file) {
- var formatCodeSettings;
- if (file) {
- var info = this.getScriptInfoForNormalizedPath(file);
- if (info) {
- formatCodeSettings = info.getFormatCodeSettings();
- }
- }
- return formatCodeSettings || this.hostConfiguration.formatCodeOptions;
- };
- ProjectService.prototype.updateProjectGraphs = function (projects) {
- var shouldRefreshInferredProjects = false;
- for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) {
- var p = projects_2[_i];
- if (!p.updateGraph()) {
- shouldRefreshInferredProjects = true;
- }
- }
- if (shouldRefreshInferredProjects) {
- this.refreshInferredProjects();
- }
- };
- ProjectService.prototype.onSourceFileChanged = function (fileName) {
- var info = this.getScriptInfoForNormalizedPath(fileName);
- if (!info) {
- this.logger.info("Error: got watch notification for unknown file: " + fileName);
- return;
- }
- if (!this.host.fileExists(fileName)) {
- this.handleDeletedFile(info);
- }
- else {
- if (info && (!info.isOpen)) {
- info.reloadFromFile();
- this.updateProjectGraphs(info.containingProjects);
- }
- }
- };
- ProjectService.prototype.handleDeletedFile = function (info) {
- this.logger.info(info.fileName + " deleted");
- info.stopWatcher();
- if (!info.isOpen) {
- this.filenameToScriptInfo.remove(info.path);
- var containingProjects = info.containingProjects.slice();
- info.detachAllProjects();
- this.updateProjectGraphs(containingProjects);
- if (!this.eventHandler) {
- return;
- }
- for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) {
- var openFile = _a[_i];
- this.eventHandler({ eventName: "context", data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } });
- }
- }
- this.printProjects();
- };
- ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) {
- var _this = this;
- this.logger.info("Type root file " + fileName + " changed");
- this.throttledOperations.schedule(project.configFileName + " * type root", 250, function () {
- project.updateTypes();
- _this.updateConfiguredProject(project);
- _this.refreshInferredProjects();
- });
- };
- ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) {
- var _this = this;
- if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) {
- return;
- }
- this.logger.info("Detected source file changes: " + fileName);
- this.throttledOperations.schedule(project.configFileName, 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project); });
- };
- ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project) {
- var _this = this;
- var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors;
- this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors);
- var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); }));
- var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); }));
- if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) {
- this.logger.info("Updating configured project");
- this.updateConfiguredProject(project);
- this.refreshInferredProjects();
- }
- };
- ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) {
- this.logger.info("Config file changed: " + project.configFileName);
- this.updateConfiguredProject(project);
- this.refreshInferredProjects();
- };
- ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) {
- if (ts.getBaseFileName(fileName) != "tsconfig.json") {
- this.logger.info(fileName + " is not tsconfig.json");
- return;
- }
- var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors;
- this.reportConfigFileDiagnostics(fileName, configFileErrors);
- this.logger.info("Detected newly added tsconfig file: " + fileName);
- this.reloadProjects();
- };
- ProjectService.prototype.getCanonicalFileName = function (fileName) {
- var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
- return ts.normalizePath(name);
- };
- ProjectService.prototype.removeProject = function (project) {
- this.logger.info("remove project: " + project.getRootFiles().toString());
- project.close();
- switch (project.projectKind) {
- case server.ProjectKind.External:
- server.removeItemFromSet(this.externalProjects, project);
- break;
- case server.ProjectKind.Configured:
- server.removeItemFromSet(this.configuredProjects, project);
- break;
- case server.ProjectKind.Inferred:
- server.removeItemFromSet(this.inferredProjects, project);
- break;
- }
- };
- ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) {
- var externalProject = this.findContainingExternalProject(info.fileName);
- if (externalProject) {
- if (addToListOfOpenFiles) {
- this.openFiles.push(info);
- }
- return;
- }
- var foundConfiguredProject = false;
- for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) {
- var p = _a[_i];
- if (p.projectKind === server.ProjectKind.Configured) {
- foundConfiguredProject = true;
- if (addToListOfOpenFiles) {
- (p).addOpenRef();
- }
- }
- }
- if (foundConfiguredProject) {
- if (addToListOfOpenFiles) {
- this.openFiles.push(info);
- }
- return;
- }
- if (info.containingProjects.length === 0) {
- var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info);
- if (!this.useSingleInferredProject) {
- for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) {
- var f = _c[_b];
- if (f.containingProjects.length === 0) {
- continue;
- }
- var defaultProject = f.getDefaultProject();
- if (isRootFileInInferredProject(info) && defaultProject !== inferredProject && inferredProject.containsScriptInfo(f)) {
- this.removeProject(defaultProject);
- f.attachToProject(inferredProject);
- }
- }
- }
- }
- if (addToListOfOpenFiles) {
- this.openFiles.push(info);
- }
- };
- ProjectService.prototype.closeOpenFile = function (info) {
- info.reloadFromFile();
- server.removeItemFromSet(this.openFiles, info);
- info.isOpen = false;
- var projectsToRemove;
- for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) {
- var p = _a[_i];
- if (p.projectKind === server.ProjectKind.Configured) {
- if (p.deleteOpenRef() === 0) {
- (projectsToRemove || (projectsToRemove = [])).push(p);
- }
- }
- else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) {
- (projectsToRemove || (projectsToRemove = [])).push(p);
- }
- }
- if (projectsToRemove) {
- for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) {
- var project = projectsToRemove_1[_b];
- this.removeProject(project);
- }
- var orphanFiles = void 0;
- for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) {
- var f = _d[_c];
- if (f.containingProjects.length === 0) {
- (orphanFiles || (orphanFiles = [])).push(f);
- }
- }
- if (orphanFiles) {
- for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) {
- var f = orphanFiles_1[_e];
- this.assignScriptInfoToInferredProjectIfNecessary(f, false);
- }
- }
- }
- if (info.containingProjects.length === 0) {
- this.filenameToScriptInfo.remove(info.path);
- }
- };
- ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) {
- var searchPath = ts.getDirectoryPath(fileName);
- this.logger.info("Search path: " + searchPath);
- var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath));
- if (!configFileName) {
- this.logger.info("No config files found.");
- return {};
- }
- this.logger.info("Config file name: " + configFileName);
- var project = this.findConfiguredProjectByProjectName(configFileName);
- if (!project) {
- var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors;
- if (!success) {
- return { configFileName: configFileName, configFileErrors: errors };
- }
- this.logger.info("Opened configuration file " + configFileName);
- if (errors && errors.length > 0) {
- return { configFileName: configFileName, configFileErrors: errors };
- }
- }
- else {
- this.updateConfiguredProject(project);
- }
- return { configFileName: configFileName };
- };
- ProjectService.prototype.findConfigFile = function (searchPath) {
- while (true) {
- var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json"));
- if (this.host.fileExists(tsconfigFileName)) {
- return tsconfigFileName;
- }
- var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json"));
- if (this.host.fileExists(jsconfigFileName)) {
- return jsconfigFileName;
- }
- var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath));
- if (parentPath === searchPath) {
- break;
- }
- searchPath = parentPath;
- }
- return undefined;
- };
- ProjectService.prototype.printProjects = function () {
- if (!this.logger.hasLevel(server.LogLevel.verbose)) {
- return;
- }
- this.logger.startGroup();
- var counter = 0;
- counter = printProjects(this.logger, this.externalProjects, counter);
- counter = printProjects(this.logger, this.configuredProjects, counter);
- counter = printProjects(this.logger, this.inferredProjects, counter);
- this.logger.info("Open files: ");
- for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) {
- var rootFile = _a[_i];
- this.logger.info(rootFile.fileName);
- }
- this.logger.endGroup();
- function printProjects(logger, projects, counter) {
- for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) {
- var project = projects_3[_i];
- project.updateGraph();
- logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter);
- logger.info(project.filesToString());
- logger.info("-----------------------------------------------");
- counter++;
- }
- return counter;
- }
- };
- ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) {
- return findProjectByName(configFileName, this.configuredProjects);
- };
- ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) {
- return findProjectByName(projectFileName, this.externalProjects);
- };
- ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) {
- configFilename = ts.normalizePath(configFilename);
- var configFileContent = this.host.readFile(configFilename);
- var errors;
- var result = ts.parseConfigFileTextToJson(configFilename, configFileContent);
- var config = result.config;
- if (result.error) {
- var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics;
- config = sanitizedConfig;
- errors = diagnostics.length ? diagnostics : [result.error];
- }
- var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename);
- if (parsedCommandLine.errors.length) {
- errors = ts.concatenate(errors, parsedCommandLine.errors);
- }
- ts.Debug.assert(!!parsedCommandLine.fileNames);
- if (parsedCommandLine.fileNames.length === 0) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename));
- return { success: false, configFileErrors: errors };
- }
- var projectOptions = {
- files: parsedCommandLine.fileNames,
- compilerOptions: parsedCommandLine.options,
- configHasFilesProperty: config["files"] !== undefined,
- wildcardDirectories: ts.createMap(parsedCommandLine.wildcardDirectories),
- typingOptions: parsedCommandLine.typingOptions,
- compileOnSave: parsedCommandLine.compileOnSave
- };
- return { success: true, projectOptions: projectOptions, configFileErrors: errors };
- };
- ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (options, fileNames, propertyReader) {
- if (options && options.disableSizeLimit || !this.host.getFileSize) {
- return false;
- }
- var totalNonTsFileSize = 0;
- for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) {
- var f = fileNames_3[_i];
- var fileName = propertyReader.getFileName(f);
- if (ts.hasTypeScriptFileExtension(fileName)) {
- continue;
- }
- totalNonTsFileSize += this.host.getFileSize(fileName);
- if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) {
- return true;
- }
- }
- return false;
- };
- ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typingOptions) {
- var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, options, !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave);
- this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typingOptions, undefined);
- this.externalProjects.push(project);
- return project;
- };
- ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) {
- if (diagnostics && diagnostics.length > 0) {
- this.eventHandler({
- eventName: "configFileDiag",
- data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile }
- });
- }
- };
- ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) {
- var _this = this;
- var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader);
- var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave);
- this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors);
- project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); });
- if (!sizeLimitExceeded) {
- this.watchConfigDirectoryForProject(project, projectOptions);
- }
- project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); });
- project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); });
- this.configuredProjects.push(project);
- return project;
- };
- ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) {
- var _this = this;
- if (!options.configHasFilesProperty) {
- project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); });
- }
- };
- ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typingOptions, configFileErrors) {
- var errors;
- for (var _i = 0, files_4 = files; _i < files_4.length; _i++) {
- var f = files_4[_i];
- var rootFilename = propertyReader.getFileName(f);
- var scriptKind = propertyReader.getScriptKind(f);
- var hasMixedContent = propertyReader.hasMixedContent(f);
- if (this.host.fileExists(rootFilename)) {
- var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent);
- project.addRoot(info);
- }
- else {
- (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename));
- }
- }
- project.setProjectErrors(ts.concatenate(configFileErrors, errors));
- project.setTypingOptions(typingOptions);
- project.updateGraph();
- };
- ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) {
- var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName);
- var projectOptions = conversionResult.success
- ? conversionResult.projectOptions
- : { files: [], compilerOptions: {} };
- var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName);
- return {
- success: conversionResult.success,
- project: project,
- errors: project.getProjectErrors()
- };
- };
- ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors) {
- var oldRootScriptInfos = project.getRootScriptInfos();
- var newRootScriptInfos = [];
- var newRootScriptInfoMap = server.createNormalizedPathMap();
- var projectErrors;
- var rootFilesChanged = false;
- for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) {
- var f = newUncheckedFiles_1[_i];
- var newRootFile = propertyReader.getFileName(f);
- if (!this.host.fileExists(newRootFile)) {
- (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile));
- continue;
- }
- var normalizedPath = server.toNormalizedPath(newRootFile);
- var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath);
- if (!scriptInfo || !project.isRoot(scriptInfo)) {
- rootFilesChanged = true;
- if (!scriptInfo) {
- var scriptKind = propertyReader.getScriptKind(f);
- var hasMixedContent = propertyReader.hasMixedContent(f);
- scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent);
- }
- }
- newRootScriptInfos.push(scriptInfo);
- newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo);
- }
- if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) {
- var toAdd = void 0;
- var toRemove = void 0;
- for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) {
- var oldFile = oldRootScriptInfos_1[_a];
- if (!newRootScriptInfoMap.contains(oldFile.fileName)) {
- (toRemove || (toRemove = [])).push(oldFile);
- }
- }
- for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) {
- var newFile = newRootScriptInfos_1[_b];
- if (!project.isRoot(newFile)) {
- (toAdd || (toAdd = [])).push(newFile);
- }
- }
- if (toRemove) {
- for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) {
- var f = toRemove_1[_c];
- project.removeFile(f);
- }
- }
- if (toAdd) {
- for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) {
- var f = toAdd_1[_d];
- if (f.isOpen && isRootFileInInferredProject(f)) {
- var inferredProject = f.containingProjects[0];
- inferredProject.removeFile(f);
- if (!inferredProject.hasRoots()) {
- this.removeProject(inferredProject);
- }
- }
- project.addRoot(f);
- }
- }
- }
- project.setCompilerOptions(newOptions);
- project.setTypingOptions(newTypingOptions);
- if (compileOnSave !== undefined) {
- project.compileOnSaveEnabled = compileOnSave;
- }
- project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors));
- project.updateGraph();
- };
- ProjectService.prototype.updateConfiguredProject = function (project) {
- if (!this.host.fileExists(project.configFileName)) {
- this.logger.info("Config file deleted");
- this.removeProject(project);
- return;
- }
- var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors;
- if (!success) {
- this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors);
- return configFileErrors;
- }
- if (this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) {
- project.setCompilerOptions(projectOptions.compilerOptions);
- if (!project.languageServiceEnabled) {
- return;
- }
- project.disableLanguageService();
- project.stopWatchingDirectory();
- }
- else {
- if (!project.languageServiceEnabled) {
- project.enableLanguageService();
- }
- this.watchConfigDirectoryForProject(project, projectOptions);
- this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typingOptions, projectOptions.compileOnSave, configFileErrors);
- }
- };
- ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) {
- var _this = this;
- var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length;
- var project = useExistingProject
- ? this.inferredProjects[0]
- : new server.InferredProject(this, this.documentRegistry, true, this.compilerOptionsForInferredProjects, this.compileOnSaveForInferredProjects);
- project.addRoot(root);
- this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); });
- project.updateGraph();
- if (!useExistingProject) {
- this.inferredProjects.push(project);
- }
- return project;
- };
- ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) {
- return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind);
- };
- ProjectService.prototype.getScriptInfo = function (uncheckedFileName) {
- return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
- };
- ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) {
- var _this = this;
- var info = this.getScriptInfoForNormalizedPath(fileName);
- if (!info) {
- var content = void 0;
- if (this.host.fileExists(fileName)) {
- content = fileContent || (hasMixedContent ? "" : this.host.readFile(fileName));
- }
- if (!content) {
- if (openedByClient) {
- content = "";
- }
- }
- if (content !== undefined) {
- info = new server.ScriptInfo(this.host, fileName, content, scriptKind, openedByClient, hasMixedContent);
- this.filenameToScriptInfo.set(info.path, info);
- if (!info.isOpen && !hasMixedContent) {
- info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); }));
- }
- }
- }
- if (info) {
- if (fileContent !== undefined) {
- info.reload(fileContent);
- }
- if (openedByClient) {
- info.isOpen = true;
- }
- }
- return info;
- };
- ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) {
- return this.filenameToScriptInfo.get(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName));
- };
- ProjectService.prototype.setHostConfiguration = function (args) {
- if (args.file) {
- var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file));
- if (info) {
- info.setFormatOptions(args.formatOptions);
- this.logger.info("Host configuration update for file " + args.file);
- }
- }
- else {
- if (args.hostInfo !== undefined) {
- this.hostConfiguration.hostInfo = args.hostInfo;
- this.logger.info("Host information " + args.hostInfo);
- }
- if (args.formatOptions) {
- server.mergeMaps(this.hostConfiguration.formatCodeOptions, args.formatOptions);
- this.logger.info("Format host information updated");
- }
- }
- };
- ProjectService.prototype.closeLog = function () {
- this.logger.close();
- };
- ProjectService.prototype.reloadProjects = function () {
- this.logger.info("reload projects.");
- for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) {
- var info = _a[_i];
- this.openOrUpdateConfiguredProjectForFile(info.fileName);
- }
- this.refreshInferredProjects();
- };
- ProjectService.prototype.refreshInferredProjects = function () {
- this.logger.info("updating project structure from ...");
- this.printProjects();
- var orphantedFiles = [];
- for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) {
- var info = _a[_i];
- if (info.containingProjects.length === 0) {
- orphantedFiles.push(info);
- }
- else {
- if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) {
- var inferredProject = info.containingProjects[0];
- ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred);
- inferredProject.removeFile(info);
- if (!inferredProject.hasRoots()) {
- this.removeProject(inferredProject);
- }
- }
- }
- }
- for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) {
- var f = orphantedFiles_1[_b];
- this.assignScriptInfoToInferredProjectIfNecessary(f, false);
- }
- for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) {
- var p = _d[_c];
- p.updateGraph();
- }
- this.printProjects();
- };
- ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) {
- return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind);
- };
- ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) {
- var _a = this.findContainingExternalProject(fileName)
- ? {}
- : this.openOrUpdateConfiguredProjectForFile(fileName), _b = _a.configFileName, configFileName = _b === void 0 ? undefined : _b, _c = _a.configFileErrors, configFileErrors = _c === void 0 ? undefined : _c;
- var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent);
- this.assignScriptInfoToInferredProjectIfNecessary(info, true);
- this.printProjects();
- return { configFileName: configFileName, configFileErrors: configFileErrors };
- };
- ProjectService.prototype.closeClientFile = function (uncheckedFileName) {
- var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
- if (info) {
- this.closeOpenFile(info);
- info.isOpen = false;
- }
- this.printProjects();
- };
- ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) {
- var _loop_3 = function (proj) {
- var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; });
- result.push(proj.getChangesSinceVersion(knownProject && knownProject.version));
- };
- for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) {
- var proj = currentProjects_1[_i];
- _loop_3(proj);
- }
- };
- ProjectService.prototype.synchronizeProjectList = function (knownProjects) {
- var files = [];
- this.collectChanges(knownProjects, this.externalProjects, files);
- this.collectChanges(knownProjects, this.configuredProjects, files);
- this.collectChanges(knownProjects, this.inferredProjects, files);
- return files;
- };
- ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) {
- var recordChangedFiles = changedFiles && !openFiles && !closedFiles;
- if (openFiles) {
- for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) {
- var file = openFiles_1[_i];
- var scriptInfo = this.getScriptInfo(file.fileName);
- ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen);
- var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName);
- this.openClientFileWithNormalizedPath(normalizedPath, file.content, file.scriptKind, file.hasMixedContent);
- }
- }
- if (changedFiles) {
- for (var _a = 0, changedFiles_1 = changedFiles; _a < changedFiles_1.length; _a++) {
- var file = changedFiles_1[_a];
- var scriptInfo = this.getScriptInfo(file.fileName);
- ts.Debug.assert(!!scriptInfo);
- for (var i = file.changes.length - 1; i >= 0; i--) {
- var change = file.changes[i];
- scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
- }
- if (recordChangedFiles) {
- if (!this.changedFiles) {
- this.changedFiles = [scriptInfo];
- }
- else if (this.changedFiles.indexOf(scriptInfo) < 0) {
- this.changedFiles.push(scriptInfo);
- }
- }
- }
- }
- if (closedFiles) {
- for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) {
- var file = closedFiles_1[_b];
- this.closeClientFile(file);
- }
- }
- if (openFiles || closedFiles) {
- this.refreshInferredProjects();
- }
- };
- ProjectService.prototype.closeConfiguredProject = function (configFile) {
- var configuredProject = this.findConfiguredProjectByProjectName(configFile);
- if (configuredProject && configuredProject.deleteOpenRef() === 0) {
- this.removeProject(configuredProject);
- }
- };
- ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) {
- if (suppressRefresh === void 0) { suppressRefresh = false; }
- var fileName = server.toNormalizedPath(uncheckedFileName);
- var configFiles = this.externalProjectToConfiguredProjectMap[fileName];
- if (configFiles) {
- var shouldRefreshInferredProjects = false;
- for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) {
- var configFile = configFiles_1[_i];
- if (this.closeConfiguredProject(configFile)) {
- shouldRefreshInferredProjects = true;
- }
- }
- delete this.externalProjectToConfiguredProjectMap[fileName];
- if (shouldRefreshInferredProjects && !suppressRefresh) {
- this.refreshInferredProjects();
- }
- }
- else {
- var externalProject = this.findExternalProjectByProjectName(uncheckedFileName);
- if (externalProject) {
- this.removeProject(externalProject);
- if (!suppressRefresh) {
- this.refreshInferredProjects();
- }
- }
- }
- };
- ProjectService.prototype.openExternalProject = function (proj) {
- var tsConfigFiles;
- var rootFiles = [];
- for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) {
- var file = _a[_i];
- var normalized = server.toNormalizedPath(file.fileName);
- if (ts.getBaseFileName(normalized) === "tsconfig.json") {
- (tsConfigFiles || (tsConfigFiles = [])).push(normalized);
- }
- else {
- rootFiles.push(file);
- }
- }
- if (tsConfigFiles) {
- tsConfigFiles.sort();
- }
- var externalProject = this.findExternalProjectByProjectName(proj.projectFileName);
- var exisingConfigFiles;
- if (externalProject) {
- if (!tsConfigFiles) {
- this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, proj.options, proj.typingOptions, proj.options.compileOnSave, undefined);
- return;
- }
- this.closeExternalProject(proj.projectFileName, true);
- }
- else if (this.externalProjectToConfiguredProjectMap[proj.projectFileName]) {
- if (!tsConfigFiles) {
- this.closeExternalProject(proj.projectFileName, true);
- }
- else {
- var oldConfigFiles = this.externalProjectToConfiguredProjectMap[proj.projectFileName];
- var iNew = 0;
- var iOld = 0;
- while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) {
- var newConfig = tsConfigFiles[iNew];
- var oldConfig = oldConfigFiles[iOld];
- if (oldConfig < newConfig) {
- this.closeConfiguredProject(oldConfig);
- iOld++;
- }
- else if (oldConfig > newConfig) {
- iNew++;
- }
- else {
- (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig);
- iOld++;
- iNew++;
- }
- }
- for (var i = iOld; i < oldConfigFiles.length; i++) {
- this.closeConfiguredProject(oldConfigFiles[i]);
- }
- }
- }
- if (tsConfigFiles) {
- this.externalProjectToConfiguredProjectMap[proj.projectFileName] = tsConfigFiles;
- for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) {
- var tsconfigFile = tsConfigFiles_1[_b];
- var project = this.findConfiguredProjectByProjectName(tsconfigFile);
- if (!project) {
- var result = this.openConfigFile(tsconfigFile);
- project = result.success && result.project;
- }
- if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) {
- project.addOpenRef();
- }
- }
- }
- else {
- delete this.externalProjectToConfiguredProjectMap[proj.projectFileName];
- this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typingOptions);
- }
- this.refreshInferredProjects();
- };
- return ProjectService;
- }());
- server.ProjectService = ProjectService;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- function hrTimeToMilliseconds(time) {
- var seconds = time[0];
- var nanoseconds = time[1];
- return ((1e9 * seconds) + nanoseconds) / 1000000.0;
- }
+ server.generateIndentString = generateIndentString;
function compareNumber(a, b) {
- return a - b;
+ if (a < b) {
+ return -1;
+ }
+ else if (a === b) {
+ return 0;
+ }
+ else
+ return 1;
}
function compareFileStart(a, b) {
if (a.file < b.file) {
@@ -62855,10 +60288,9 @@ var ts;
}
}
function formatDiag(fileName, project, diag) {
- var scriptInfo = project.getScriptInfoForNormalizedPath(fileName);
return {
- start: scriptInfo.positionToLineOffset(diag.start),
- end: scriptInfo.positionToLineOffset(diag.start + diag.length),
+ start: project.compilerService.host.positionToLineOffset(fileName, diag.start),
+ end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length),
text: ts.flattenDiagnosticMessageText(diag.messageText, "\n")
};
}
@@ -62870,9 +60302,8 @@ var ts;
};
}
function allEditsBeforePos(edits, pos) {
- for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
- var edit = edits_1[_i];
- if (ts.textSpanEnd(edit.span) >= pos) {
+ for (var i = 0, len = edits.length; i < len; i++) {
+ if (ts.textSpanEnd(edits[i].span) >= pos) {
return false;
}
}
@@ -62881,153 +60312,73 @@ var ts;
var CommandNames;
(function (CommandNames) {
CommandNames.Brace = "brace";
- CommandNames.BraceFull = "brace-full";
- CommandNames.BraceCompletion = "braceCompletion";
CommandNames.Change = "change";
CommandNames.Close = "close";
CommandNames.Completions = "completions";
- CommandNames.CompletionsFull = "completions-full";
CommandNames.CompletionDetails = "completionEntryDetails";
- CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList";
- CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile";
CommandNames.Configure = "configure";
CommandNames.Definition = "definition";
- CommandNames.DefinitionFull = "definition-full";
CommandNames.Exit = "exit";
CommandNames.Format = "format";
CommandNames.Formatonkey = "formatonkey";
- CommandNames.FormatFull = "format-full";
- CommandNames.FormatonkeyFull = "formatonkey-full";
- CommandNames.FormatRangeFull = "formatRange-full";
CommandNames.Geterr = "geterr";
CommandNames.GeterrForProject = "geterrForProject";
+ CommandNames.Implementation = "implementation";
CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync";
CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync";
CommandNames.NavBar = "navbar";
- CommandNames.NavBarFull = "navbar-full";
CommandNames.Navto = "navto";
- CommandNames.NavtoFull = "navto-full";
CommandNames.Occurrences = "occurrences";
CommandNames.DocumentHighlights = "documentHighlights";
- CommandNames.DocumentHighlightsFull = "documentHighlights-full";
CommandNames.Open = "open";
CommandNames.Quickinfo = "quickinfo";
- CommandNames.QuickinfoFull = "quickinfo-full";
CommandNames.References = "references";
- CommandNames.ReferencesFull = "references-full";
CommandNames.Reload = "reload";
CommandNames.Rename = "rename";
- CommandNames.RenameInfoFull = "rename-full";
- CommandNames.RenameLocationsFull = "renameLocations-full";
CommandNames.Saveto = "saveto";
CommandNames.SignatureHelp = "signatureHelp";
- CommandNames.SignatureHelpFull = "signatureHelp-full";
CommandNames.TypeDefinition = "typeDefinition";
CommandNames.ProjectInfo = "projectInfo";
CommandNames.ReloadProjects = "reloadProjects";
CommandNames.Unknown = "unknown";
- CommandNames.OpenExternalProject = "openExternalProject";
- CommandNames.OpenExternalProjects = "openExternalProjects";
- CommandNames.CloseExternalProject = "closeExternalProject";
- CommandNames.SynchronizeProjectList = "synchronizeProjectList";
- CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles";
- CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full";
- CommandNames.Cleanup = "cleanup";
- CommandNames.OutliningSpans = "outliningSpans";
- CommandNames.TodoComments = "todoComments";
- CommandNames.Indentation = "indentation";
- CommandNames.DocCommentTemplate = "docCommentTemplate";
- CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full";
- CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan";
- CommandNames.BreakpointStatement = "breakpointStatement";
- CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects";
})(CommandNames = server.CommandNames || (server.CommandNames = {}));
- function formatMessage(msg, logger, byteLength, newLine) {
- var verboseLogging = logger.hasLevel(server.LogLevel.verbose);
- var json = JSON.stringify(msg);
- if (verboseLogging) {
- logger.info(msg.type + ": " + json);
- }
- var len = byteLength(json, "utf8");
- return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine;
- }
- server.formatMessage = formatMessage;
+ var Errors;
+ (function (Errors) {
+ Errors.NoProject = new Error("No Project.");
+ Errors.ProjectLanguageServiceDisabled = new Error("The project's language service is disabled.");
+ })(Errors || (Errors = {}));
var Session = (function () {
- function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents) {
+ function Session(host, byteLength, hrtime, logger) {
var _this = this;
this.host = host;
- this.typingsInstaller = typingsInstaller;
this.byteLength = byteLength;
this.hrtime = hrtime;
this.logger = logger;
- this.canUseEvents = canUseEvents;
this.changeSeq = 0;
this.handlers = ts.createMap((_a = {},
- _a[CommandNames.OpenExternalProject] = function (request) {
- _this.projectService.openExternalProject(request.arguments);
- return _this.requiredResponse(true);
- },
- _a[CommandNames.OpenExternalProjects] = function (request) {
- for (var _i = 0, _a = request.arguments.projects; _i < _a.length; _i++) {
- var proj = _a[_i];
- _this.projectService.openExternalProject(proj);
- }
- return _this.requiredResponse(true);
- },
- _a[CommandNames.CloseExternalProject] = function (request) {
- _this.projectService.closeExternalProject(request.arguments.projectFileName);
- return _this.requiredResponse(true);
- },
- _a[CommandNames.SynchronizeProjectList] = function (request) {
- var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects);
- if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) {
- return _this.requiredResponse(result);
- }
- var converted = ts.map(result, function (p) {
- if (!p.projectErrors || p.projectErrors.length === 0) {
- return p;
- }
- return {
- info: p.info,
- changes: p.changes,
- files: p.files,
- projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined)
- };
- });
- return _this.requiredResponse(converted);
- },
- _a[CommandNames.ApplyChangedToOpenFiles] = function (request) {
- _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles);
- _this.changeSeq++;
- return _this.requiredResponse(true);
- },
_a[CommandNames.Exit] = function () {
_this.exit();
- return _this.notRequired();
+ return { responseRequired: false };
},
_a[CommandNames.Definition] = function (request) {
- return _this.requiredResponse(_this.getDefinition(request.arguments, true));
- },
- _a[CommandNames.DefinitionFull] = function (request) {
- return _this.requiredResponse(_this.getDefinition(request.arguments, false));
+ var defArgs = request.arguments;
+ return { response: _this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true };
},
_a[CommandNames.TypeDefinition] = function (request) {
- return _this.requiredResponse(_this.getTypeDefinition(request.arguments));
+ var defArgs = request.arguments;
+ return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true };
+ },
+ _a[CommandNames.Implementation] = function (request) {
+ var implArgs = request.arguments;
+ return { response: _this.getImplementation(implArgs.line, implArgs.offset, implArgs.file), responseRequired: true };
},
_a[CommandNames.References] = function (request) {
- return _this.requiredResponse(_this.getReferences(request.arguments, true));
- },
- _a[CommandNames.ReferencesFull] = function (request) {
- return _this.requiredResponse(_this.getReferences(request.arguments, false));
+ var defArgs = request.arguments;
+ return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true };
},
_a[CommandNames.Rename] = function (request) {
- return _this.requiredResponse(_this.getRenameLocations(request.arguments, true));
- },
- _a[CommandNames.RenameLocationsFull] = function (request) {
- return _this.requiredResponse(_this.getRenameLocations(request.arguments, false));
- },
- _a[CommandNames.RenameInfoFull] = function (request) {
- return _this.requiredResponse(_this.getRenameInfo(request.arguments));
+ var renameArgs = request.arguments;
+ return { response: _this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true };
},
_a[CommandNames.Open] = function (request) {
var openArgs = request.arguments;
@@ -63046,81 +60397,34 @@ var ts;
scriptKind = 2;
break;
}
- _this.openClientFile(server.toNormalizedPath(openArgs.file), openArgs.fileContent, scriptKind);
- return _this.notRequired();
+ _this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind);
+ return { responseRequired: false };
},
_a[CommandNames.Quickinfo] = function (request) {
- return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true));
- },
- _a[CommandNames.QuickinfoFull] = function (request) {
- return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false));
- },
- _a[CommandNames.OutliningSpans] = function (request) {
- return _this.requiredResponse(_this.getOutliningSpans(request.arguments));
- },
- _a[CommandNames.TodoComments] = function (request) {
- return _this.requiredResponse(_this.getTodoComments(request.arguments));
- },
- _a[CommandNames.Indentation] = function (request) {
- return _this.requiredResponse(_this.getIndentation(request.arguments));
- },
- _a[CommandNames.NameOrDottedNameSpan] = function (request) {
- return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments));
- },
- _a[CommandNames.BreakpointStatement] = function (request) {
- return _this.requiredResponse(_this.getBreakpointStatement(request.arguments));
- },
- _a[CommandNames.BraceCompletion] = function (request) {
- return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments));
- },
- _a[CommandNames.DocCommentTemplate] = function (request) {
- return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments));
+ var quickinfoArgs = request.arguments;
+ return { response: _this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true };
},
_a[CommandNames.Format] = function (request) {
- return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments));
+ var formatArgs = request.arguments;
+ return { response: _this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true };
},
_a[CommandNames.Formatonkey] = function (request) {
- return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments));
- },
- _a[CommandNames.FormatFull] = function (request) {
- return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments));
- },
- _a[CommandNames.FormatonkeyFull] = function (request) {
- return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments));
- },
- _a[CommandNames.FormatRangeFull] = function (request) {
- return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments));
+ var formatOnKeyArgs = request.arguments;
+ return { response: _this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true };
},
_a[CommandNames.Completions] = function (request) {
- return _this.requiredResponse(_this.getCompletions(request.arguments, true));
- },
- _a[CommandNames.CompletionsFull] = function (request) {
- return _this.requiredResponse(_this.getCompletions(request.arguments, false));
+ var completionsArgs = request.arguments;
+ return { response: _this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true };
},
_a[CommandNames.CompletionDetails] = function (request) {
- return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments));
- },
- _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) {
- return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments));
- },
- _a[CommandNames.CompileOnSaveEmitFile] = function (request) {
- return _this.requiredResponse(_this.emitFile(request.arguments));
+ var completionDetailsArgs = request.arguments;
+ return {
+ response: _this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true
+ };
},
_a[CommandNames.SignatureHelp] = function (request) {
- return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true));
- },
- _a[CommandNames.SignatureHelpFull] = function (request) {
- return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false));
- },
- _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) {
- return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments));
- },
- _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) {
- return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments));
- },
- _a[CommandNames.Cleanup] = function (request) {
- _this.cleanup();
- return _this.requiredResponse(true);
+ var signatureHelpArgs = request.arguments;
+ return { response: _this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true };
},
_a[CommandNames.SemanticDiagnosticsSync] = function (request) {
return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments));
@@ -63137,71 +60441,64 @@ var ts;
return { response: _this.getDiagnosticsForProject(delay, file), responseRequired: false };
},
_a[CommandNames.Change] = function (request) {
- _this.change(request.arguments);
- return _this.notRequired();
+ var changeArgs = request.arguments;
+ _this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file);
+ return { responseRequired: false };
},
_a[CommandNames.Configure] = function (request) {
- _this.projectService.setHostConfiguration(request.arguments);
+ var configureArgs = request.arguments;
+ _this.projectService.setHostConfiguration(configureArgs);
_this.output(undefined, CommandNames.Configure, request.seq);
- return _this.notRequired();
+ return { responseRequired: false };
},
_a[CommandNames.Reload] = function (request) {
- _this.reload(request.arguments, request.seq);
- return _this.requiredResponse({ reloadFinished: true });
+ var reloadArgs = request.arguments;
+ _this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq);
+ return { response: { reloadFinished: true }, responseRequired: true };
},
_a[CommandNames.Saveto] = function (request) {
var savetoArgs = request.arguments;
_this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile);
- return _this.notRequired();
+ return { responseRequired: false };
},
_a[CommandNames.Close] = function (request) {
var closeArgs = request.arguments;
_this.closeClientFile(closeArgs.file);
- return _this.notRequired();
+ return { responseRequired: false };
},
_a[CommandNames.Navto] = function (request) {
- return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true));
- },
- _a[CommandNames.NavtoFull] = function (request) {
- return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false));
+ var navtoArgs = request.arguments;
+ return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount, navtoArgs.currentFileOnly), responseRequired: true };
},
_a[CommandNames.Brace] = function (request) {
- return _this.requiredResponse(_this.getBraceMatching(request.arguments, true));
- },
- _a[CommandNames.BraceFull] = function (request) {
- return _this.requiredResponse(_this.getBraceMatching(request.arguments, false));
+ var braceArguments = request.arguments;
+ return { response: _this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true };
},
_a[CommandNames.NavBar] = function (request) {
- return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true));
- },
- _a[CommandNames.NavBarFull] = function (request) {
- return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false));
+ var navBarArgs = request.arguments;
+ return { response: _this.getNavigationBarItems(navBarArgs.file), responseRequired: true };
},
_a[CommandNames.Occurrences] = function (request) {
- return _this.requiredResponse(_this.getOccurrences(request.arguments));
+ var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file;
+ return { response: _this.getOccurrences(line, offset, fileName), responseRequired: true };
},
_a[CommandNames.DocumentHighlights] = function (request) {
- return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true));
- },
- _a[CommandNames.DocumentHighlightsFull] = function (request) {
- return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false));
- },
- _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) {
- return _this.requiredResponse(_this.setCompilerOptionsForInferredProjects(request.arguments));
+ var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file, filesToSearch = _a.filesToSearch;
+ return { response: _this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true };
},
_a[CommandNames.ProjectInfo] = function (request) {
- return _this.requiredResponse(_this.getProjectInfo(request.arguments));
+ var _a = request.arguments, file = _a.file, needFileNameList = _a.needFileNameList;
+ return { response: _this.getProjectInfo(file, needFileNameList), responseRequired: true };
},
_a[CommandNames.ReloadProjects] = function (request) {
- _this.projectService.reloadProjects();
- return _this.notRequired();
+ _this.reloadProjects();
+ return { responseRequired: false };
},
_a));
- var eventHandler = canUseEvents
- ? function (event) { return _this.handleEvent(event); }
- : undefined;
- this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler);
- this.gcTimer = new server.GcTimer(host, 7000, logger);
+ this.projectService =
+ new server.ProjectService(host, logger, function (event) {
+ _this.handleEvent(event);
+ });
var _a;
}
Session.prototype.handleEvent = function (event) {
@@ -63209,7 +60506,7 @@ var ts;
switch (event.eventName) {
case "context":
var _a = event.data, project = _a.project, fileName = _a.fileName;
- this.projectService.logger.info("got context event, updating diagnostics for " + fileName);
+ this.projectService.log("got context event, updating diagnostics for" + fileName, "Info");
this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100);
break;
case "configFileDiag":
@@ -63218,23 +60515,26 @@ var ts;
}
};
Session.prototype.logError = function (err, cmd) {
+ var typedErr = err;
var msg = "Exception on executing command " + cmd;
- if (err.message) {
- msg += ":\n" + err.message;
- if (err.stack) {
- msg += "\n" + err.stack;
+ if (typedErr.message) {
+ msg += ":\n" + typedErr.message;
+ if (typedErr.stack) {
+ msg += "\n" + typedErr.stack;
}
}
- this.logger.msg(msg, server.Msg.Err);
+ this.projectService.log(msg);
+ };
+ Session.prototype.sendLineToClient = function (line) {
+ this.host.write(line + this.host.newLine);
};
Session.prototype.send = function (msg) {
- if (msg.type === "event" && !this.canUseEvents) {
- if (this.logger.hasLevel(server.LogLevel.verbose)) {
- this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg));
- }
- return;
+ var json = JSON.stringify(msg);
+ if (this.logger.isVerbose()) {
+ this.logger.info(msg.type + ": " + json);
}
- this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine));
+ this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) +
+ "\r\n\r\n" + json);
};
Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) {
var bakedDiags = ts.map(diagnostics, formatConfigFileDiag);
@@ -63259,7 +60559,7 @@ var ts;
};
this.send(ev);
};
- Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) {
+ Session.prototype.response = function (info, cmdName, reqSeq, errorMsg) {
if (reqSeq === void 0) { reqSeq = 0; }
var res = {
seq: 0,
@@ -63276,9 +60576,13 @@ var ts;
}
this.send(res);
};
+ Session.prototype.output = function (body, commandName, requestSequence, errorMessage) {
+ if (requestSequence === void 0) { requestSequence = 0; }
+ this.response(body, commandName, requestSequence, errorMessage);
+ };
Session.prototype.semanticCheck = function (file, project) {
try {
- var diags = project.getLanguageService().getSemanticDiagnostics(file);
+ var diags = project.compilerService.languageService.getSemanticDiagnostics(file);
if (diags) {
var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); });
this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag");
@@ -63290,7 +60594,7 @@ var ts;
};
Session.prototype.syntacticCheck = function (file, project) {
try {
- var diags = project.getLanguageService().getSyntacticDiagnostics(file);
+ var diags = project.compilerService.languageService.getSyntacticDiagnostics(file);
if (diags) {
var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); });
this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag");
@@ -63300,12 +60604,15 @@ var ts;
this.logError(err, "syntactic check");
}
};
+ Session.prototype.reloadProjects = function () {
+ this.projectService.reloadProjects();
+ };
Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) {
var _this = this;
if (ms === void 0) { ms = 1500; }
- this.host.setTimeout(function () {
+ setTimeout(function () {
if (matchSeq(seq)) {
- _this.projectService.refreshInferredProjects();
+ _this.projectService.updateProjectStructure();
}
}, ms);
};
@@ -63318,10 +60625,10 @@ var ts;
followMs = ms;
}
if (this.errorTimer) {
- this.host.clearTimeout(this.errorTimer);
+ clearTimeout(this.errorTimer);
}
if (this.immediateId) {
- this.host.clearImmediate(this.immediateId);
+ clearImmediate(this.immediateId);
this.immediateId = undefined;
}
var index = 0;
@@ -63329,13 +60636,13 @@ var ts;
if (matchSeq(seq)) {
var checkSpec_1 = checkList[index];
index++;
- if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) {
+ if (checkSpec_1.project.getSourceFileFromName(checkSpec_1.fileName, requireOpen)) {
_this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project);
- _this.immediateId = _this.host.setImmediate(function () {
+ _this.immediateId = setImmediate(function () {
_this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project);
_this.immediateId = undefined;
if (checkList.length > index) {
- _this.errorTimer = _this.host.setTimeout(checkOne, followMs);
+ _this.errorTimer = setTimeout(checkOne, followMs);
}
else {
_this.errorTimer = undefined;
@@ -63345,111 +60652,78 @@ var ts;
}
};
if ((checkList.length > index) && (matchSeq(seq))) {
- this.errorTimer = this.host.setTimeout(checkOne, ms);
+ this.errorTimer = setTimeout(checkOne, ms);
}
};
- Session.prototype.cleanProjects = function (caption, projects) {
- if (!projects) {
- return;
+ Session.prototype.getDefinition = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
}
- this.logger.info("cleaning " + caption);
- for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) {
- var p = projects_4[_i];
- p.getLanguageService(false).cleanupSemanticCache();
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var definitions = compilerService.languageService.getDefinitionAtPosition(file, position);
+ if (!definitions) {
+ return undefined;
}
- };
- Session.prototype.cleanup = function () {
- this.cleanProjects("inferred projects", this.projectService.inferredProjects);
- this.cleanProjects("configured projects", this.projectService.configuredProjects);
- this.cleanProjects("external projects", this.projectService.externalProjects);
- if (this.host.gc) {
- this.logger.info("host.gc()");
- this.host.gc();
- }
- };
- Session.prototype.getEncodedSemanticClassifications = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- return project.getLanguageService().getEncodedSemanticClassifications(file, args);
- };
- Session.prototype.getProject = function (projectFileName) {
- return projectFileName && this.projectService.findProject(projectFileName);
- };
- Session.prototype.getCompilerOptionsDiagnostics = function (args) {
- var project = this.getProject(args.projectFileName);
- return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined);
- };
- Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) {
- var _this = this;
- return diagnostics.map(function (d) { return ({
- message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine),
- start: d.start,
- length: d.length,
- category: ts.DiagnosticCategory[d.category].toLowerCase(),
- code: d.code,
- startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start),
- endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length)
+ return definitions.map(function (def) { return ({
+ file: def.fileName,
+ start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start),
+ end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan))
}); });
};
- Session.prototype.getDiagnosticsWorker = function (args, selector, includeLinePosition) {
- var _a = this.getFileAndProject(args), project = _a.project, file = _a.file;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var diagnostics = selector(project, file);
- return includeLinePosition
- ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo)
- : diagnostics.map(function (d) { return formatDiag(file, project, d); });
- };
- Session.prototype.getDefinition = function (args, simplifiedResult) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var definitions = project.getLanguageService().getDefinitionAtPosition(file, position);
+ Session.prototype.getTypeDefinition = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position);
if (!definitions) {
return undefined;
}
- if (simplifiedResult) {
- return definitions.map(function (def) {
- var defScriptInfo = project.getScriptInfo(def.fileName);
- return {
- file: def.fileName,
- start: defScriptInfo.positionToLineOffset(def.textSpan.start),
- end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan))
- };
- });
- }
- else {
- return definitions;
- }
+ return definitions.map(function (def) { return ({
+ file: def.fileName,
+ start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start),
+ end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan))
+ }); });
};
- Session.prototype.getTypeDefinition = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position);
- if (!definitions) {
+ Session.prototype.getImplementation = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var implementations = compilerService.languageService.getImplementationAtPosition(file, compilerService.host.lineOffsetToPosition(file, line, offset));
+ if (!implementations) {
return undefined;
}
- return definitions.map(function (def) {
- var defScriptInfo = project.getScriptInfo(def.fileName);
- return {
- file: def.fileName,
- start: defScriptInfo.positionToLineOffset(def.textSpan.start),
- end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan))
- };
- });
+ return implementations.map(function (impl) { return ({
+ file: impl.fileName,
+ start: compilerService.host.positionToLineOffset(impl.fileName, impl.textSpan.start),
+ end: compilerService.host.positionToLineOffset(impl.fileName, ts.textSpanEnd(impl.textSpan))
+ }); });
};
- Session.prototype.getOccurrences = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position);
+ Session.prototype.getOccurrences = function (line, offset, fileName) {
+ fileName = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(fileName);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(fileName, line, offset);
+ var occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position);
if (!occurrences) {
return undefined;
}
return occurrences.map(function (occurrence) {
var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan;
- var scriptInfo = project.getScriptInfo(fileName);
- var start = scriptInfo.positionToLineOffset(textSpan.start);
- var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan));
+ var start = compilerService.host.positionToLineOffset(fileName, textSpan.start);
+ var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan));
return {
start: start,
end: end,
@@ -63458,142 +60732,115 @@ var ts;
};
});
};
+ Session.prototype.getDiagnosticsWorker = function (args, selector) {
+ var file = ts.normalizePath(args.file);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project) {
+ throw Errors.NoProject;
+ }
+ if (project.languageServiceDiabled) {
+ throw Errors.ProjectLanguageServiceDisabled;
+ }
+ var diagnostics = selector(project, file);
+ return ts.map(diagnostics, function (originalDiagnostic) { return formatDiag(file, project, originalDiagnostic); });
+ };
Session.prototype.getSyntacticDiagnosticsSync = function (args) {
- return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition);
+ return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSyntacticDiagnostics(file); });
};
Session.prototype.getSemanticDiagnosticsSync = function (args) {
- return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition);
+ return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSemanticDiagnostics(file); });
};
- Session.prototype.getDocumentHighlights = function (args, simplifiedResult) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch);
+ Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) {
+ fileName = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(fileName);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(fileName, line, offset);
+ var documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch);
if (!documentHighlights) {
return undefined;
}
- if (simplifiedResult) {
- return documentHighlights.map(convertToDocumentHighlightsItem);
- }
- else {
- return documentHighlights;
- }
+ return documentHighlights.map(convertToDocumentHighlightsItem);
function convertToDocumentHighlightsItem(documentHighlights) {
var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans;
- var scriptInfo = project.getScriptInfo(fileName);
return {
file: fileName,
highlightSpans: highlightSpans.map(convertHighlightSpan)
};
function convertHighlightSpan(highlightSpan) {
var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind;
- var start = scriptInfo.positionToLineOffset(textSpan.start);
- var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan));
+ var start = compilerService.host.positionToLineOffset(fileName, textSpan.start);
+ var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan));
return { start: start, end: end, kind: kind };
}
}
};
- Session.prototype.setCompilerOptionsForInferredProjects = function (args) {
- this.projectService.setCompilerOptionsForInferredProjects(args.options);
- };
- Session.prototype.getProjectInfo = function (args) {
- return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList);
- };
- Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) {
- var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project;
+ Session.prototype.getProjectInfo = function (fileName, needFileNameList) {
+ fileName = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(fileName);
+ if (!project) {
+ throw Errors.NoProject;
+ }
var projectInfo = {
- configFileName: project.getProjectName(),
- languageServiceDisabled: !project.languageServiceEnabled,
- fileNames: needFileNameList ? project.getFileNames() : undefined
+ configFileName: project.projectFilename,
+ languageServiceDisabled: project.languageServiceDiabled
};
+ if (needFileNameList) {
+ projectInfo.fileNames = project.getFileNames();
+ }
return projectInfo;
};
- Session.prototype.getRenameInfo = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- return project.getLanguageService().getRenameInfo(file, position);
- };
- Session.prototype.getProjects = function (args) {
- var projects;
- if (args.projectFileName) {
- var project = this.getProject(args.projectFileName);
- if (project) {
- projects = [project];
- }
+ Session.prototype.getRenameLocations = function (line, offset, fileName, findInComments, findInStrings) {
+ var file = ts.normalizePath(fileName);
+ var info = this.projectService.getScriptInfo(file);
+ var projects = this.projectService.findReferencingProjects(info);
+ var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; });
+ if (projectsWithLanguageServiceEnabeld.length === 0) {
+ throw Errors.NoProject;
}
- else {
- var scriptInfo = this.projectService.getScriptInfo(args.file);
- projects = scriptInfo.containingProjects;
+ var defaultProject = projectsWithLanguageServiceEnabeld[0];
+ var defaultProjectCompilerService = defaultProject.compilerService;
+ var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset);
+ var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position);
+ if (!renameInfo) {
+ return undefined;
}
- projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; });
- if (!projects || !projects.length) {
- return server.Errors.ThrowNoProject();
+ if (!renameInfo.canRename) {
+ return {
+ info: renameInfo,
+ locs: []
+ };
}
- return projects;
- };
- Session.prototype.getRenameLocations = function (args, simplifiedResult) {
- var file = server.toNormalizedPath(args.file);
- var info = this.projectService.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, info);
- var projects = this.getProjects(args);
- if (simplifiedResult) {
- var defaultProject = projects[0];
- var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position);
- if (!renameInfo) {
- return undefined;
+ var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) {
+ var compilerService = project.compilerService;
+ var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments);
+ if (!renameLocations) {
+ return [];
}
- if (!renameInfo.canRename) {
- return {
- info: renameInfo,
- locs: []
- };
- }
- var fileSpans = server.combineProjectOutput(projects, function (project) {
- var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments);
- if (!renameLocations) {
- return [];
+ return renameLocations.map(function (location) { return ({
+ file: location.fileName,
+ start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start),
+ end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan))
+ }); });
+ }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; });
+ var locs = fileSpans.reduce(function (accum, cur) {
+ var curFileAccum;
+ if (accum.length > 0) {
+ curFileAccum = accum[accum.length - 1];
+ if (curFileAccum.file !== cur.file) {
+ curFileAccum = undefined;
}
- return renameLocations.map(function (location) {
- var locationScriptInfo = project.getScriptInfo(location.fileName);
- return {
- file: location.fileName,
- start: locationScriptInfo.positionToLineOffset(location.textSpan.start),
- end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan))
- };
- });
- }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; });
- var locs = fileSpans.reduce(function (accum, cur) {
- var curFileAccum;
- if (accum.length > 0) {
- curFileAccum = accum[accum.length - 1];
- if (curFileAccum.file !== cur.file) {
- curFileAccum = undefined;
- }
- }
- if (!curFileAccum) {
- curFileAccum = { file: cur.file, locs: [] };
- accum.push(curFileAccum);
- }
- curFileAccum.locs.push({ start: cur.start, end: cur.end });
- return accum;
- }, []);
- return { info: renameInfo, locs: locs };
- }
- else {
- return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo);
- }
- function renameLocationIsEqualTo(a, b) {
- if (a === b) {
- return true;
}
- if (!a || !b) {
- return false;
+ if (!curFileAccum) {
+ curFileAccum = { file: cur.file, locs: [] };
+ accum.push(curFileAccum);
}
- return a.fileName === b.fileName &&
- a.textSpan.start === b.textSpan.start &&
- a.textSpan.length === b.textSpan.length;
- }
+ curFileAccum.locs.push({ start: cur.start, end: cur.end });
+ return accum;
+ }, []);
+ return { info: renameInfo, locs: locs };
function compareRenameLocation(a, b) {
if (a.file < b.file) {
return -1;
@@ -63614,51 +60861,51 @@ var ts;
}
}
};
- Session.prototype.getReferences = function (args, simplifiedResult) {
- var file = server.toNormalizedPath(args.file);
- var projects = this.getProjects(args);
- var defaultProject = projects[0];
- var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- if (simplifiedResult) {
- var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position);
- if (!nameInfo) {
- return undefined;
+ Session.prototype.getReferences = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var info = this.projectService.getScriptInfo(file);
+ var projects = this.projectService.findReferencingProjects(info);
+ var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; });
+ if (projectsWithLanguageServiceEnabeld.length === 0) {
+ throw Errors.NoProject;
+ }
+ var defaultProject = projectsWithLanguageServiceEnabeld[0];
+ var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset);
+ var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position);
+ if (!nameInfo) {
+ return undefined;
+ }
+ var displayString = ts.displayPartsToString(nameInfo.displayParts);
+ var nameSpan = nameInfo.textSpan;
+ var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset;
+ var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan));
+ var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) {
+ var compilerService = project.compilerService;
+ var references = compilerService.languageService.getReferencesAtPosition(file, position);
+ if (!references) {
+ return [];
}
- var displayString = ts.displayPartsToString(nameInfo.displayParts);
- var nameSpan = nameInfo.textSpan;
- var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset;
- var nameText = scriptInfo.snap().getText(nameSpan.start, ts.textSpanEnd(nameSpan));
- var refs = server.combineProjectOutput(projects, function (project) {
- var references = project.getLanguageService().getReferencesAtPosition(file, position);
- if (!references) {
- return [];
- }
- return references.map(function (ref) {
- var refScriptInfo = project.getScriptInfo(ref.fileName);
- var start = refScriptInfo.positionToLineOffset(ref.textSpan.start);
- var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1);
- var lineText = refScriptInfo.snap().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, "");
- return {
- file: ref.fileName,
- start: start,
- lineText: lineText,
- end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)),
- isWriteAccess: ref.isWriteAccess,
- isDefinition: ref.isDefinition
- };
- });
- }, compareFileStart, areReferencesResponseItemsForTheSameLocation);
- return {
- refs: refs,
- symbolName: nameText,
- symbolStartOffset: nameColStart,
- symbolDisplayString: displayString
- };
- }
- else {
- return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined);
- }
+ return references.map(function (ref) {
+ var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start);
+ var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1);
+ var snap = compilerService.host.getScriptSnapshot(ref.fileName);
+ var lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, "");
+ return {
+ file: ref.fileName,
+ start: start,
+ lineText: lineText,
+ end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)),
+ isWriteAccess: ref.isWriteAccess,
+ isDefinition: ref.isDefinition
+ };
+ });
+ }, compareFileStart, areReferencesResponseItemsForTheSameLocation);
+ return {
+ refs: refs,
+ symbolName: nameText,
+ symbolStartOffset: nameColStart,
+ symbolDisplayString: displayString
+ };
function areReferencesResponseItemsForTheSameLocation(a, b) {
if (a && b) {
return a.file === b.file &&
@@ -63669,152 +60916,102 @@ var ts;
}
};
Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) {
- var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors;
+ var file = ts.normalizePath(fileName);
+ var _a = this.projectService.openClientFile(file, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors;
if (configFileErrors) {
this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors);
}
};
- Session.prototype.getPosition = function (args, scriptInfo) {
- return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset);
- };
- Session.prototype.getFileAndProject = function (args, errorOnMissingProject) {
- if (errorOnMissingProject === void 0) { errorOnMissingProject = true; }
- return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject);
- };
- Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) {
- if (errorOnMissingProject === void 0) { errorOnMissingProject = true; }
- return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject);
- };
- Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) {
- var file = server.toNormalizedPath(uncheckedFileName);
- var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects);
- if (!project && errorOnMissingProject) {
- return server.Errors.ThrowNoProject();
+ Session.prototype.getQuickInfo = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
}
- return { file: file, project: project };
- };
- Session.prototype.getOutliningSpans = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- return project.getLanguageService(false).getOutliningSpans(file);
- };
- Session.prototype.getTodoComments = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- return project.getLanguageService().getTodoComments(file, args.descriptors);
- };
- Session.prototype.getDocCommentTemplate = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position);
- };
- Session.prototype.getIndentation = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file));
- var options = args.options || this.projectService.getFormatCodeOptions(file);
- var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options);
- return { position: position, indentation: indentation };
- };
- Session.prototype.getBreakpointStatement = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file));
- return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position);
- };
- Session.prototype.getNameOrDottedNameSpan = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file));
- return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position);
- };
- Session.prototype.isValidBraceCompletion = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file));
- return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0));
- };
- Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo));
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position);
if (!quickInfo) {
return undefined;
}
- if (simplifiedResult) {
- var displayString = ts.displayPartsToString(quickInfo.displayParts);
- var docString = ts.displayPartsToString(quickInfo.documentation);
- return {
- kind: quickInfo.kind,
- kindModifiers: quickInfo.kindModifiers,
- start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start),
- end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)),
- displayString: displayString,
- documentation: docString
- };
- }
- else {
- return quickInfo;
- }
+ var displayString = ts.displayPartsToString(quickInfo.displayParts);
+ var docString = ts.displayPartsToString(quickInfo.documentation);
+ return {
+ kind: quickInfo.kind,
+ kindModifiers: quickInfo.kindModifiers,
+ start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start),
+ end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)),
+ displayString: displayString,
+ documentation: docString
+ };
};
- Session.prototype.getFormattingEditsForRange = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset);
- var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
- var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file));
+ Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var startPosition = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset);
+ var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file));
if (!edits) {
return undefined;
}
return edits.map(function (edit) {
return {
- start: scriptInfo.positionToLineOffset(edit.span.start),
- end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)),
+ start: compilerService.host.positionToLineOffset(file, edit.span.start),
+ end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)),
newText: edit.newText ? edit.newText : ""
};
});
};
- Session.prototype.getFormattingEditsForRangeFull = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var options = args.options || this.projectService.getFormatCodeOptions(file);
- return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options);
- };
- Session.prototype.getFormattingEditsForDocumentFull = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var options = args.options || this.projectService.getFormatCodeOptions(file);
- return project.getLanguageService(false).getFormattingEditsForDocument(file, options);
- };
- Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var options = args.options || this.projectService.getFormatCodeOptions(file);
- return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options);
- };
- Session.prototype.getFormattingEditsAfterKeystroke = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = scriptInfo.lineOffsetToPosition(args.line, args.offset);
+ Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
var formatOptions = this.projectService.getFormatCodeOptions(file);
- var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions);
- if ((args.key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) {
- var lineInfo = scriptInfo.getLineInfo(args.line);
- if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) {
- var lineText = lineInfo.leaf.text;
- if (lineText.search("\\S") < 0) {
- var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions);
- var hasIndent = 0;
- var i = void 0, len = void 0;
- for (i = 0, len = lineText.length; i < len; i++) {
- if (lineText.charAt(i) == " ") {
- hasIndent++;
+ var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions);
+ if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) {
+ var scriptInfo = compilerService.host.getScriptInfo(file);
+ if (scriptInfo) {
+ var lineInfo = scriptInfo.getLineInfo(line);
+ if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) {
+ var lineText = lineInfo.leaf.text;
+ if (lineText.search("\\S") < 0) {
+ var editorOptions = {
+ BaseIndentSize: formatOptions.BaseIndentSize,
+ IndentSize: formatOptions.IndentSize,
+ TabSize: formatOptions.TabSize,
+ NewLineCharacter: formatOptions.NewLineCharacter,
+ ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces,
+ IndentStyle: ts.IndentStyle.Smart
+ };
+ var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions);
+ var hasIndent = 0;
+ var i = void 0, len = void 0;
+ for (i = 0, len = lineText.length; i < len; i++) {
+ if (lineText.charAt(i) == " ") {
+ hasIndent++;
+ }
+ else if (lineText.charAt(i) == "\t") {
+ hasIndent += editorOptions.TabSize;
+ }
+ else {
+ break;
+ }
}
- else if (lineText.charAt(i) == "\t") {
- hasIndent += formatOptions.tabSize;
+ if (preferredIndent !== hasIndent) {
+ var firstNoWhiteSpacePosition = lineInfo.offset + i;
+ edits.push({
+ span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition),
+ newText: generateIndentString(preferredIndent, editorOptions)
+ });
}
- else {
- break;
- }
- }
- if (preferredIndent !== hasIndent) {
- var firstNoWhiteSpacePosition = lineInfo.offset + i;
- edits.push({
- span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition),
- newText: ts.formatting.getIndentationString(preferredIndent, formatOptions)
- });
}
}
}
@@ -63824,111 +61021,89 @@ var ts;
}
return edits.map(function (edit) {
return {
- start: scriptInfo.positionToLineOffset(edit.span.start),
- end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)),
+ start: compilerService.host.positionToLineOffset(file, edit.span.start),
+ end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)),
newText: edit.newText ? edit.newText : ""
};
});
};
- Session.prototype.getCompletions = function (args, simplifiedResult) {
- var prefix = args.prefix || "";
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var completions = project.getLanguageService().getCompletionsAtPosition(file, position);
+ Session.prototype.getCompletions = function (line, offset, prefix, fileName) {
+ if (!prefix) {
+ prefix = "";
+ }
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var completions = compilerService.languageService.getCompletionsAtPosition(file, position);
if (!completions) {
return undefined;
}
- if (simplifiedResult) {
- return completions.entries.reduce(function (result, entry) {
- if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) {
- var name_53 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan;
- var convertedSpan = undefined;
- if (replacementSpan) {
- convertedSpan = {
- start: scriptInfo.positionToLineOffset(replacementSpan.start),
- end: scriptInfo.positionToLineOffset(replacementSpan.start + replacementSpan.length)
- };
- }
- result.push({ name: name_53, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan });
+ return completions.entries.reduce(function (result, entry) {
+ if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) {
+ var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan;
+ var convertedSpan = undefined;
+ if (replacementSpan) {
+ convertedSpan = {
+ start: compilerService.host.positionToLineOffset(fileName, replacementSpan.start),
+ end: compilerService.host.positionToLineOffset(fileName, replacementSpan.start + replacementSpan.length)
+ };
}
- return result;
- }, []).sort(function (a, b) { return a.name.localeCompare(b.name); });
- }
- else {
- return completions;
- }
+ result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan });
+ }
+ return result;
+ }, []).sort(function (a, b) { return a.name.localeCompare(b.name); });
};
- Session.prototype.getCompletionEntryDetails = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- return args.entryNames.reduce(function (accum, entryName) {
- var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName);
+ Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ return entryNames.reduce(function (accum, entryName) {
+ var details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName);
if (details) {
accum.push(details);
}
return accum;
}, []);
};
- Session.prototype.getCompileOnSaveAffectedFileList = function (args) {
- var info = this.projectService.getScriptInfo(args.file);
- var result = [];
- if (!info) {
- return [];
+ Session.prototype.getSignatureHelpItems = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
}
- var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects;
- for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) {
- var project = projectsToSearch_1[_i];
- if (project.compileOnSaveEnabled && project.languageServiceEnabled) {
- result.push({
- projectFileName: project.getProjectName(),
- fileNames: project.getCompileOnSaveAffectedFileList(info)
- });
- }
- }
- return result;
- };
- Session.prototype.emitFile = function (args) {
- var _this = this;
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- if (!project) {
- server.Errors.ThrowNoProject();
- }
- var scriptInfo = project.getScriptInfo(file);
- return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); });
- };
- Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var helpItems = project.getLanguageService().getSignatureHelpItems(file, position);
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var helpItems = compilerService.languageService.getSignatureHelpItems(file, position);
if (!helpItems) {
return undefined;
}
- if (simplifiedResult) {
- var span_16 = helpItems.applicableSpan;
- return {
- items: helpItems.items,
- applicableSpan: {
- start: scriptInfo.positionToLineOffset(span_16.start),
- end: scriptInfo.positionToLineOffset(span_16.start + span_16.length)
- },
- selectedItemIndex: helpItems.selectedItemIndex,
- argumentIndex: helpItems.argumentIndex,
- argumentCount: helpItems.argumentCount
- };
- }
- else {
- return helpItems;
- }
+ var span = helpItems.applicableSpan;
+ var result = {
+ items: helpItems.items,
+ applicableSpan: {
+ start: compilerService.host.positionToLineOffset(file, span.start),
+ end: compilerService.host.positionToLineOffset(file, span.start + span.length)
+ },
+ selectedItemIndex: helpItems.selectedItemIndex,
+ argumentIndex: helpItems.argumentIndex,
+ argumentCount: helpItems.argumentCount
+ };
+ return result;
};
Session.prototype.getDiagnostics = function (delay, fileNames) {
var _this = this;
- var checkList = fileNames.reduce(function (accum, uncheckedFileName) {
- var fileName = server.toNormalizedPath(uncheckedFileName);
- var project = _this.projectService.getDefaultProjectForFile(fileName, true);
- if (project) {
+ var checkList = fileNames.reduce(function (accum, fileName) {
+ fileName = ts.normalizePath(fileName);
+ var project = _this.projectService.getProjectForFile(fileName);
+ if (project && !project.languageServiceDiabled) {
accum.push({ fileName: fileName, project: project });
}
return accum;
@@ -63937,34 +61112,40 @@ var ts;
this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay);
}
};
- Session.prototype.change = function (args) {
+ Session.prototype.change = function (line, offset, endLine, endOffset, insertString, fileName) {
var _this = this;
- var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project;
- if (project) {
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var start = scriptInfo.lineOffsetToPosition(args.line, args.offset);
- var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (project && !project.languageServiceDiabled) {
+ var compilerService = project.compilerService;
+ var start = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset);
if (start >= 0) {
- scriptInfo.editContent(start, end, args.insertString);
+ compilerService.host.editScript(file, start, end, insertString);
this.changeSeq++;
}
this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; });
}
};
- Session.prototype.reload = function (args, reqSeq) {
- var file = server.toNormalizedPath(args.file);
- var project = this.projectService.getDefaultProjectForFile(file, true);
- if (project) {
+ Session.prototype.reload = function (fileName, tempFileName, reqSeq) {
+ var _this = this;
+ if (reqSeq === void 0) { reqSeq = 0; }
+ var file = ts.normalizePath(fileName);
+ var tmpfile = ts.normalizePath(tempFileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (project && !project.languageServiceDiabled) {
this.changeSeq++;
- if (project.reloadScript(file)) {
- this.output(undefined, CommandNames.Reload, reqSeq);
- }
+ project.compilerService.host.reloadScript(file, tmpfile, function () {
+ _this.output(undefined, CommandNames.Reload, reqSeq);
+ });
}
};
Session.prototype.saveToTmp = function (fileName, tempFileName) {
- var scriptInfo = this.projectService.getScriptInfo(fileName);
- if (scriptInfo) {
- scriptInfo.saveTo(tempFileName);
+ var file = ts.normalizePath(fileName);
+ var tmpfile = ts.normalizePath(tempFileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (project && !project.languageServiceDiabled) {
+ project.compilerService.host.saveTo(file, tmpfile);
}
};
Session.prototype.closeClientFile = function (fileName) {
@@ -63974,91 +61155,77 @@ var ts;
var file = ts.normalizePath(fileName);
this.projectService.closeClientFile(file);
};
- Session.prototype.decorateNavigationBarItem = function (project, fileName, items) {
+ Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) {
var _this = this;
if (!items) {
return undefined;
}
- var scriptInfo = project.getScriptInfoForNormalizedPath(fileName);
+ var compilerService = project.compilerService;
return items.map(function (item) { return ({
text: item.text,
kind: item.kind,
kindModifiers: item.kindModifiers,
spans: item.spans.map(function (span) { return ({
- start: scriptInfo.positionToLineOffset(span.start),
- end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span))
+ start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex),
+ end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex)
}); }),
- childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems),
+ childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex),
indent: item.indent
}); });
};
- Session.prototype.getNavigationBarItems = function (args, simplifiedResult) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var items = project.getLanguageService().getNavigationBarItems(file);
+ Session.prototype.getNavigationBarItems = function (fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var items = compilerService.languageService.getNavigationBarItems(file);
if (!items) {
return undefined;
}
- return simplifiedResult
- ? this.decorateNavigationBarItem(project, file, items)
- : items;
+ return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName));
};
- Session.prototype.getNavigateToItems = function (args, simplifiedResult) {
- var projects = this.getProjects(args);
- var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined;
- if (simplifiedResult) {
- return server.combineProjectOutput(projects, function (project) {
- var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isJsOnlyProject());
- if (!navItems) {
- return [];
+ Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount, currentFileOnly) {
+ var file = ts.normalizePath(fileName);
+ var info = this.projectService.getScriptInfo(file);
+ var projects = this.projectService.findReferencingProjects(info);
+ var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; });
+ if (projectsWithLanguageServiceEnabeld.length === 0) {
+ throw Errors.NoProject;
+ }
+ var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) {
+ var compilerService = project.compilerService;
+ var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount, currentFileOnly ? fileName : undefined);
+ if (!navItems) {
+ return [];
+ }
+ return navItems.map(function (navItem) {
+ var start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start);
+ var end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan));
+ var bakedItem = {
+ name: navItem.name,
+ kind: navItem.kind,
+ file: navItem.fileName,
+ start: start,
+ end: end
+ };
+ if (navItem.kindModifiers && (navItem.kindModifiers !== "")) {
+ bakedItem.kindModifiers = navItem.kindModifiers;
}
- return navItems.map(function (navItem) {
- var scriptInfo = project.getScriptInfo(navItem.fileName);
- var start = scriptInfo.positionToLineOffset(navItem.textSpan.start);
- var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan));
- var bakedItem = {
- name: navItem.name,
- kind: navItem.kind,
- file: navItem.fileName,
- start: start,
- end: end
- };
- if (navItem.kindModifiers && (navItem.kindModifiers !== "")) {
- bakedItem.kindModifiers = navItem.kindModifiers;
- }
- if (navItem.matchKind !== "none") {
- bakedItem.matchKind = navItem.matchKind;
- }
- if (navItem.containerName && (navItem.containerName.length > 0)) {
- bakedItem.containerName = navItem.containerName;
- }
- if (navItem.containerKind && (navItem.containerKind.length > 0)) {
- bakedItem.containerKind = navItem.containerKind;
- }
- return bakedItem;
- });
- }, undefined, areNavToItemsForTheSameLocation);
- }
- else {
- return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isJsOnlyProject()); }, undefined, navigateToItemIsEqualTo);
- }
- function navigateToItemIsEqualTo(a, b) {
- if (a === b) {
- return true;
- }
- if (!a || !b) {
- return false;
- }
- return a.containerKind === b.containerKind &&
- a.containerName === b.containerName &&
- a.fileName === b.fileName &&
- a.isCaseSensitive === b.isCaseSensitive &&
- a.kind === b.kind &&
- a.kindModifiers === b.containerName &&
- a.matchKind === b.matchKind &&
- a.name === b.name &&
- a.textSpan.start === b.textSpan.start &&
- a.textSpan.length === b.textSpan.length;
- }
+ if (navItem.matchKind !== "none") {
+ bakedItem.matchKind = navItem.matchKind;
+ }
+ if (navItem.containerName && (navItem.containerName.length > 0)) {
+ bakedItem.containerName = navItem.containerName;
+ }
+ if (navItem.containerKind && (navItem.containerKind.length > 0)) {
+ bakedItem.containerKind = navItem.containerKind;
+ }
+ return bakedItem;
+ });
+ }, undefined, areNavToItemsForTheSameLocation);
+ return allNavToItems;
function areNavToItemsForTheSameLocation(a, b) {
if (a && b) {
return a.file === b.file &&
@@ -64068,27 +61235,26 @@ var ts;
return false;
}
};
- Session.prototype.getBraceMatching = function (args, simplifiedResult) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position);
+ Session.prototype.getBraceMatching = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var spans = compilerService.languageService.getBraceMatchingAtPosition(file, position);
if (!spans) {
return undefined;
}
- if (simplifiedResult) {
- return spans.map(function (span) { return ({
- start: scriptInfo.positionToLineOffset(span.start),
- end: scriptInfo.positionToLineOffset(span.start + span.length)
- }); });
- }
- else {
- return spans;
- }
+ return spans.map(function (span) { return ({
+ start: compilerService.host.positionToLineOffset(file, span.start),
+ end: compilerService.host.positionToLineOffset(file, span.start + span.length)
+ }); });
};
Session.prototype.getDiagnosticsForProject = function (delay, fileName) {
var _this = this;
- var _a = this.getProjectInfoWorker(fileName, undefined, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled;
+ var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled;
if (languageServiceDisabled) {
return;
}
@@ -64097,8 +61263,8 @@ var ts;
var mediumPriorityFiles = [];
var lowPriorityFiles = [];
var veryLowPriorityFiles = [];
- var normalizedFileName = server.toNormalizedPath(fileName);
- var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true);
+ var normalizedFileName = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(normalizedFileName);
for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) {
var fileNameInProject = fileNamesInProject_1[_i];
if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName))
@@ -64117,7 +61283,10 @@ var ts;
}
fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles);
if (fileNamesInProject.length > 0) {
- var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); });
+ var checkList = fileNamesInProject.map(function (fileName) {
+ var normalizedFileName = ts.normalizePath(fileName);
+ return { fileName: normalizedFileName, project: project };
+ });
this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n == _this.changeSeq; }, delay, 200, false);
}
};
@@ -64127,9 +61296,6 @@ var ts;
};
Session.prototype.exit = function () {
};
- Session.prototype.notRequired = function () {
- return { responseRequired: false };
- };
Session.prototype.requiredResponse = function (response) {
return { response: response, responseRequired: true };
};
@@ -64145,32 +61311,31 @@ var ts;
return handler(request);
}
else {
- this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err);
+ this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request));
this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command);
return { responseRequired: false };
}
};
Session.prototype.onMessage = function (message) {
- this.gcTimer.scheduleCollect();
var start;
- if (this.logger.hasLevel(server.LogLevel.requestTime)) {
+ if (this.logger.isVerbose()) {
+ this.logger.info("request: " + message);
start = this.hrtime();
- if (this.logger.hasLevel(server.LogLevel.verbose)) {
- this.logger.info("request: " + message);
- }
}
var request;
try {
request = JSON.parse(message);
var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired;
- if (this.logger.hasLevel(server.LogLevel.requestTime)) {
- var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4);
- if (responseRequired) {
- this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime);
- }
- else {
- this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime);
+ if (this.logger.isVerbose()) {
+ var elapsed = this.hrtime(start);
+ var seconds = elapsed[0];
+ var nanoseconds = elapsed[1];
+ var elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0;
+ var leader = "Elapsed time (in milliseconds)";
+ if (!responseRequired) {
+ leader = "Async elapsed time (in milliseconds)";
}
+ this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf");
}
if (response) {
this.output(response, request.command, request.seq);
@@ -64181,8 +61346,6 @@ var ts;
}
catch (err) {
if (err instanceof ts.OperationCanceledException) {
- this.output({ canceled: true }, request.command, request.seq);
- return;
}
this.logError(err, message);
this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack);
@@ -64198,6 +61361,1229 @@ var ts;
var server;
(function (server) {
var lineCollectionCapacity = 4;
+ function mergeFormatOptions(formatCodeOptions, formatOptions) {
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
+ Object.keys(formatOptions).forEach(function (key) {
+ var codeKey = key.charAt(0).toUpperCase() + key.substring(1);
+ if (hasOwnProperty.call(formatCodeOptions, codeKey)) {
+ formatCodeOptions[codeKey] = formatOptions[key];
+ }
+ });
+ }
+ server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
+ var ScriptInfo = (function () {
+ function ScriptInfo(host, fileName, content, isOpen) {
+ if (isOpen === void 0) { isOpen = false; }
+ this.host = host;
+ this.fileName = fileName;
+ this.isOpen = isOpen;
+ this.children = [];
+ this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host));
+ this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
+ this.svc = ScriptVersionCache.fromString(host, content);
+ }
+ ScriptInfo.prototype.setFormatOptions = function (formatOptions) {
+ if (formatOptions) {
+ mergeFormatOptions(this.formatCodeOptions, formatOptions);
+ }
+ };
+ ScriptInfo.prototype.close = function () {
+ this.isOpen = false;
+ };
+ ScriptInfo.prototype.addChild = function (childInfo) {
+ this.children.push(childInfo);
+ };
+ ScriptInfo.prototype.snap = function () {
+ return this.svc.getSnapshot();
+ };
+ ScriptInfo.prototype.getText = function () {
+ var snap = this.snap();
+ return snap.getText(0, snap.getLength());
+ };
+ ScriptInfo.prototype.getLineInfo = function (line) {
+ var snap = this.snap();
+ return snap.index.lineNumberToInfo(line);
+ };
+ ScriptInfo.prototype.editContent = function (start, end, newText) {
+ this.svc.edit(start, end - start, newText);
+ };
+ ScriptInfo.prototype.getTextChangeRangeBetweenVersions = function (startVersion, endVersion) {
+ return this.svc.getTextChangesBetweenVersions(startVersion, endVersion);
+ };
+ ScriptInfo.prototype.getChangeRange = function (oldSnapshot) {
+ return this.snap().getChangeRange(oldSnapshot);
+ };
+ return ScriptInfo;
+ }());
+ server.ScriptInfo = ScriptInfo;
+ var LSHost = (function () {
+ function LSHost(host, project) {
+ var _this = this;
+ this.host = host;
+ this.project = project;
+ this.roots = [];
+ this.getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
+ this.resolvedModuleNames = ts.createFileMap();
+ this.resolvedTypeReferenceDirectives = ts.createFileMap();
+ this.filenameToScript = ts.createFileMap();
+ this.moduleResolutionHost = {
+ fileExists: function (fileName) { return _this.fileExists(fileName); },
+ readFile: function (fileName) { return _this.host.readFile(fileName); },
+ directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); }
+ };
+ if (this.host.realpath) {
+ this.moduleResolutionHost.realpath = function (path) { return _this.host.realpath(path); };
+ }
+ }
+ LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) {
+ var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName);
+ var currentResolutionsInFile = cache.get(path);
+ var newResolutions = ts.createMap();
+ var resolvedModules = [];
+ var compilerOptions = this.getCompilationSettings();
+ for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
+ var name_53 = names_3[_i];
+ var resolution = newResolutions[name_53];
+ if (!resolution) {
+ var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_53];
+ if (moduleResolutionIsValid(existingResolution)) {
+ resolution = existingResolution;
+ }
+ else {
+ resolution = loader(name_53, containingFile, compilerOptions, this.moduleResolutionHost);
+ resolution.lastCheckTime = Date.now();
+ newResolutions[name_53] = resolution;
+ }
+ }
+ ts.Debug.assert(resolution !== undefined);
+ resolvedModules.push(getResult(resolution));
+ }
+ cache.set(path, newResolutions);
+ return resolvedModules;
+ function moduleResolutionIsValid(resolution) {
+ if (!resolution) {
+ return false;
+ }
+ if (getResult(resolution)) {
+ return true;
+ }
+ return resolution.failedLookupLocations.length === 0;
+ }
+ };
+ LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
+ return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; });
+ };
+ LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) {
+ return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, ts.resolveModuleName, function (m) { return m.resolvedModule; });
+ };
+ LSHost.prototype.getDefaultLibFileName = function () {
+ var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath()));
+ return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings));
+ };
+ LSHost.prototype.getScriptSnapshot = function (filename) {
+ var scriptInfo = this.getScriptInfo(filename);
+ if (scriptInfo) {
+ return scriptInfo.snap();
+ }
+ };
+ LSHost.prototype.setCompilationSettings = function (opt) {
+ this.compilationSettings = opt;
+ this.resolvedModuleNames.clear();
+ this.resolvedTypeReferenceDirectives.clear();
+ };
+ LSHost.prototype.lineAffectsRefs = function (filename, line) {
+ var info = this.getScriptInfo(filename);
+ var lineInfo = info.getLineInfo(line);
+ if (lineInfo && lineInfo.text) {
+ var regex = /reference|import|\/\*|\*\//;
+ return regex.test(lineInfo.text);
+ }
+ };
+ LSHost.prototype.getCompilationSettings = function () {
+ return this.compilationSettings;
+ };
+ LSHost.prototype.getScriptFileNames = function () {
+ return this.roots.map(function (root) { return root.fileName; });
+ };
+ LSHost.prototype.getScriptKind = function (fileName) {
+ var info = this.getScriptInfo(fileName);
+ if (!info) {
+ return undefined;
+ }
+ if (!info.scriptKind) {
+ info.scriptKind = ts.getScriptKindFromFileName(fileName);
+ }
+ return info.scriptKind;
+ };
+ LSHost.prototype.getScriptVersion = function (filename) {
+ return this.getScriptInfo(filename).svc.latestVersion().toString();
+ };
+ LSHost.prototype.getCurrentDirectory = function () {
+ return "";
+ };
+ LSHost.prototype.getScriptIsOpen = function (filename) {
+ return this.getScriptInfo(filename).isOpen;
+ };
+ LSHost.prototype.removeReferencedFile = function (info) {
+ if (!info.isOpen) {
+ this.filenameToScript.remove(info.path);
+ this.resolvedModuleNames.remove(info.path);
+ this.resolvedTypeReferenceDirectives.remove(info.path);
+ }
+ };
+ LSHost.prototype.getScriptInfo = function (filename) {
+ var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
+ var scriptInfo = this.filenameToScript.get(path);
+ if (!scriptInfo) {
+ scriptInfo = this.project.openReferencedFile(filename);
+ if (scriptInfo) {
+ this.filenameToScript.set(path, scriptInfo);
+ }
+ }
+ return scriptInfo;
+ };
+ LSHost.prototype.addRoot = function (info) {
+ if (!this.filenameToScript.contains(info.path)) {
+ this.filenameToScript.set(info.path, info);
+ this.roots.push(info);
+ }
+ };
+ LSHost.prototype.removeRoot = function (info) {
+ if (this.filenameToScript.contains(info.path)) {
+ this.filenameToScript.remove(info.path);
+ ts.unorderedRemoveItem(this.roots, info);
+ this.resolvedModuleNames.remove(info.path);
+ this.resolvedTypeReferenceDirectives.remove(info.path);
+ }
+ };
+ LSHost.prototype.saveTo = function (filename, tmpfilename) {
+ var script = this.getScriptInfo(filename);
+ if (script) {
+ var snap = script.snap();
+ this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength()));
+ }
+ };
+ LSHost.prototype.reloadScript = function (filename, tmpfilename, cb) {
+ var script = this.getScriptInfo(filename);
+ if (script) {
+ script.svc.reloadFromFile(tmpfilename, cb);
+ }
+ };
+ LSHost.prototype.editScript = function (filename, start, end, newText) {
+ var script = this.getScriptInfo(filename);
+ if (script) {
+ script.editContent(start, end, newText);
+ return;
+ }
+ throw new Error("No script with name '" + filename + "'");
+ };
+ LSHost.prototype.fileExists = function (path) {
+ var result = this.host.fileExists(path);
+ return result;
+ };
+ LSHost.prototype.directoryExists = function (path) {
+ return this.host.directoryExists(path);
+ };
+ LSHost.prototype.getDirectories = function (path) {
+ return this.host.getDirectories(path);
+ };
+ LSHost.prototype.readDirectory = function (path, extensions, exclude, include) {
+ return this.host.readDirectory(path, extensions, exclude, include);
+ };
+ LSHost.prototype.readFile = function (path, encoding) {
+ return this.host.readFile(path, encoding);
+ };
+ LSHost.prototype.lineToTextSpan = function (filename, line) {
+ var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
+ var script = this.filenameToScript.get(path);
+ var index = script.snap().index;
+ var lineInfo = index.lineNumberToInfo(line + 1);
+ var len;
+ if (lineInfo.leaf) {
+ len = lineInfo.leaf.text.length;
+ }
+ else {
+ var nextLineInfo = index.lineNumberToInfo(line + 2);
+ len = nextLineInfo.offset - lineInfo.offset;
+ }
+ return ts.createTextSpan(lineInfo.offset, len);
+ };
+ LSHost.prototype.lineOffsetToPosition = function (filename, line, offset) {
+ var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
+ var script = this.filenameToScript.get(path);
+ var index = script.snap().index;
+ var lineInfo = index.lineNumberToInfo(line);
+ return (lineInfo.offset + offset - 1);
+ };
+ LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) {
+ lineIndex = lineIndex || this.getLineIndex(filename);
+ var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position);
+ return { line: lineOffset.line, offset: lineOffset.offset + 1 };
+ };
+ LSHost.prototype.getLineIndex = function (filename) {
+ var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
+ var script = this.filenameToScript.get(path);
+ return script.snap().index;
+ };
+ return LSHost;
+ }());
+ server.LSHost = LSHost;
+ var Project = (function () {
+ function Project(projectService, projectOptions, languageServiceDiabled) {
+ if (languageServiceDiabled === void 0) { languageServiceDiabled = false; }
+ this.projectService = projectService;
+ this.projectOptions = projectOptions;
+ this.languageServiceDiabled = languageServiceDiabled;
+ this.directoriesWatchedForTsconfig = [];
+ this.filenameToSourceFile = ts.createMap();
+ this.updateGraphSeq = 0;
+ this.openRefCount = 0;
+ if (projectOptions && projectOptions.files) {
+ projectOptions.compilerOptions.allowNonTsExtensions = true;
+ }
+ if (!languageServiceDiabled) {
+ this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions);
+ }
+ }
+ Project.prototype.enableLanguageService = function () {
+ if (this.languageServiceDiabled) {
+ this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions);
+ }
+ this.languageServiceDiabled = false;
+ };
+ Project.prototype.disableLanguageService = function () {
+ this.languageServiceDiabled = true;
+ };
+ Project.prototype.addOpenRef = function () {
+ this.openRefCount++;
+ };
+ Project.prototype.deleteOpenRef = function () {
+ this.openRefCount--;
+ return this.openRefCount;
+ };
+ Project.prototype.openReferencedFile = function (filename) {
+ return this.projectService.openFile(filename, false);
+ };
+ Project.prototype.getRootFiles = function () {
+ if (this.languageServiceDiabled) {
+ return this.projectOptions ? this.projectOptions.files : undefined;
+ }
+ return this.compilerService.host.roots.map(function (info) { return info.fileName; });
+ };
+ Project.prototype.getFileNames = function () {
+ if (this.languageServiceDiabled) {
+ if (!this.projectOptions) {
+ return undefined;
+ }
+ var fileNames = [];
+ if (this.projectOptions && this.projectOptions.compilerOptions) {
+ fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions));
+ }
+ ts.addRange(fileNames, this.projectOptions.files);
+ return fileNames;
+ }
+ var sourceFiles = this.program.getSourceFiles();
+ return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; });
+ };
+ Project.prototype.getSourceFile = function (info) {
+ if (this.languageServiceDiabled) {
+ return undefined;
+ }
+ return this.filenameToSourceFile[info.fileName];
+ };
+ Project.prototype.getSourceFileFromName = function (filename, requireOpen) {
+ if (this.languageServiceDiabled) {
+ return undefined;
+ }
+ var info = this.projectService.getScriptInfo(filename);
+ if (info) {
+ if ((!requireOpen) || info.isOpen) {
+ return this.getSourceFile(info);
+ }
+ }
+ };
+ Project.prototype.isRoot = function (info) {
+ if (this.languageServiceDiabled) {
+ return undefined;
+ }
+ return this.compilerService.host.roots.some(function (root) { return root === info; });
+ };
+ Project.prototype.removeReferencedFile = function (info) {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.compilerService.host.removeReferencedFile(info);
+ this.updateGraph();
+ };
+ Project.prototype.updateFileMap = function () {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.filenameToSourceFile = ts.createMap();
+ var sourceFiles = this.program.getSourceFiles();
+ for (var i = 0, len = sourceFiles.length; i < len; i++) {
+ var normFilename = ts.normalizePath(sourceFiles[i].fileName);
+ this.filenameToSourceFile[normFilename] = sourceFiles[i];
+ }
+ };
+ Project.prototype.finishGraph = function () {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.updateGraph();
+ this.compilerService.languageService.getNavigateToItems(".*");
+ };
+ Project.prototype.updateGraph = function () {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.program = this.compilerService.languageService.getProgram();
+ this.updateFileMap();
+ };
+ Project.prototype.isConfiguredProject = function () {
+ return this.projectFilename;
+ };
+ Project.prototype.addRoot = function (info) {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.compilerService.host.addRoot(info);
+ };
+ Project.prototype.removeRoot = function (info) {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.compilerService.host.removeRoot(info);
+ };
+ Project.prototype.filesToString = function () {
+ if (this.languageServiceDiabled) {
+ if (this.projectOptions) {
+ var strBuilder_1 = "";
+ ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; });
+ return strBuilder_1;
+ }
+ }
+ var strBuilder = "";
+ ts.forEachProperty(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; });
+ return strBuilder;
+ };
+ Project.prototype.setProjectOptions = function (projectOptions) {
+ this.projectOptions = projectOptions;
+ if (projectOptions.compilerOptions) {
+ projectOptions.compilerOptions.allowNonTsExtensions = true;
+ if (!this.languageServiceDiabled) {
+ this.compilerService.setCompilerOptions(projectOptions.compilerOptions);
+ }
+ }
+ };
+ return Project;
+ }());
+ server.Project = Project;
+ function combineProjectOutput(projects, action, comparer, areEqual) {
+ var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer);
+ return projects.length > 1 ? ts.deduplicate(result, areEqual) : result;
+ }
+ server.combineProjectOutput = combineProjectOutput;
+ var ProjectService = (function () {
+ function ProjectService(host, psLogger, eventHandler) {
+ this.host = host;
+ this.psLogger = psLogger;
+ this.eventHandler = eventHandler;
+ this.filenameToScriptInfo = ts.createMap();
+ this.openFileRoots = [];
+ this.inferredProjects = [];
+ this.configuredProjects = [];
+ this.openFilesReferenced = [];
+ this.openFileRootsConfigured = [];
+ this.directoryWatchersForTsconfig = ts.createMap();
+ this.directoryWatchersRefCount = ts.createMap();
+ this.timerForDetectingProjectFileListChanges = ts.createMap();
+ this.addDefaultHostConfiguration();
+ }
+ ProjectService.prototype.addDefaultHostConfiguration = function () {
+ this.hostConfiguration = {
+ formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)),
+ hostInfo: "Unknown host"
+ };
+ };
+ ProjectService.prototype.getFormatCodeOptions = function (file) {
+ if (file) {
+ var info = this.filenameToScriptInfo[file];
+ if (info) {
+ return info.formatCodeOptions;
+ }
+ }
+ return this.hostConfiguration.formatCodeOptions;
+ };
+ ProjectService.prototype.watchedFileChanged = function (fileName) {
+ var info = this.filenameToScriptInfo[fileName];
+ if (!info) {
+ this.psLogger.info("Error: got watch notification for unknown file: " + fileName);
+ }
+ if (!this.host.fileExists(fileName)) {
+ this.fileDeletedInFilesystem(info);
+ }
+ else {
+ if (info && (!info.isOpen)) {
+ info.svc.reloadFromFile(info.fileName);
+ }
+ }
+ };
+ ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) {
+ if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) {
+ return;
+ }
+ this.log("Detected source file changes: " + fileName);
+ this.startTimerForDetectingProjectFileListChanges(project);
+ };
+ ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) {
+ var _this = this;
+ if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) {
+ this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]);
+ }
+ this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250);
+ };
+ ProjectService.prototype.handleProjectFileListChanges = function (project) {
+ var _this = this;
+ var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors;
+ this.reportConfigFileDiagnostics(project.projectFilename, errors);
+ var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); }));
+ var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); }));
+ if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) {
+ this.updateConfiguredProject(project);
+ this.updateProjectStructure();
+ }
+ };
+ ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) {
+ if (diagnostics && diagnostics.length > 0) {
+ this.eventHandler({
+ eventName: "configFileDiag",
+ data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile }
+ });
+ }
+ };
+ ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) {
+ var _this = this;
+ if (ts.getBaseFileName(fileName) !== "tsconfig.json") {
+ this.log(fileName + " is not tsconfig.json");
+ return;
+ }
+ this.log("Detected newly added tsconfig file: " + fileName);
+ var _a = this.configFileToProjectOptions(fileName), projectOptions = _a.projectOptions, errors = _a.errors;
+ this.reportConfigFileDiagnostics(fileName, errors);
+ if (!projectOptions) {
+ return;
+ }
+ var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); });
+ var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); });
+ for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) {
+ var openFileRoot = openFileRoots_1[_i];
+ if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) {
+ this.reloadProjects();
+ return;
+ }
+ }
+ };
+ ProjectService.prototype.getCanonicalFileName = function (fileName) {
+ var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
+ return ts.normalizePath(name);
+ };
+ ProjectService.prototype.watchedProjectConfigFileChanged = function (project) {
+ this.log("Config file changed: " + project.projectFilename);
+ var configFileErrors = this.updateConfiguredProject(project);
+ this.updateProjectStructure();
+ if (configFileErrors && configFileErrors.length > 0) {
+ this.eventHandler({ eventName: "configFileDiag", data: { triggerFile: project.projectFilename, configFileName: project.projectFilename, diagnostics: configFileErrors } });
+ }
+ };
+ ProjectService.prototype.log = function (msg, type) {
+ if (type === void 0) { type = "Err"; }
+ this.psLogger.msg(msg, type);
+ };
+ ProjectService.prototype.setHostConfiguration = function (args) {
+ if (args.file) {
+ var info = this.filenameToScriptInfo[args.file];
+ if (info) {
+ info.setFormatOptions(args.formatOptions);
+ this.log("Host configuration update for file " + args.file, "Info");
+ }
+ }
+ else {
+ if (args.hostInfo !== undefined) {
+ this.hostConfiguration.hostInfo = args.hostInfo;
+ this.log("Host information " + args.hostInfo, "Info");
+ }
+ if (args.formatOptions) {
+ mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions);
+ this.log("Format host information updated", "Info");
+ }
+ }
+ };
+ ProjectService.prototype.closeLog = function () {
+ this.psLogger.close();
+ };
+ ProjectService.prototype.createInferredProject = function (root) {
+ var _this = this;
+ var project = new Project(this);
+ project.addRoot(root);
+ var currentPath = ts.getDirectoryPath(root.fileName);
+ var parentPath = ts.getDirectoryPath(currentPath);
+ while (currentPath != parentPath) {
+ if (!project.projectService.directoryWatchersForTsconfig[currentPath]) {
+ this.log("Add watcher for: " + currentPath);
+ project.projectService.directoryWatchersForTsconfig[currentPath] =
+ this.host.watchDirectory(currentPath, function (fileName) { return _this.directoryWatchedForTsconfigChanged(fileName); });
+ project.projectService.directoryWatchersRefCount[currentPath] = 1;
+ }
+ else {
+ project.projectService.directoryWatchersRefCount[currentPath] += 1;
+ }
+ project.directoriesWatchedForTsconfig.push(currentPath);
+ currentPath = parentPath;
+ parentPath = ts.getDirectoryPath(parentPath);
+ }
+ project.finishGraph();
+ this.inferredProjects.push(project);
+ return project;
+ };
+ ProjectService.prototype.fileDeletedInFilesystem = function (info) {
+ this.psLogger.info(info.fileName + " deleted");
+ if (info.fileWatcher) {
+ info.fileWatcher.close();
+ info.fileWatcher = undefined;
+ }
+ if (!info.isOpen) {
+ this.filenameToScriptInfo[info.fileName] = undefined;
+ var referencingProjects = this.findReferencingProjects(info);
+ if (info.defaultProject) {
+ info.defaultProject.removeRoot(info);
+ }
+ for (var i = 0, len = referencingProjects.length; i < len; i++) {
+ referencingProjects[i].removeReferencedFile(info);
+ }
+ for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) {
+ var openFile = this.openFileRoots[j];
+ if (this.eventHandler) {
+ this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } });
+ }
+ }
+ for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) {
+ var openFile = this.openFilesReferenced[j];
+ if (this.eventHandler) {
+ this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } });
+ }
+ }
+ }
+ this.printProjects();
+ };
+ ProjectService.prototype.updateConfiguredProjectList = function () {
+ var configuredProjects = [];
+ for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
+ if (this.configuredProjects[i].openRefCount > 0) {
+ configuredProjects.push(this.configuredProjects[i]);
+ }
+ }
+ this.configuredProjects = configuredProjects;
+ };
+ ProjectService.prototype.removeProject = function (project) {
+ this.log("remove project: " + project.getRootFiles().toString());
+ if (project.isConfiguredProject()) {
+ project.projectFileWatcher.close();
+ project.directoryWatcher.close();
+ ts.forEachProperty(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); });
+ delete project.directoriesWatchedForWildcards;
+ ts.unorderedRemoveItem(this.configuredProjects, project);
+ }
+ else {
+ for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) {
+ var directory = _a[_i];
+ project.projectService.directoryWatchersRefCount[directory]--;
+ if (!project.projectService.directoryWatchersRefCount[directory]) {
+ this.log("Close directory watcher for: " + directory);
+ project.projectService.directoryWatchersForTsconfig[directory].close();
+ delete project.projectService.directoryWatchersForTsconfig[directory];
+ }
+ }
+ ts.unorderedRemoveItem(this.inferredProjects, project);
+ }
+ var fileNames = project.getFileNames();
+ for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) {
+ var fileName = fileNames_3[_b];
+ var info = this.getScriptInfo(fileName);
+ if (info.defaultProject == project) {
+ info.defaultProject = undefined;
+ }
+ }
+ };
+ ProjectService.prototype.setConfiguredProjectRoot = function (info) {
+ for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
+ var configuredProject = this.configuredProjects[i];
+ if (configuredProject.isRoot(info)) {
+ info.defaultProject = configuredProject;
+ configuredProject.addOpenRef();
+ return true;
+ }
+ }
+ return false;
+ };
+ ProjectService.prototype.addOpenFile = function (info) {
+ if (this.setConfiguredProjectRoot(info)) {
+ this.openFileRootsConfigured.push(info);
+ }
+ else {
+ this.findReferencingProjects(info);
+ if (info.defaultProject) {
+ info.defaultProject.addOpenRef();
+ this.openFilesReferenced.push(info);
+ }
+ else {
+ info.defaultProject = this.createInferredProject(info);
+ var openFileRoots = [];
+ for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
+ var r = this.openFileRoots[i];
+ if (info.defaultProject.getSourceFile(r)) {
+ this.removeProject(r.defaultProject);
+ this.openFilesReferenced.push(r);
+ r.defaultProject = info.defaultProject;
+ }
+ else {
+ openFileRoots.push(r);
+ }
+ }
+ this.openFileRoots = openFileRoots;
+ this.openFileRoots.push(info);
+ }
+ }
+ this.updateConfiguredProjectList();
+ };
+ ProjectService.prototype.closeOpenFile = function (info) {
+ info.svc.reloadFromFile(info.fileName);
+ var openFileRoots = [];
+ var removedProject;
+ for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
+ if (info === this.openFileRoots[i]) {
+ removedProject = info.defaultProject;
+ }
+ else {
+ openFileRoots.push(this.openFileRoots[i]);
+ }
+ }
+ this.openFileRoots = openFileRoots;
+ if (!removedProject) {
+ var openFileRootsConfigured = [];
+ for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) {
+ if (info === this.openFileRootsConfigured[i]) {
+ if (info.defaultProject.deleteOpenRef() === 0) {
+ removedProject = info.defaultProject;
+ }
+ }
+ else {
+ openFileRootsConfigured.push(this.openFileRootsConfigured[i]);
+ }
+ }
+ this.openFileRootsConfigured = openFileRootsConfigured;
+ }
+ if (removedProject) {
+ this.removeProject(removedProject);
+ var openFilesReferenced = [];
+ var orphanFiles = [];
+ for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) {
+ var f = this.openFilesReferenced[i];
+ if (f.defaultProject === removedProject || !f.defaultProject) {
+ f.defaultProject = undefined;
+ orphanFiles.push(f);
+ }
+ else {
+ openFilesReferenced.push(f);
+ }
+ }
+ this.openFilesReferenced = openFilesReferenced;
+ for (var i = 0, len = orphanFiles.length; i < len; i++) {
+ this.addOpenFile(orphanFiles[i]);
+ }
+ }
+ else {
+ ts.unorderedRemoveItem(this.openFilesReferenced, info);
+ }
+ info.close();
+ };
+ ProjectService.prototype.findReferencingProjects = function (info, excludedProject) {
+ var referencingProjects = [];
+ info.defaultProject = undefined;
+ for (var i = 0, len = this.inferredProjects.length; i < len; i++) {
+ var inferredProject = this.inferredProjects[i];
+ inferredProject.updateGraph();
+ if (inferredProject !== excludedProject) {
+ if (inferredProject.getSourceFile(info)) {
+ info.defaultProject = inferredProject;
+ referencingProjects.push(inferredProject);
+ }
+ }
+ }
+ for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
+ var configuredProject = this.configuredProjects[i];
+ configuredProject.updateGraph();
+ if (configuredProject.getSourceFile(info)) {
+ info.defaultProject = configuredProject;
+ referencingProjects.push(configuredProject);
+ }
+ }
+ return referencingProjects;
+ };
+ ProjectService.prototype.reloadProjects = function () {
+ this.log("reload projects.");
+ for (var _i = 0, _a = this.openFileRoots; _i < _a.length; _i++) {
+ var info = _a[_i];
+ this.openOrUpdateConfiguredProjectForFile(info.fileName);
+ }
+ this.updateProjectStructure();
+ };
+ ProjectService.prototype.updateProjectStructure = function () {
+ this.log("updating project structure from ...", "Info");
+ this.printProjects();
+ var unattachedOpenFiles = [];
+ var openFileRootsConfigured = [];
+ for (var _i = 0, _a = this.openFileRootsConfigured; _i < _a.length; _i++) {
+ var info = _a[_i];
+ var project = info.defaultProject;
+ if (!project || !(project.getSourceFile(info))) {
+ info.defaultProject = undefined;
+ unattachedOpenFiles.push(info);
+ }
+ else {
+ openFileRootsConfigured.push(info);
+ }
+ }
+ this.openFileRootsConfigured = openFileRootsConfigured;
+ var openFilesReferenced = [];
+ for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) {
+ var referencedFile = this.openFilesReferenced[i];
+ referencedFile.defaultProject.updateGraph();
+ var sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile);
+ if (sourceFile) {
+ openFilesReferenced.push(referencedFile);
+ }
+ else {
+ unattachedOpenFiles.push(referencedFile);
+ }
+ }
+ this.openFilesReferenced = openFilesReferenced;
+ var openFileRoots = [];
+ for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
+ var rootFile = this.openFileRoots[i];
+ var rootedProject = rootFile.defaultProject;
+ var referencingProjects = this.findReferencingProjects(rootFile, rootedProject);
+ if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) {
+ if (!rootedProject.isConfiguredProject()) {
+ this.removeProject(rootedProject);
+ }
+ this.openFileRootsConfigured.push(rootFile);
+ }
+ else {
+ if (referencingProjects.length === 0) {
+ rootFile.defaultProject = rootedProject;
+ openFileRoots.push(rootFile);
+ }
+ else {
+ this.removeProject(rootedProject);
+ this.openFilesReferenced.push(rootFile);
+ }
+ }
+ }
+ this.openFileRoots = openFileRoots;
+ for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) {
+ this.addOpenFile(unattachedOpenFiles[i]);
+ }
+ this.printProjects();
+ };
+ ProjectService.prototype.getScriptInfo = function (filename) {
+ filename = ts.normalizePath(filename);
+ return this.filenameToScriptInfo[filename];
+ };
+ ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) {
+ var _this = this;
+ fileName = ts.normalizePath(fileName);
+ var info = this.filenameToScriptInfo[fileName];
+ if (!info) {
+ var content = void 0;
+ if (this.host.fileExists(fileName)) {
+ content = fileContent || this.host.readFile(fileName);
+ }
+ if (!content) {
+ if (openedByClient) {
+ content = "";
+ }
+ }
+ if (content !== undefined) {
+ info = new ScriptInfo(this.host, fileName, content, openedByClient);
+ info.scriptKind = scriptKind;
+ info.setFormatOptions(this.getFormatCodeOptions());
+ this.filenameToScriptInfo[fileName] = info;
+ if (!info.isOpen) {
+ info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); });
+ }
+ }
+ }
+ if (info) {
+ if (fileContent) {
+ info.svc.reload(fileContent);
+ }
+ if (openedByClient) {
+ info.isOpen = true;
+ }
+ }
+ return info;
+ };
+ ProjectService.prototype.findConfigFile = function (searchPath) {
+ while (true) {
+ var tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json");
+ if (this.host.fileExists(tsconfigFileName)) {
+ return tsconfigFileName;
+ }
+ var jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json");
+ if (this.host.fileExists(jsconfigFileName)) {
+ return jsconfigFileName;
+ }
+ var parentPath = ts.getDirectoryPath(searchPath);
+ if (parentPath === searchPath) {
+ break;
+ }
+ searchPath = parentPath;
+ }
+ return undefined;
+ };
+ ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) {
+ var _a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors;
+ var info = this.openFile(fileName, true, fileContent, scriptKind);
+ this.addOpenFile(info);
+ this.printProjects();
+ return { configFileName: configFileName, configFileErrors: configFileErrors };
+ };
+ ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) {
+ var searchPath = ts.normalizePath(ts.getDirectoryPath(fileName));
+ this.log("Search path: " + searchPath, "Info");
+ var configFileName = this.findConfigFile(searchPath);
+ if (configFileName) {
+ this.log("Config file name: " + configFileName, "Info");
+ var project = this.findConfiguredProjectByConfigFile(configFileName);
+ if (!project) {
+ var configResult = this.openConfigFile(configFileName, fileName);
+ if (!configResult.project) {
+ return { configFileName: configFileName, configFileErrors: configResult.errors };
+ }
+ else {
+ this.log("Opened configuration file " + configFileName, "Info");
+ this.configuredProjects.push(configResult.project);
+ if (configResult.errors && configResult.errors.length > 0) {
+ return { configFileName: configFileName, configFileErrors: configResult.errors };
+ }
+ }
+ }
+ else {
+ this.updateConfiguredProject(project);
+ }
+ return { configFileName: configFileName };
+ }
+ else {
+ this.log("No config files found.");
+ }
+ return {};
+ };
+ ProjectService.prototype.closeClientFile = function (filename) {
+ var info = this.filenameToScriptInfo[filename];
+ if (info) {
+ this.closeOpenFile(info);
+ info.isOpen = false;
+ }
+ this.printProjects();
+ };
+ ProjectService.prototype.getProjectForFile = function (filename) {
+ var scriptInfo = this.filenameToScriptInfo[filename];
+ if (scriptInfo) {
+ return scriptInfo.defaultProject;
+ }
+ };
+ ProjectService.prototype.printProjectsForFile = function (filename) {
+ var scriptInfo = this.filenameToScriptInfo[filename];
+ if (scriptInfo) {
+ this.psLogger.startGroup();
+ this.psLogger.info("Projects for " + filename);
+ var projects = this.findReferencingProjects(scriptInfo);
+ for (var i = 0, len = projects.length; i < len; i++) {
+ this.psLogger.info("Project " + i.toString());
+ }
+ this.psLogger.endGroup();
+ }
+ else {
+ this.psLogger.info(filename + " not in any project");
+ }
+ };
+ ProjectService.prototype.printProjects = function () {
+ if (!this.psLogger.isVerbose()) {
+ return;
+ }
+ this.psLogger.startGroup();
+ for (var i = 0, len = this.inferredProjects.length; i < len; i++) {
+ var project = this.inferredProjects[i];
+ project.updateGraph();
+ this.psLogger.info("Project " + i.toString());
+ this.psLogger.info(project.filesToString());
+ this.psLogger.info("-----------------------------------------------");
+ }
+ for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
+ var project = this.configuredProjects[i];
+ project.updateGraph();
+ this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString());
+ this.psLogger.info(project.filesToString());
+ this.psLogger.info("-----------------------------------------------");
+ }
+ this.psLogger.info("Open file roots of inferred projects: ");
+ for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
+ this.psLogger.info(this.openFileRoots[i].fileName);
+ }
+ this.psLogger.info("Open files referenced by inferred or configured projects: ");
+ for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) {
+ var fileInfo = this.openFilesReferenced[i].fileName;
+ if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) {
+ fileInfo += " (configured)";
+ }
+ this.psLogger.info(fileInfo);
+ }
+ this.psLogger.info("Open file roots of configured projects: ");
+ for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) {
+ this.psLogger.info(this.openFileRootsConfigured[i].fileName);
+ }
+ this.psLogger.endGroup();
+ };
+ ProjectService.prototype.configProjectIsActive = function (fileName) {
+ return this.findConfiguredProjectByConfigFile(fileName) === undefined;
+ };
+ ProjectService.prototype.findConfiguredProjectByConfigFile = function (configFileName) {
+ for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
+ if (this.configuredProjects[i].projectFilename == configFileName) {
+ return this.configuredProjects[i];
+ }
+ }
+ return undefined;
+ };
+ ProjectService.prototype.configFileToProjectOptions = function (configFilename) {
+ configFilename = ts.normalizePath(configFilename);
+ var errors = [];
+ var dirPath = ts.getDirectoryPath(configFilename);
+ var contents = this.host.readFile(configFilename);
+ var _a = ts.parseAndReEmitConfigJSONFile(contents), configJsonObject = _a.configJsonObject, diagnostics = _a.diagnostics;
+ errors = ts.concatenate(errors, diagnostics);
+ var parsedCommandLine = ts.parseJsonConfigFileContent(configJsonObject, this.host, dirPath, {}, configFilename);
+ errors = ts.concatenate(errors, parsedCommandLine.errors);
+ ts.Debug.assert(!!parsedCommandLine.fileNames);
+ if (parsedCommandLine.fileNames.length === 0) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename));
+ return { errors: errors };
+ }
+ else {
+ var projectOptions = {
+ files: parsedCommandLine.fileNames,
+ wildcardDirectories: parsedCommandLine.wildcardDirectories,
+ compilerOptions: parsedCommandLine.options
+ };
+ return { projectOptions: projectOptions, errors: errors };
+ }
+ };
+ ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) {
+ var totalNonTsFileSize = 0;
+ if (!this.host.getFileSize) {
+ return false;
+ }
+ for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) {
+ var fileName = fileNames_4[_i];
+ if (ts.hasTypeScriptFileExtension(fileName)) {
+ continue;
+ }
+ totalNonTsFileSize += this.host.getFileSize(fileName);
+ if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) {
+ return true;
+ }
+ }
+ return false;
+ };
+ ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) {
+ var _this = this;
+ var parseConfigFileResult = this.configFileToProjectOptions(configFilename);
+ var errors = parseConfigFileResult.errors;
+ if (!parseConfigFileResult.projectOptions) {
+ return { errors: errors };
+ }
+ var projectOptions = parseConfigFileResult.projectOptions;
+ if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) {
+ if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) {
+ var project_1 = this.createProject(configFilename, projectOptions, true);
+ project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); });
+ return { project: project_1, errors: errors };
+ }
+ }
+ var project = this.createProject(configFilename, projectOptions);
+ for (var _i = 0, _a = projectOptions.files; _i < _a.length; _i++) {
+ var rootFilename = _a[_i];
+ if (this.host.fileExists(rootFilename)) {
+ var info = this.openFile(rootFilename, clientFileName == rootFilename);
+ project.addRoot(info);
+ }
+ else {
+ (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename));
+ }
+ }
+ project.finishGraph();
+ project.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project); });
+ var configDirectoryPath = ts.getDirectoryPath(configFilename);
+ this.log("Add recursive watcher for: " + configDirectoryPath);
+ project.directoryWatcher = this.host.watchDirectory(configDirectoryPath, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true);
+ project.directoriesWatchedForWildcards = ts.reduceProperties(ts.createMap(projectOptions.wildcardDirectories), function (watchers, flag, directory) {
+ if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) {
+ var recursive = (flag & 1) !== 0;
+ _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory);
+ watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, recursive);
+ }
+ return watchers;
+ }, {});
+ return { project: project, errors: errors };
+ };
+ ProjectService.prototype.updateConfiguredProject = function (project) {
+ var _this = this;
+ if (!this.host.fileExists(project.projectFilename)) {
+ this.log("Config file deleted");
+ this.removeProject(project);
+ }
+ else {
+ var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors;
+ if (!projectOptions) {
+ return errors;
+ }
+ else {
+ if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) {
+ project.setProjectOptions(projectOptions);
+ if (project.languageServiceDiabled) {
+ return errors;
+ }
+ project.disableLanguageService();
+ if (project.directoryWatcher) {
+ project.directoryWatcher.close();
+ project.directoryWatcher = undefined;
+ }
+ return errors;
+ }
+ if (project.languageServiceDiabled) {
+ project.setProjectOptions(projectOptions);
+ project.enableLanguageService();
+ project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true);
+ for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) {
+ var rootFilename = _b[_i];
+ if (this.host.fileExists(rootFilename)) {
+ var info = this.openFile(rootFilename, false);
+ project.addRoot(info);
+ }
+ }
+ project.finishGraph();
+ return errors;
+ }
+ var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; });
+ var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); });
+ var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; });
+ var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; });
+ for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) {
+ var fileName = fileNamesToRemove_1[_c];
+ var info = this.getScriptInfo(fileName);
+ if (info) {
+ project.removeRoot(info);
+ }
+ }
+ for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) {
+ var fileName = fileNamesToAdd_1[_d];
+ var info = this.getScriptInfo(fileName);
+ if (!info) {
+ info = this.openFile(fileName, false);
+ }
+ else {
+ if (info.isOpen) {
+ if (this.openFileRoots.indexOf(info) >= 0) {
+ ts.unorderedRemoveItem(this.openFileRoots, info);
+ if (info.defaultProject && !info.defaultProject.isConfiguredProject()) {
+ this.removeProject(info.defaultProject);
+ }
+ }
+ if (this.openFilesReferenced.indexOf(info) >= 0) {
+ ts.unorderedRemoveItem(this.openFilesReferenced, info);
+ }
+ this.openFileRootsConfigured.push(info);
+ info.defaultProject = project;
+ }
+ }
+ project.addRoot(info);
+ }
+ project.setProjectOptions(projectOptions);
+ project.finishGraph();
+ }
+ return errors;
+ }
+ };
+ ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) {
+ var project = new Project(this, projectOptions, languageServiceDisabled);
+ project.projectFilename = projectFilename;
+ return project;
+ };
+ return ProjectService;
+ }());
+ server.ProjectService = ProjectService;
+ var CompilerService = (function () {
+ function CompilerService(project, opt) {
+ this.project = project;
+ this.documentRegistry = ts.createDocumentRegistry();
+ this.host = new LSHost(project.projectService.host, project);
+ if (opt) {
+ this.setCompilerOptions(opt);
+ }
+ else {
+ var defaultOpts = ts.getDefaultCompilerOptions();
+ defaultOpts.allowNonTsExtensions = true;
+ defaultOpts.allowJs = true;
+ this.setCompilerOptions(defaultOpts);
+ }
+ this.languageService = ts.createLanguageService(this.host, this.documentRegistry);
+ this.classifier = ts.createClassifier();
+ }
+ CompilerService.prototype.setCompilerOptions = function (opt) {
+ this.settings = opt;
+ this.host.setCompilationSettings(opt);
+ };
+ CompilerService.prototype.isExternalModule = function (filename) {
+ var sourceFile = this.languageService.getNonBoundSourceFile(filename);
+ return ts.isExternalModule(sourceFile);
+ };
+ CompilerService.getDefaultFormatCodeOptions = function (host) {
+ return ts.clone({
+ BaseIndentSize: 0,
+ IndentSize: 4,
+ TabSize: 4,
+ NewLineCharacter: host.newLine || "\n",
+ ConvertTabsToSpaces: true,
+ IndentStyle: ts.IndentStyle.Smart,
+ InsertSpaceAfterCommaDelimiter: true,
+ InsertSpaceAfterSemicolonInForStatements: true,
+ InsertSpaceBeforeAndAfterBinaryOperators: true,
+ InsertSpaceAfterKeywordsInControlFlowStatements: true,
+ InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
+ InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
+ InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
+ InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
+ InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
+ InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
+ InsertSpaceAfterTypeAssertion: false,
+ PlaceOpenBraceOnNewLineForFunctions: false,
+ PlaceOpenBraceOnNewLineForControlBlocks: false
+ });
+ };
+ return CompilerService;
+ }());
+ server.CompilerService = CompilerService;
(function (CharRangeSection) {
CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart";
CharRangeSection[CharRangeSection["Start"] = 1] = "Start";
@@ -64415,19 +62801,10 @@ var ts;
var ScriptVersionCache = (function () {
function ScriptVersionCache() {
this.changes = [];
- this.versions = new Array(ScriptVersionCache.maxVersions);
+ this.versions = [];
this.minVersion = 0;
this.currentVersion = 0;
}
- ScriptVersionCache.prototype.versionToIndex = function (version) {
- if (version < this.minVersion || version > this.currentVersion) {
- return undefined;
- }
- return version % ScriptVersionCache.maxVersions;
- };
- ScriptVersionCache.prototype.currentVersionToIndex = function () {
- return this.currentVersion % ScriptVersionCache.maxVersions;
- };
ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) {
this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText);
if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) ||
@@ -64437,7 +62814,7 @@ var ts;
}
};
ScriptVersionCache.prototype.latest = function () {
- return this.versions[this.currentVersionToIndex()];
+ return this.versions[this.currentVersion];
};
ScriptVersionCache.prototype.latestVersion = function () {
if (this.changes.length > 0) {
@@ -64445,30 +62822,32 @@ var ts;
}
return this.currentVersion;
};
- ScriptVersionCache.prototype.reloadFromFile = function (filename) {
+ ScriptVersionCache.prototype.reloadFromFile = function (filename, cb) {
var content = this.host.readFile(filename);
if (!content) {
content = "";
}
this.reload(content);
+ if (cb)
+ cb();
};
ScriptVersionCache.prototype.reload = function (script) {
this.currentVersion++;
this.changes = [];
var snap = new LineIndexSnapshot(this.currentVersion, this);
- for (var i = 0; i < this.versions.length; i++) {
- this.versions[i] = undefined;
- }
- this.versions[this.currentVersionToIndex()] = snap;
+ this.versions[this.currentVersion] = snap;
snap.index = new LineIndex();
var lm = LineIndex.linesFromText(script);
snap.index.load(lm.lines);
+ for (var i = this.minVersion; i < this.currentVersion; i++) {
+ this.versions[i] = undefined;
+ }
this.minVersion = this.currentVersion;
};
ScriptVersionCache.prototype.getSnapshot = function () {
- var snap = this.versions[this.currentVersionToIndex()];
+ var snap = this.versions[this.currentVersion];
if (this.changes.length > 0) {
- var snapIndex = snap.index;
+ var snapIndex = this.latest().index;
for (var i = 0, len = this.changes.length; i < len; i++) {
var change = this.changes[i];
snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText);
@@ -64477,10 +62856,14 @@ var ts;
snap.index = snapIndex;
snap.changesSincePreviousVersion = this.changes;
this.currentVersion = snap.version;
- this.versions[this.currentVersionToIndex()] = snap;
+ this.versions[snap.version] = snap;
this.changes = [];
if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) {
+ var oldMin = this.minVersion;
this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1;
+ for (var j = oldMin; j < this.minVersion; j++) {
+ this.versions[j] = undefined;
+ }
}
}
return snap;
@@ -64490,7 +62873,7 @@ var ts;
if (oldVersion >= this.minVersion) {
var textChangeRanges = [];
for (var i = oldVersion + 1; i <= newVersion; i++) {
- var snap = this.versions[this.versionToIndex(i)];
+ var snap = this.versions[i];
for (var j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) {
var textChange = snap.changesSincePreviousVersion[j];
textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange();
@@ -64628,7 +63011,7 @@ var ts;
done: false,
leaf: function (relativeStart, relativeLength, ll) {
if (!f(ll, relativeStart, relativeLength)) {
- this.done = true;
+ walkFns.done = true;
}
}
};
@@ -64641,7 +63024,7 @@ var ts;
return source.substring(0, s) + nt + source.substring(s + dl, source.length);
}
if (this.root.charCount() === 0) {
- if (newText !== undefined) {
+ if (newText) {
this.load(LineIndex.linesFromText(newText).lines);
return this;
}
@@ -65021,6 +63404,12 @@ var ts;
function LineLeaf(text) {
this.text = text;
}
+ LineLeaf.prototype.setUdata = function (data) {
+ this.udata = data;
+ };
+ LineLeaf.prototype.getUdata = function () {
+ return this.udata;
+ };
LineLeaf.prototype.isLeaf = function () {
return true;
};
@@ -65042,25 +63431,6 @@ var ts;
(function (ts) {
var server;
(function (server) {
- var net = require("net");
- var childProcess = require("child_process");
- var os = require("os");
- function getGlobalTypingsCacheLocation() {
- var basePath;
- switch (process.platform) {
- case "win32":
- basePath = process.env.LOCALAPPDATA || process.env.APPDATA || os.homedir();
- break;
- case "linux":
- basePath = os.homedir();
- break;
- case "darwin":
- basePath = ts.combinePaths(os.homedir(), "Library/Application Support/");
- break;
- }
- ts.Debug.assert(basePath !== undefined);
- return ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript");
- }
var readline = require("readline");
var fs = require("fs");
var rl = readline.createInterface({
@@ -65069,9 +63439,8 @@ var ts;
terminal: false
});
var Logger = (function () {
- function Logger(logFilename, traceToConsole, level) {
+ function Logger(logFilename, level) {
this.logFilename = logFilename;
- this.traceToConsole = traceToConsole;
this.level = level;
this.fd = -1;
this.seq = 0;
@@ -65086,14 +63455,11 @@ var ts;
fs.close(this.fd);
}
};
- Logger.prototype.getLogFileName = function () {
- return this.logFilename;
- };
Logger.prototype.perftrc = function (s) {
- this.msg(s, server.Msg.Perf);
+ this.msg(s, "Perf");
};
Logger.prototype.info = function (s) {
- this.msg(s, server.Msg.Info);
+ this.msg(s, "Info");
};
Logger.prototype.startGroup = function () {
this.inGroup = true;
@@ -65105,19 +63471,19 @@ var ts;
this.firstInGroup = true;
};
Logger.prototype.loggingEnabled = function () {
- return !!this.logFilename || this.traceToConsole;
+ return !!this.logFilename;
};
- Logger.prototype.hasLevel = function (level) {
- return this.loggingEnabled() && this.level >= level;
+ Logger.prototype.isVerbose = function () {
+ return this.loggingEnabled() && (this.level == "verbose");
};
Logger.prototype.msg = function (s, type) {
- if (type === void 0) { type = server.Msg.Err; }
+ if (type === void 0) { type = "Err"; }
if (this.fd < 0) {
if (this.logFilename) {
this.fd = fs.openSync(this.logFilename, "w");
}
}
- if (this.fd >= 0 || this.traceToConsole) {
+ if (this.fd >= 0) {
s = s + "\n";
var prefix = Logger.padStringRight(type + " " + this.seq.toString(), " ");
if (this.firstInGroup) {
@@ -65128,88 +63494,19 @@ var ts;
this.seq++;
this.firstInGroup = true;
}
- if (this.fd >= 0) {
- var buf = new Buffer(s);
- fs.writeSync(this.fd, buf, 0, buf.length, null);
- }
- if (this.traceToConsole) {
- console.warn(s);
- }
+ var buf = new Buffer(s);
+ fs.writeSync(this.fd, buf, 0, buf.length, null);
}
};
return Logger;
}());
- var NodeTypingsInstaller = (function () {
- function NodeTypingsInstaller(logger, eventPort, globalTypingsCacheLocation, newLine) {
- var _this = this;
- this.logger = logger;
- this.eventPort = eventPort;
- this.globalTypingsCacheLocation = globalTypingsCacheLocation;
- this.newLine = newLine;
- if (eventPort) {
- var s_1 = net.connect({ port: eventPort }, function () {
- _this.socket = s_1;
- });
- }
- }
- NodeTypingsInstaller.prototype.attach = function (projectService) {
- var _this = this;
- this.projectService = projectService;
- if (this.logger.hasLevel(server.LogLevel.requestTime)) {
- this.logger.info("Binding...");
- }
- var args = ["--globalTypingsCacheLocation", this.globalTypingsCacheLocation];
- if (this.logger.loggingEnabled() && this.logger.getLogFileName()) {
- args.push("--logFile", ts.combinePaths(ts.getDirectoryPath(ts.normalizeSlashes(this.logger.getLogFileName())), "ti-" + process.pid + ".log"));
- }
- var execArgv = [];
- {
- for (var _i = 0, _a = process.execArgv; _i < _a.length; _i++) {
- var arg = _a[_i];
- var match = /^--(debug|inspect)(=(\d+))?$/.exec(arg);
- if (match) {
- var currentPort = match[3] !== undefined
- ? +match[3]
- : match[1] === "debug" ? 5858 : 9229;
- execArgv.push("--" + match[1] + "=" + (currentPort + 1));
- break;
- }
- }
- }
- this.installer = childProcess.fork(ts.combinePaths(__dirname, "typingsInstaller.js"), args, { execArgv: execArgv });
- this.installer.on("message", function (m) { return _this.handleMessage(m); });
- process.on("exit", function () {
- _this.installer.kill();
- });
- };
- NodeTypingsInstaller.prototype.onProjectClosed = function (p) {
- this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" });
- };
- NodeTypingsInstaller.prototype.enqueueInstallTypingsRequest = function (project, typingOptions) {
- var request = server.createInstallTypingsRequest(project, typingOptions);
- if (this.logger.hasLevel(server.LogLevel.verbose)) {
- this.logger.info("Sending request: " + JSON.stringify(request));
- }
- this.installer.send(request);
- };
- NodeTypingsInstaller.prototype.handleMessage = function (response) {
- if (this.logger.hasLevel(server.LogLevel.verbose)) {
- this.logger.info("Received response: " + JSON.stringify(response));
- }
- this.projectService.updateTypingsForProject(response);
- if (response.kind == "set" && this.socket) {
- this.socket.write(server.formatMessage({ seq: 0, type: "event", message: response }, this.logger, Buffer.byteLength, this.newLine), "utf8");
- }
- };
- return NodeTypingsInstaller;
- }());
var IOSession = (function (_super) {
__extends(IOSession, _super);
- function IOSession(host, cancellationToken, installerEventPort, canUseEvents, useSingleInferredProject, globalTypingsCacheLocation, logger) {
- _super.call(this, host, cancellationToken, useSingleInferredProject, new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine), Buffer.byteLength, process.hrtime, logger, canUseEvents);
+ function IOSession(host, logger) {
+ _super.call(this, host, Buffer.byteLength, process.hrtime, logger);
}
IOSession.prototype.exit = function () {
- this.logger.info("Exiting...");
+ this.projectService.log("Exiting...", "Info");
this.projectService.closeLog();
process.exit(0);
};
@@ -65226,7 +63523,7 @@ var ts;
return IOSession;
}(server.Session));
function parseLoggingEnvironmentString(logEnvStr) {
- var logEnv = { logToFile: true };
+ var logEnv = {};
var args = logEnvStr.split(" ");
for (var i = 0, len = args.length; i < (len - 1); i += 2) {
var option = args[i];
@@ -65234,17 +63531,10 @@ var ts;
if (option && value) {
switch (option) {
case "-file":
- logEnv.file = ts.stripQuotes(value);
+ logEnv.file = value;
break;
case "-level":
- var level = server.LogLevel[value];
- logEnv.detailLevel = typeof level === "number" ? level : server.LogLevel.normal;
- break;
- case "-traceToConsole":
- logEnv.traceToConsole = value.toLowerCase() === "true";
- break;
- case "-logToFile":
- logEnv.logToFile = value.toLowerCase() === "true";
+ logEnv.detailLevel = value;
break;
}
}
@@ -65253,25 +63543,21 @@ var ts;
}
function createLoggerFromEnv() {
var fileName = undefined;
- var detailLevel = server.LogLevel.normal;
- var traceToConsole = false;
+ var detailLevel = "normal";
var logEnvStr = process.env["TSS_LOG"];
if (logEnvStr) {
var logEnv = parseLoggingEnvironmentString(logEnvStr);
- if (logEnv.logToFile) {
- if (logEnv.file) {
- fileName = logEnv.file;
- }
- else {
- fileName = __dirname + "/.log" + process.pid.toString();
- }
+ if (logEnv.file) {
+ fileName = logEnv.file;
+ }
+ else {
+ fileName = __dirname + "/.log" + process.pid.toString();
}
if (logEnv.detailLevel) {
detailLevel = logEnv.detailLevel;
}
- traceToConsole = logEnv.traceToConsole;
}
- return new Logger(fileName, traceToConsole, detailLevel);
+ return new Logger(fileName, detailLevel);
}
function createPollingWatchedFileSet(interval, chunkSize) {
if (interval === void 0) { interval = 2500; }
@@ -65343,13 +63629,13 @@ var ts;
var logger = createLoggerFromEnv();
var pending = [];
var canWrite = true;
- function writeMessage(buf) {
+ function writeMessage(s) {
if (!canWrite) {
- pending.push(buf);
+ pending.push(s);
}
else {
canWrite = false;
- process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary);
+ process.stdout.write(new Buffer(s, "utf8"), setCanWriteFlagAndWriteMessageIfNecessary);
}
}
function setCanWriteFlagAndWriteMessageIfNecessary() {
@@ -65359,7 +63645,7 @@ var ts;
}
}
var sys = ts.sys;
- sys.write = function (s) { return writeMessage(new Buffer(s, "utf8")); };
+ sys.write = function (s) { return writeMessage(s); };
sys.watchFile = function (fileName, callback) {
var watchedFile = pollingWatchedFileSet.addFile(fileName, callback);
return {
@@ -65368,34 +63654,7 @@ var ts;
};
sys.setTimeout = setTimeout;
sys.clearTimeout = clearTimeout;
- sys.setImmediate = setImmediate;
- sys.clearImmediate = clearImmediate;
- if (typeof global !== "undefined" && global.gc) {
- sys.gc = function () { return global.gc(); };
- }
- var cancellationToken;
- try {
- var factory = require("./cancellationToken");
- cancellationToken = factory(sys.args);
- }
- catch (e) {
- cancellationToken = {
- isCancellationRequested: function () { return false; }
- };
- }
- ;
- var eventPort;
- {
- var index = sys.args.indexOf("--eventPort");
- if (index >= 0 && index < sys.args.length - 1) {
- var v = parseInt(sys.args[index + 1]);
- if (!isNaN(v)) {
- eventPort = v;
- }
- }
- }
- var useSingleInferredProject = sys.args.indexOf("--useSingleInferredProject") >= 0;
- var ioSession = new IOSession(sys, cancellationToken, eventPort, eventPort === undefined, useSingleInferredProject, getGlobalTypingsCacheLocation(), logger);
+ var ioSession = new IOSession(sys, logger);
process.on("uncaughtException", function (err) {
ioSession.logError(err, "unknown");
});
@@ -65480,12 +63739,6 @@ var ts;
}
return this.shimHost.getProjectVersion();
};
- LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () {
- if (!this.shimHost.getTypeRootsVersion) {
- return 0;
- }
- return this.shimHost.getTypeRootsVersion();
- };
LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () {
return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
};
@@ -66085,4 +64338,4 @@ var TypeScript;
Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
})(Services = TypeScript.Services || (TypeScript.Services = {}));
})(TypeScript || (TypeScript = {}));
-var toolsVersion = "2.0";
+var toolsVersion = "2.1";
diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts
index 5c303c302b7..7ed6595bc80 100644
--- a/lib/tsserverlibrary.d.ts
+++ b/lib/tsserverlibrary.d.ts
@@ -1,6 +1,4 @@
-///
///
-///
declare namespace ts {
interface MapLike {
[index: string]: T;
@@ -17,7 +15,6 @@ declare namespace ts {
contains(fileName: Path): boolean;
remove(fileName: Path): void;
forEachValue(f: (key: Path, v: T) => void): void;
- getKeys(): Path[];
clear(): void;
}
interface TextRange {
@@ -1242,7 +1239,7 @@ declare namespace ts {
interface Program extends ScriptReferenceHost {
getRootFileNames(): string[];
getSourceFiles(): SourceFile[];
- emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult;
+ emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult;
getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
@@ -1251,7 +1248,6 @@ declare namespace ts {
getTypeChecker(): TypeChecker;
getCommonSourceDirectory(): string;
getDiagnosticsProducingTypeChecker(): TypeChecker;
- dropDiagnosticsProducingTypeChecker(): void;
getClassifiableNames(): Map;
getNodeCount(): number;
getIdentifierCount(): number;
@@ -1383,7 +1379,6 @@ declare namespace ts {
UseFullyQualifiedType = 128,
InFirstTypeArgument = 256,
InTypeAlias = 512,
- UseTypeAliasValue = 1024,
}
const enum SymbolFormatFlags {
None = 0,
@@ -1979,7 +1974,6 @@ declare namespace ts {
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: MapLike;
- compileOnSave?: boolean;
}
const enum WatchDirectoryFlags {
None = 0,
@@ -2333,7 +2327,7 @@ declare namespace ts {
function singleOrUndefined(array: T[]): T;
function singleOrMany(array: T[]): T | T[];
function lastOrUndefined(array: T[]): T;
- function binarySearch(array: T[], value: T, comparer?: (v1: T, v2: T) => number): number;
+ function binarySearch(array: number[], value: number): number;
function reduceLeft(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U;
function reduceLeft(array: T[], f: (memo: T, value: T, i: number) => T): T;
function reduceRight(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U;
@@ -2381,12 +2375,7 @@ declare namespace ts {
function getDirectoryPath(path: Path): Path;
function getDirectoryPath(path: string): string;
function isUrl(path: string): boolean;
- function isExternalModuleNameRelative(moduleName: string): boolean;
- function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget;
- function getEmitModuleKind(compilerOptions: CompilerOptions): ModuleKind;
- function hasZeroOrOneAsteriskCharacter(str: string): boolean;
function isRootedDiskPath(path: string): boolean;
- function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string;
function getNormalizedPathComponents(path: string, currentDirectory: string): string[];
function getNormalizedAbsolutePath(fileName: string, currentDirectory: string): string;
function getNormalizedPathFromPathComponents(pathComponents: string[]): string;
@@ -2420,8 +2409,6 @@ declare namespace ts {
const supportedTypescriptExtensionsForExtractExtension: string[];
const supportedJavascriptExtensions: string[];
function getSupportedExtensions(options?: CompilerOptions): string[];
- function hasJavaScriptFileExtension(fileName: string): boolean;
- function hasTypeScriptFileExtension(fileName: string): boolean;
function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions): boolean;
const enum ExtensionPriority {
TypeScriptFiles = 0,
@@ -2464,7 +2451,6 @@ declare namespace ts {
function unorderedRemoveItemAt(array: T[], index: number): void;
function unorderedRemoveItem(array: T[], item: T): void;
function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): (fileName: string) => string;
- function positionIsSynthesized(pos: number): boolean;
}
declare namespace ts {
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
@@ -6795,12 +6781,6 @@ declare namespace ts {
key: string;
message: string;
};
- Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: {
- code: number;
- category: DiagnosticCategory;
- key: string;
- message: string;
- };
Variable_0_implicitly_has_an_1_type: {
code: number;
category: DiagnosticCategory;
@@ -7194,7 +7174,6 @@ declare namespace ts {
function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner;
}
declare namespace ts {
- const compileOnSaveCommandLineOption: CommandLineOption;
const optionDeclarations: CommandLineOption[];
let typingOptionDeclarations: CommandLineOption[];
interface OptionNameMap {
@@ -7211,7 +7190,7 @@ declare namespace ts {
config?: any;
error?: Diagnostic;
};
- function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): {
+ function parseConfigFileTextToJson(fileName: string, jsonText: string): {
config?: any;
error?: Diagnostic;
};
@@ -7219,112 +7198,15 @@ declare namespace ts {
compilerOptions: Map;
};
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine;
- function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
};
function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
- options: TypingOptions;
+ options: CompilerOptions;
errors: Diagnostic[];
};
}
-declare namespace ts.JsTyping {
- interface TypingResolutionHost {
- directoryExists: (path: string) => boolean;
- fileExists: (fileName: string) => boolean;
- readFile: (path: string, encoding?: string) => string;
- readDirectory: (rootDir: string, extensions: string[], excludes: string[], includes: string[], depth?: number) => string[];
- }
- function discoverTypings(host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, typingOptions: TypingOptions, compilerOptions: CompilerOptions): {
- cachedTypingPaths: string[];
- newTypingNames: string[];
- filesToWatch: string[];
- };
-}
-declare namespace ts.server {
- enum LogLevel {
- terse = 0,
- normal = 1,
- requestTime = 2,
- verbose = 3,
- }
- const emptyArray: ReadonlyArray;
- interface Logger {
- close(): void;
- hasLevel(level: LogLevel): boolean;
- loggingEnabled(): boolean;
- perftrc(s: string): void;
- info(s: string): void;
- startGroup(): void;
- endGroup(): void;
- msg(s: string, type?: Msg.Types): void;
- getLogFileName(): string;
- }
- namespace Msg {
- type Err = "Err";
- const Err: Err;
- type Info = "Info";
- const Info: Info;
- type Perf = "Perf";
- const Perf: Perf;
- type Types = Err | Info | Perf;
- }
- function createInstallTypingsRequest(project: Project, typingOptions: TypingOptions, cachePath?: string): DiscoverTypings;
- namespace Errors {
- function ThrowNoProject(): never;
- function ThrowProjectLanguageServiceDisabled(): never;
- function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never;
- }
- function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings;
- function mergeMaps(target: MapLike, source: MapLike): void;
- function removeItemFromSet(items: T[], itemToRemove: T): void;
- type NormalizedPath = string & {
- __normalizedPathTag: any;
- };
- function toNormalizedPath(fileName: string): NormalizedPath;
- function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path;
- function asNormalizedPath(fileName: string): NormalizedPath;
- interface NormalizedPathMap {
- get(path: NormalizedPath): T;
- set(path: NormalizedPath, value: T): void;
- contains(path: NormalizedPath): boolean;
- remove(path: NormalizedPath): void;
- }
- function createNormalizedPathMap(): NormalizedPathMap;
- const nullLanguageService: LanguageService;
- interface ServerLanguageServiceHost {
- setCompilationSettings(options: CompilerOptions): void;
- notifyFileRemoved(info: ScriptInfo): void;
- }
- const nullLanguageServiceHost: ServerLanguageServiceHost;
- interface ProjectOptions {
- configHasFilesProperty?: boolean;
- files?: string[];
- wildcardDirectories?: Map;
- compilerOptions?: CompilerOptions;
- typingOptions?: TypingOptions;
- compileOnSave?: boolean;
- }
- function isInferredProjectName(name: string): boolean;
- function makeInferredProjectName(counter: number): string;
- class ThrottledOperations {
- private readonly host;
- private pendingTimeouts;
- constructor(host: ServerHost);
- schedule(operationId: string, delay: number, cb: () => void): void;
- private static run(self, operationId, cb);
- }
- class GcTimer {
- private readonly host;
- private readonly delay;
- private readonly logger;
- private timerId;
- constructor(host: ServerHost, delay: number, logger: Logger);
- scheduleCollect(): void;
- private static run(self);
- }
-}
declare namespace ts {
const externalHelpersModuleNameText = "tslib";
interface ReferencePathMatchResult {
@@ -7349,7 +7231,7 @@ declare namespace ts {
function getSingleLineStringWriter(): StringSymbolWriter;
function releaseStringWriter(writer: StringSymbolWriter): void;
function getFullWidth(node: Node): number;
- function arrayIsEqualTo(array1: ReadonlyArray, array2: ReadonlyArray, equaler?: (a: T, b: T) => boolean): boolean;
+ function arrayIsEqualTo(array1: T[], array2: T[], equaler?: (a: T, b: T) => boolean): boolean;
function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean;
function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule;
function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModule): void;
@@ -7436,6 +7318,7 @@ declare namespace ts {
function childIsDecorated(node: Node): boolean;
function isJSXTagName(node: Node): boolean;
function isPartOfExpression(node: Node): boolean;
+ function isExternalModuleNameRelative(moduleName: string): boolean;
function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean;
function isExternalModuleImportEqualsDeclaration(node: Node): boolean;
function getExternalModuleImportEqualsDeclarationExpression(node: Node): Expression;
@@ -7490,6 +7373,7 @@ declare namespace ts {
function getRootDeclaration(node: Node): Node;
function nodeStartsNewLexicalEnvironment(node: Node): boolean;
function nodeIsSynthesized(node: TextRange): boolean;
+ function positionIsSynthesized(pos: number): boolean;
function getOriginalNode(node: Node): Node;
function isParseTreeNode(node: Node): boolean;
function getParseTreeNode(node: Node): Node;
@@ -7533,14 +7417,16 @@ declare namespace ts {
function getExternalModuleNameFromPath(host: EmitHost, fileName: string): string;
function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string): string;
function getDeclarationEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost): string;
+ function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget;
+ function getEmitModuleKind(compilerOptions: CompilerOptions): ModuleKind;
interface EmitFileNames {
jsFilePath: string;
sourceMapFilePath: string;
declarationFilePath: string;
}
function getSourceFilesToEmit(host: EmitHost, targetSourceFile?: SourceFile): SourceFile[];
- function forEachTransformedEmitFile(host: EmitHost, sourceFiles: SourceFile[], action: (jsFilePath: string, sourceMapFilePath: string, declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, emitOnlyDtsFiles?: boolean): void;
- function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean, emitOnlyDtsFiles: boolean) => void, targetSourceFile?: SourceFile, emitOnlyDtsFiles?: boolean): void;
+ function forEachTransformedEmitFile(host: EmitHost, sourceFiles: SourceFile[], action: (jsFilePath: string, sourceMapFilePath: string, declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) => void): void;
+ function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, targetSourceFile?: SourceFile): void;
function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string): string;
function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: SourceFile[]): void;
function getLineOfLocalPosition(currentSourceFile: SourceFile, pos: number): number;
@@ -7577,9 +7463,12 @@ declare namespace ts {
function isRightSideOfQualifiedNameOrPropertyAccess(node: Node): boolean;
function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean;
function getLocalSymbolForExportDefault(symbol: Symbol): Symbol;
+ function hasJavaScriptFileExtension(fileName: string): boolean;
+ function hasTypeScriptFileExtension(fileName: string): boolean;
function tryExtractTypeScriptExtension(fileName: string): string | undefined;
const stringify: (value: any) => string;
function convertToBase64(input: string): string;
+ function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string;
function getNewLineCharacter(options: CompilerOptions): string;
function isSimpleExpression(node: Expression): boolean;
function formatSyntaxKind(kind: SyntaxKind): string;
@@ -7714,32 +7603,6 @@ declare namespace ts {
function getCombinedModifierFlags(node: Node): ModifierFlags;
function getCombinedNodeFlags(node: Node): NodeFlags;
}
-declare namespace ts {
- function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void;
- function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean;
- function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations;
- interface ModuleResolutionState {
- host: ModuleResolutionHost;
- compilerOptions: CompilerOptions;
- traceEnabled: boolean;
- skipTsx: boolean;
- }
- function getEffectiveTypeRoots(options: CompilerOptions, host: {
- directoryExists?: (directoryName: string) => boolean;
- getCurrentDirectory?: () => string;
- }): string[] | undefined;
- function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
- function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[];
- function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
- function findBestPatternMatch(values: T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined;
- function tryParsePattern(pattern: string): Pattern | undefined;
- function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
- function directoryProbablyExists(directoryName: string, host: {
- directoryExists?: (directoryName: string) => boolean;
- }): boolean;
- function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState, checkOneLevel: boolean): string;
- function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
-}
declare namespace ts {
function updateNode(updated: T, original: T): T;
function createNodeArray(elements?: T[], location?: TextRange, hasTrailingComma?: boolean): NodeArray;
@@ -8112,7 +7975,7 @@ declare namespace ts {
}
declare namespace ts {
function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[];
- function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection, emitOnlyDtsFiles: boolean): boolean;
+ function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection): boolean;
}
declare namespace ts {
interface SourceMapWriter {
@@ -8148,13 +8011,27 @@ declare namespace ts {
function createCommentWriter(host: EmitHost, writer: EmitTextWriter, sourceMap: SourceMapWriter): CommentWriter;
}
declare namespace ts {
- function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean): EmitResult;
+ function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult;
}
declare namespace ts {
- const version = "2.0.5";
+ const version = "2.1.0";
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
function computeCommonSourceDirectoryOfFilenames(fileNames: string[], currentDirectory: string, getCanonicalFileName: (fileName: string) => string): string;
+ function hasZeroOrOneAsteriskCharacter(str: string): boolean;
+ function getEffectiveTypeRoots(options: CompilerOptions, host: {
+ directoryExists?: (directoryName: string) => boolean;
+ getCurrentDirectory?: () => string;
+ }): string[] | undefined;
+ function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
+ function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
+ function findBestPatternMatch(values: T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined;
+ function tryParsePattern(pattern: string): Pattern | undefined;
+ function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
+ function directoryProbablyExists(directoryName: string, host: {
+ directoryExists?: (directoryName: string) => boolean;
+ }): boolean;
+ function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
interface FormatDiagnosticsHost {
@@ -8164,6 +8041,7 @@ declare namespace ts {
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
+ function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[];
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
declare namespace ts {
@@ -8287,18 +8165,18 @@ declare namespace ts {
findReferences(fileName: string, position: number): ReferencedSymbol[];
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[];
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[];
- getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[];
+ getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[];
getNavigationBarItems(fileName: string): NavigationBarItem[];
getOutliningSpans(fileName: string): OutliningSpan[];
getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[];
getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[];
- getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number;
- getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[];
- getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[];
- getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[];
+ getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number;
+ getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[];
+ getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[];
+ getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[];
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
- getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput;
+ getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
getNonBoundSourceFile(fileName: string): SourceFile;
getSourceFile(fileName: string): SourceFile;
@@ -8379,11 +8257,6 @@ declare namespace ts {
containerName: string;
containerKind: string;
}
- enum IndentStyle {
- None = 0,
- Block = 1,
- Smart = 2,
- }
interface EditorOptions {
BaseIndentSize?: number;
IndentSize: number;
@@ -8392,13 +8265,10 @@ declare namespace ts {
ConvertTabsToSpaces: boolean;
IndentStyle: IndentStyle;
}
- interface EditorSettings {
- baseIndentSize?: number;
- indentSize: number;
- tabSize: number;
- newLineCharacter: string;
- convertTabsToSpaces: boolean;
- indentStyle: IndentStyle;
+ enum IndentStyle {
+ None = 0,
+ Block = 1,
+ Smart = 2,
}
interface FormatCodeOptions extends EditorOptions {
InsertSpaceAfterCommaDelimiter: boolean;
@@ -8414,21 +8284,7 @@ declare namespace ts {
InsertSpaceAfterTypeAssertion?: boolean;
PlaceOpenBraceOnNewLineForFunctions: boolean;
PlaceOpenBraceOnNewLineForControlBlocks: boolean;
- }
- interface FormatCodeSettings extends EditorSettings {
- insertSpaceAfterCommaDelimiter: boolean;
- insertSpaceAfterSemicolonInForStatements: boolean;
- insertSpaceBeforeAndAfterBinaryOperators: boolean;
- insertSpaceAfterKeywordsInControlFlowStatements: boolean;
- insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean;
- insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean;
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean;
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean;
- insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean;
- insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: boolean;
- insertSpaceAfterTypeAssertion?: boolean;
- placeOpenBraceOnNewLineForFunctions: boolean;
- placeOpenBraceOnNewLineForControlBlocks: boolean;
+ [s: string]: boolean | number | string | undefined;
}
interface DefinitionInfo {
fileName: string;
@@ -8772,7 +8628,7 @@ declare namespace ts {
function stripQuotes(name: string): string;
function scriptKindIs(fileName: string, host: LanguageServiceHost, ...scriptKinds: ScriptKind[]): boolean;
function getScriptKind(fileName: string, host?: LanguageServiceHost): ScriptKind;
- function sanitizeConfigFile(configFileName: string, content: string): {
+ function parseAndReEmitConfigJSONFile(content: string): {
configJsonObject: any;
diagnostics: Diagnostic[];
};
@@ -8830,8 +8686,21 @@ declare namespace ts.JsDoc {
function getAllJsDocCompletionEntries(): CompletionEntry[];
function getDocCommentTemplateAtPosition(newLine: string, sourceFile: SourceFile, position: number): TextInsertion;
}
+declare namespace ts.JsTyping {
+ interface TypingResolutionHost {
+ directoryExists: (path: string) => boolean;
+ fileExists: (fileName: string) => boolean;
+ readFile: (path: string, encoding?: string) => string;
+ readDirectory: (rootDir: string, extensions: string[], excludes: string[], includes: string[], depth?: number) => string[];
+ }
+ function discoverTypings(host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, typingOptions: TypingOptions, compilerOptions: CompilerOptions): {
+ cachedTypingPaths: string[];
+ newTypingNames: string[];
+ filesToWatch: string[];
+ };
+}
declare namespace ts.NavigateTo {
- function getNavigateToItems(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number, excludeDtsFiles: boolean): NavigateToItem[];
+ function getNavigateToItems(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[];
}
declare namespace ts.NavigationBar {
function getNavigationBarItems(sourceFile: SourceFile): NavigationBarItem[];
@@ -9279,7 +9148,7 @@ declare namespace ts.formatting {
getRuleName(rule: Rule): string;
getRuleByName(name: string): Rule;
getRulesMap(): RulesMap;
- ensureUpToDate(options: ts.FormatCodeSettings): void;
+ ensureUpToDate(options: ts.FormatCodeOptions): void;
private createActiveRules(options);
}
}
@@ -9292,24 +9161,24 @@ declare namespace ts.formatting {
token: TextRangeWithKind;
trailingTrivia: TextRangeWithKind[];
}
- function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[];
- function formatOnSemicolon(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[];
- function formatOnClosingCurly(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[];
- function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[];
- function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[];
- function getIndentationString(indentation: number, options: EditorSettings): string;
+ function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[];
+ function formatOnSemicolon(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[];
+ function formatOnClosingCurly(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[];
+ function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[];
+ function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[];
+ function getIndentationString(indentation: number, options: FormatCodeOptions): string;
}
declare namespace ts.formatting {
namespace SmartIndenter {
- function getIndentation(position: number, sourceFile: SourceFile, options: EditorSettings): number;
- function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: EditorSettings): number;
- function getBaseIndentation(options: EditorSettings): number;
+ function getIndentation(position: number, sourceFile: SourceFile, options: EditorOptions): number;
+ function getBaseIndentation(options: EditorOptions): number;
+ function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: FormatCodeOptions): number;
function childStartsOnTheSameLineWithElseInIfStatement(parent: Node, child: TextRangeWithKind, childStartLine: number, sourceFile: SourceFile): boolean;
- function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorSettings): {
+ function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions): {
column: number;
character: number;
};
- function findFirstNonWhitespaceColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorSettings): number;
+ function findFirstNonWhitespaceColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions): number;
function nodeWillIndentChild(parent: TextRangeWithKind, child: TextRangeWithKind, indentByDefault: boolean): boolean;
function shouldIndentChildNode(parent: TextRangeWithKind, child?: TextRangeWithKind): boolean;
}
@@ -9319,8 +9188,6 @@ declare namespace ts {
interface DisplayPartsSymbolWriter extends SymbolWriter {
displayParts(): SymbolDisplayPart[];
}
- function toEditorSettings(options: FormatCodeOptions | FormatCodeSettings): FormatCodeSettings;
- function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings;
function displayPartsToString(displayParts: SymbolDisplayPart[]): string;
function getDefaultCompilerOptions(): CompilerOptions;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile;
@@ -9331,496 +9198,101 @@ declare namespace ts {
function getDefaultLibFilePath(options: CompilerOptions): string;
}
declare namespace ts.server {
- class ScriptInfo {
- private readonly host;
- readonly fileName: NormalizedPath;
- readonly scriptKind: ScriptKind;
- isOpen: boolean;
- hasMixedContent: boolean;
- readonly containingProjects: Project[];
- private formatCodeSettings;
- readonly path: Path;
- private fileWatcher;
- private svc;
- constructor(host: ServerHost, fileName: NormalizedPath, content: string, scriptKind: ScriptKind, isOpen?: boolean, hasMixedContent?: boolean);
- getFormatCodeSettings(): FormatCodeSettings;
- attachToProject(project: Project): boolean;
- isAttached(project: Project): boolean;
- detachFromProject(project: Project): void;
- detachAllProjects(): void;
- getDefaultProject(): Project;
- setFormatOptions(formatSettings: protocol.FormatOptions): void;
- setWatcher(watcher: FileWatcher): void;
- stopWatcher(): void;
- getLatestVersion(): string;
- reload(script: string): void;
- saveTo(fileName: string): void;
- reloadFromFile(): void;
- snap(): LineIndexSnapshot;
- getLineInfo(line: number): ILineInfo;
- editContent(start: number, end: number, newText: string): void;
- markContainingProjectsAsDirty(): void;
- lineToTextSpan(line: number): TextSpan;
- lineOffsetToPosition(line: number, offset: number): number;
- positionToLineOffset(position: number): ILineInfo;
- }
-}
-declare namespace ts.server {
- class LSHost implements ts.LanguageServiceHost, ModuleResolutionHost, ServerLanguageServiceHost {
- private readonly host;
- private readonly project;
- private readonly cancellationToken;
- private compilationSettings;
- private readonly resolvedModuleNames;
- private readonly resolvedTypeReferenceDirectives;
- private readonly getCanonicalFileName;
- private readonly resolveModuleName;
- readonly trace: (s: string) => void;
- constructor(host: ServerHost, project: Project, cancellationToken: HostCancellationToken);
- private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult);
- getProjectVersion(): string;
- getCompilationSettings(): CompilerOptions;
- useCaseSensitiveFileNames(): boolean;
- getCancellationToken(): HostCancellationToken;
- resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
- resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[];
- getDefaultLibFileName(): string;
- getScriptSnapshot(filename: string): ts.IScriptSnapshot;
- getScriptFileNames(): string[];
- getTypeRootsVersion(): number;
- getScriptKind(fileName: string): ScriptKind;
- getScriptVersion(filename: string): string;
- getCurrentDirectory(): string;
- resolvePath(path: string): string;
- fileExists(path: string): boolean;
- directoryExists(path: string): boolean;
- readFile(fileName: string): string;
- getDirectories(path: string): string[];
- notifyFileRemoved(info: ScriptInfo): void;
- setCompilationSettings(opt: ts.CompilerOptions): void;
- }
-}
-declare namespace ts.server {
- interface ITypingsInstaller {
- enqueueInstallTypingsRequest(p: Project, typingOptions: TypingOptions): void;
- attach(projectService: ProjectService): void;
- onProjectClosed(p: Project): void;
- readonly globalTypingsCacheLocation: string;
- }
- const nullTypingsInstaller: ITypingsInstaller;
- interface TypingsArray extends ReadonlyArray {
- " __typingsArrayBrand": any;
- }
- class TypingsCache {
- private readonly installer;
- private readonly perProjectCache;
- constructor(installer: ITypingsInstaller);
- getTypingsForProject(project: Project, forceRefresh: boolean): TypingsArray;
- invalidateCachedTypingsForProject(project: Project): void;
- updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typingOptions: TypingOptions, newTypings: string[]): void;
- onProjectClosed(project: Project): void;
- }
-}
-declare namespace ts.server {
- function shouldEmitFile(scriptInfo: ScriptInfo): boolean;
- class BuilderFileInfo {
- readonly scriptInfo: ScriptInfo;
- readonly project: Project;
- private lastCheckedShapeSignature;
- constructor(scriptInfo: ScriptInfo, project: Project);
- isExternalModuleOrHasOnlyAmbientExternalModules(): boolean;
- private containsOnlyAmbientModules(sourceFile);
- private computeHash(text);
- private getSourceFile();
- updateShapeSignature(): boolean;
- }
- interface Builder {
- readonly project: Project;
- getFilesAffectedBy(scriptInfo: ScriptInfo): string[];
- onProjectUpdateGraph(): void;
- emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): boolean;
- }
- function createBuilder(project: Project): Builder;
-}
-declare namespace ts.server {
- enum ProjectKind {
- Inferred = 0,
- Configured = 1,
- External = 2,
- }
- function allRootFilesAreJsOrDts(project: Project): boolean;
- function allFilesAreJsOrDts(project: Project): boolean;
- interface ProjectFilesWithTSDiagnostics extends protocol.ProjectFiles {
- projectErrors: Diagnostic[];
- }
- abstract class Project {
- readonly projectKind: ProjectKind;
- readonly projectService: ProjectService;
- private documentRegistry;
- languageServiceEnabled: boolean;
- private compilerOptions;
- compileOnSaveEnabled: boolean;
- private rootFiles;
- private rootFilesMap;
- private lsHost;
- private program;
- private languageService;
- builder: Builder;
- private lastReportedFileNames;
- private lastReportedVersion;
- private projectStructureVersion;
- private projectStateVersion;
- private typingFiles;
- protected projectErrors: Diagnostic[];
- typesVersion: number;
- isJsOnlyProject(): boolean;
- constructor(projectKind: ProjectKind, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean);
- getProjectErrors(): Diagnostic[];
- getLanguageService(ensureSynchronized?: boolean): LanguageService;
- getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[];
- getProjectVersion(): string;
- enableLanguageService(): void;
- disableLanguageService(): void;
- abstract getProjectName(): string;
- abstract getProjectRootPath(): string | undefined;
- abstract getTypingOptions(): TypingOptions;
- getSourceFile(path: Path): SourceFile;
- updateTypes(): void;
- close(): void;
- getCompilerOptions(): CompilerOptions;
- hasRoots(): boolean;
- getRootFiles(): NormalizedPath[];
- getRootFilesLSHost(): string[];
- getRootScriptInfos(): ScriptInfo[];
- getScriptInfos(): ScriptInfo[];
- getFileEmitOutput(info: ScriptInfo, emitOnlyDtsFiles: boolean): EmitOutput;
- getFileNames(): NormalizedPath[];
- getAllEmittableFiles(): string[];
- containsScriptInfo(info: ScriptInfo): boolean;
- containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean;
- isRoot(info: ScriptInfo): boolean;
- addRoot(info: ScriptInfo): void;
- removeFile(info: ScriptInfo, detachFromProject?: boolean): void;
- markAsDirty(): void;
- updateGraph(): boolean;
- private setTypings(typings);
- private updateGraphWorker();
- getScriptInfoLSHost(fileName: string): ScriptInfo;
- getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo;
- getScriptInfo(uncheckedFileName: string): ScriptInfo;
- filesToString(): string;
- setCompilerOptions(compilerOptions: CompilerOptions): void;
- reloadScript(filename: NormalizedPath): boolean;
- getChangesSinceVersion(lastKnownVersion?: number): ProjectFilesWithTSDiagnostics;
- getReferencedFiles(path: Path): Path[];
- private removeRootFileIfNecessary(info);
- }
- class InferredProject extends Project {
- compileOnSaveEnabled: boolean;
- private static NextId;
- private readonly inferredProjectName;
- directoriesWatchedForTsconfig: string[];
- constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean);
- getProjectName(): string;
- getProjectRootPath(): string;
- close(): void;
- getTypingOptions(): TypingOptions;
- }
- class ConfiguredProject extends Project {
- readonly configFileName: NormalizedPath;
- private wildcardDirectories;
- compileOnSaveEnabled: boolean;
- private typingOptions;
- private projectFileWatcher;
- private directoryWatcher;
- private directoriesWatchedForWildcards;
- private typeRootsWatchers;
- openRefCount: number;
- constructor(configFileName: NormalizedPath, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, compilerOptions: CompilerOptions, wildcardDirectories: Map, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean);
- getProjectRootPath(): string;
- setProjectErrors(projectErrors: Diagnostic[]): void;
- setTypingOptions(newTypingOptions: TypingOptions): void;
- getTypingOptions(): TypingOptions;
- getProjectName(): NormalizedPath;
- watchConfigFile(callback: (project: ConfiguredProject) => void): void;
- watchTypeRoots(callback: (project: ConfiguredProject, path: string) => void): void;
- watchConfigDirectory(callback: (project: ConfiguredProject, path: string) => void): void;
- watchWildcards(callback: (project: ConfiguredProject, path: string) => void): void;
- stopWatchingDirectory(): void;
- close(): void;
- addOpenRef(): void;
- deleteOpenRef(): number;
- getEffectiveTypeRoots(): string[];
- }
- class ExternalProject extends Project {
- readonly externalProjectName: string;
- compileOnSaveEnabled: boolean;
- private readonly projectFilePath;
- private typingOptions;
- constructor(externalProjectName: string, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, compilerOptions: CompilerOptions, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean, projectFilePath?: string);
- getProjectRootPath(): string;
- getTypingOptions(): TypingOptions;
- setProjectErrors(projectErrors: Diagnostic[]): void;
- setTypingOptions(newTypingOptions: TypingOptions): void;
- getProjectName(): string;
- }
-}
-declare namespace ts.server {
- const maxProgramSizeForNonTsFiles: number;
- type ProjectServiceEvent = {
- eventName: "context";
- data: {
- project: Project;
- fileName: NormalizedPath;
- };
- } | {
- eventName: "configFileDiag";
- data: {
- triggerFile?: string;
- configFileName: string;
- diagnostics: Diagnostic[];
- };
- };
- interface ProjectServiceEventHandler {
- (event: ProjectServiceEvent): void;
- }
- function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[];
- interface HostConfiguration {
- formatCodeOptions: FormatCodeSettings;
- hostInfo: string;
- }
- interface OpenConfiguredProjectResult {
- configFileName?: string;
- configFileErrors?: Diagnostic[];
- }
- class ProjectService {
- readonly host: ServerHost;
- readonly logger: Logger;
- readonly cancellationToken: HostCancellationToken;
- readonly useSingleInferredProject: boolean;
- readonly typingsInstaller: ITypingsInstaller;
- private readonly eventHandler;
- readonly typingsCache: TypingsCache;
- private readonly documentRegistry;
- private readonly filenameToScriptInfo;
- private readonly externalProjectToConfiguredProjectMap;
- readonly externalProjects: ExternalProject[];
- readonly inferredProjects: InferredProject[];
- readonly configuredProjects: ConfiguredProject[];
- readonly openFiles: ScriptInfo[];
- private compilerOptionsForInferredProjects;
- private compileOnSaveForInferredProjects;
- private readonly directoryWatchers;
- private readonly throttledOperations;
- private readonly hostConfiguration;
- private changedFiles;
- private toCanonicalFileName;
- constructor(host: ServerHost, logger: Logger, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller?: ITypingsInstaller, eventHandler?: ProjectServiceEventHandler);
- getChangedFiles_TestOnly(): ScriptInfo[];
- ensureInferredProjectsUpToDate_TestOnly(): void;
- updateTypingsForProject(response: SetTypings | InvalidateCachedTypings): void;
- setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions): void;
- stopWatchingDirectory(directory: string): void;
- findProject(projectName: string): Project;
- getDefaultProjectForFile(fileName: NormalizedPath, refreshInferredProjects: boolean): Project;
- private ensureInferredProjectsUpToDate();
- private findContainingExternalProject(fileName);
- getFormatCodeOptions(file?: NormalizedPath): FormatCodeSettings;
- private updateProjectGraphs(projects);
- private onSourceFileChanged(fileName);
- private handleDeletedFile(info);
- private onTypeRootFileChanged(project, fileName);
- private onSourceFileInDirectoryChangedForConfiguredProject(project, fileName);
- private handleChangeInSourceFileForConfiguredProject(project);
- private onConfigChangedForConfiguredProject(project);
- private onConfigFileAddedForInferredProject(fileName);
- private getCanonicalFileName(fileName);
- private removeProject(project);
- private assignScriptInfoToInferredProjectIfNecessary(info, addToListOfOpenFiles);
- private closeOpenFile(info);
- private openOrUpdateConfiguredProjectForFile(fileName);
- private findConfigFile(searchPath);
- private printProjects();
- private findConfiguredProjectByProjectName(configFileName);
- private findExternalProjectByProjectName(projectFileName);
- private convertConfigFileContentToProjectOptions(configFilename);
- private exceededTotalSizeLimitForNonTsFiles(options, fileNames, propertyReader);
- private createAndAddExternalProject(projectFileName, files, options, typingOptions);
- private reportConfigFileDiagnostics(configFileName, diagnostics, triggerFile?);
- private createAndAddConfiguredProject(configFileName, projectOptions, configFileErrors, clientFileName?);
- private watchConfigDirectoryForProject(project, options);
- private addFilesToProjectAndUpdateGraph(project, files, propertyReader, clientFileName, typingOptions, configFileErrors);
- private openConfigFile(configFileName, clientFileName?);
- private updateNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors);
- private updateConfiguredProject(project);
- createInferredProjectWithRootFileIfNecessary(root: ScriptInfo): InferredProject;
- getOrCreateScriptInfo(uncheckedFileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo;
- getScriptInfo(uncheckedFileName: string): ScriptInfo;
- getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): ScriptInfo;
- getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo;
- setHostConfiguration(args: protocol.ConfigureRequestArguments): void;
- closeLog(): void;
- reloadProjects(): void;
- refreshInferredProjects(): void;
- openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind): OpenConfiguredProjectResult;
- openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): OpenConfiguredProjectResult;
- closeClientFile(uncheckedFileName: string): void;
- private collectChanges(lastKnownProjectVersions, currentProjects, result);
- synchronizeProjectList(knownProjects: protocol.ProjectVersionInfo[]): ProjectFilesWithTSDiagnostics[];
- applyChangesInOpenFiles(openFiles: protocol.ExternalFile[], changedFiles: protocol.ChangedOpenFile[], closedFiles: string[]): void;
- private closeConfiguredProject(configFile);
- closeExternalProject(uncheckedFileName: string, suppressRefresh?: boolean): void;
- openExternalProject(proj: protocol.ExternalProject): void;
- }
-}
-declare namespace ts.server {
+ function generateSpaces(n: number): string;
+ function generateIndentString(n: number, editorOptions: EditorOptions): string;
interface PendingErrorCheck {
- fileName: NormalizedPath;
+ fileName: string;
project: Project;
}
namespace CommandNames {
const Brace = "brace";
- const BraceFull = "brace-full";
- const BraceCompletion = "braceCompletion";
const Change = "change";
const Close = "close";
const Completions = "completions";
- const CompletionsFull = "completions-full";
const CompletionDetails = "completionEntryDetails";
- const CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList";
- const CompileOnSaveEmitFile = "compileOnSaveEmitFile";
const Configure = "configure";
const Definition = "definition";
- const DefinitionFull = "definition-full";
const Exit = "exit";
const Format = "format";
const Formatonkey = "formatonkey";
- const FormatFull = "format-full";
- const FormatonkeyFull = "formatonkey-full";
- const FormatRangeFull = "formatRange-full";
const Geterr = "geterr";
const GeterrForProject = "geterrForProject";
+ const Implementation = "implementation";
const SemanticDiagnosticsSync = "semanticDiagnosticsSync";
const SyntacticDiagnosticsSync = "syntacticDiagnosticsSync";
const NavBar = "navbar";
- const NavBarFull = "navbar-full";
const Navto = "navto";
- const NavtoFull = "navto-full";
const Occurrences = "occurrences";
const DocumentHighlights = "documentHighlights";
- const DocumentHighlightsFull = "documentHighlights-full";
const Open = "open";
const Quickinfo = "quickinfo";
- const QuickinfoFull = "quickinfo-full";
const References = "references";
- const ReferencesFull = "references-full";
const Reload = "reload";
const Rename = "rename";
- const RenameInfoFull = "rename-full";
- const RenameLocationsFull = "renameLocations-full";
const Saveto = "saveto";
const SignatureHelp = "signatureHelp";
- const SignatureHelpFull = "signatureHelp-full";
const TypeDefinition = "typeDefinition";
const ProjectInfo = "projectInfo";
const ReloadProjects = "reloadProjects";
const Unknown = "unknown";
- const OpenExternalProject = "openExternalProject";
- const OpenExternalProjects = "openExternalProjects";
- const CloseExternalProject = "closeExternalProject";
- const SynchronizeProjectList = "synchronizeProjectList";
- const ApplyChangedToOpenFiles = "applyChangedToOpenFiles";
- const EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full";
- const Cleanup = "cleanup";
- const OutliningSpans = "outliningSpans";
- const TodoComments = "todoComments";
- const Indentation = "indentation";
- const DocCommentTemplate = "docCommentTemplate";
- const CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full";
- const NameOrDottedNameSpan = "nameOrDottedNameSpan";
- const BreakpointStatement = "breakpointStatement";
- const CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects";
}
- function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string;
+ interface ServerHost extends ts.System {
+ setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any;
+ clearTimeout(timeoutId: any): void;
+ }
class Session {
private host;
- protected readonly typingsInstaller: ITypingsInstaller;
private byteLength;
private hrtime;
- protected logger: Logger;
- protected readonly canUseEvents: boolean;
- private readonly gcTimer;
+ private logger;
protected projectService: ProjectService;
private errorTimer;
private immediateId;
private changeSeq;
- constructor(host: ServerHost, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller: ITypingsInstaller, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger, canUseEvents: boolean);
+ constructor(host: ServerHost, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger);
private handleEvent(event);
logError(err: Error, cmd: string): void;
+ private sendLineToClient(line);
send(msg: protocol.Message): void;
configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]): void;
event(info: any, eventName: string): void;
- output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void;
+ private response(info, cmdName, reqSeq?, errorMsg?);
+ output(body: any, commandName: string, requestSequence?: number, errorMessage?: string): void;
private semanticCheck(file, project);
private syntacticCheck(file, project);
+ private reloadProjects();
private updateProjectStructure(seq, matchSeq, ms?);
private updateErrorCheck(checkList, seq, matchSeq, ms?, followMs?, requireOpen?);
- private cleanProjects(caption, projects);
- private cleanup();
- private getEncodedSemanticClassifications(args);
- private getProject(projectFileName);
- private getCompilerOptionsDiagnostics(args);
- private convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo);
- private getDiagnosticsWorker(args, selector, includeLinePosition);
- private getDefinition(args, simplifiedResult);
- private getTypeDefinition(args);
- private getOccurrences(args);
+ private getDefinition(line, offset, fileName);
+ private getTypeDefinition(line, offset, fileName);
+ private getImplementation(line, offset, fileName);
+ private getOccurrences(line, offset, fileName);
+ private getDiagnosticsWorker(args, selector);
private getSyntacticDiagnosticsSync(args);
private getSemanticDiagnosticsSync(args);
- private getDocumentHighlights(args, simplifiedResult);
- private setCompilerOptionsForInferredProjects(args);
- private getProjectInfo(args);
- private getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList);
- private getRenameInfo(args);
- private getProjects(args);
- private getRenameLocations(args, simplifiedResult);
- private getReferences(args, simplifiedResult);
+ private getDocumentHighlights(line, offset, fileName, filesToSearch);
+ private getProjectInfo(fileName, needFileNameList);
+ private getRenameLocations(line, offset, fileName, findInComments, findInStrings);
+ private getReferences(line, offset, fileName);
private openClientFile(fileName, fileContent?, scriptKind?);
- private getPosition(args, scriptInfo);
- private getFileAndProject(args, errorOnMissingProject?);
- private getFileAndProjectWithoutRefreshingInferredProjects(args, errorOnMissingProject?);
- private getFileAndProjectWorker(uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject);
- private getOutliningSpans(args);
- private getTodoComments(args);
- private getDocCommentTemplate(args);
- private getIndentation(args);
- private getBreakpointStatement(args);
- private getNameOrDottedNameSpan(args);
- private isValidBraceCompletion(args);
- private getQuickInfoWorker(args, simplifiedResult);
- private getFormattingEditsForRange(args);
- private getFormattingEditsForRangeFull(args);
- private getFormattingEditsForDocumentFull(args);
- private getFormattingEditsAfterKeystrokeFull(args);
- private getFormattingEditsAfterKeystroke(args);
- private getCompletions(args, simplifiedResult);
- private getCompletionEntryDetails(args);
- private getCompileOnSaveAffectedFileList(args);
- private emitFile(args);
- private getSignatureHelpItems(args, simplifiedResult);
+ private getQuickInfo(line, offset, fileName);
+ private getFormattingEditsForRange(line, offset, endLine, endOffset, fileName);
+ private getFormattingEditsAfterKeystroke(line, offset, key, fileName);
+ private getCompletions(line, offset, prefix, fileName);
+ private getCompletionEntryDetails(line, offset, entryNames, fileName);
+ private getSignatureHelpItems(line, offset, fileName);
private getDiagnostics(delay, fileNames);
- private change(args);
- private reload(args, reqSeq);
+ private change(line, offset, endLine, endOffset, insertString, fileName);
+ private reload(fileName, tempFileName, reqSeq?);
private saveToTmp(fileName, tempFileName);
private closeClientFile(fileName);
- private decorateNavigationBarItem(project, fileName, items);
- private getNavigationBarItems(args, simplifiedResult);
- private getNavigateToItems(args, simplifiedResult);
- private getBraceMatching(args, simplifiedResult);
+ private decorateNavigationBarItem(project, fileName, items, lineIndex);
+ private getNavigationBarItems(fileName);
+ private getNavigateToItems(searchValue, fileName, maxResultCount?, currentFileOnly?);
+ private getBraceMatching(line, offset, fileName);
getDiagnosticsForProject(delay: number, fileName: string): void;
getCanonicalFileName(fileName: string): string;
exit(): void;
- private notRequired();
private requiredResponse(response);
private handlers;
addProtocolHandler(command: string, handler: (request: protocol.Request) => {
@@ -9835,6 +9307,227 @@ declare namespace ts.server {
}
}
declare namespace ts.server {
+ interface Logger {
+ close(): void;
+ isVerbose(): boolean;
+ loggingEnabled(): boolean;
+ perftrc(s: string): void;
+ info(s: string): void;
+ startGroup(): void;
+ endGroup(): void;
+ msg(s: string, type?: string): void;
+ }
+ const maxProgramSizeForNonTsFiles: number;
+ class ScriptInfo {
+ private host;
+ fileName: string;
+ isOpen: boolean;
+ svc: ScriptVersionCache;
+ children: ScriptInfo[];
+ defaultProject: Project;
+ fileWatcher: FileWatcher;
+ formatCodeOptions: FormatCodeOptions;
+ path: Path;
+ scriptKind: ScriptKind;
+ constructor(host: ServerHost, fileName: string, content: string, isOpen?: boolean);
+ setFormatOptions(formatOptions: protocol.FormatOptions): void;
+ close(): void;
+ addChild(childInfo: ScriptInfo): void;
+ snap(): LineIndexSnapshot;
+ getText(): string;
+ getLineInfo(line: number): ILineInfo;
+ editContent(start: number, end: number, newText: string): void;
+ getTextChangeRangeBetweenVersions(startVersion: number, endVersion: number): ts.TextChangeRange;
+ getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange;
+ }
+ class LSHost implements ts.LanguageServiceHost {
+ host: ServerHost;
+ project: Project;
+ ls: ts.LanguageService;
+ compilationSettings: ts.CompilerOptions;
+ filenameToScript: ts.FileMap;
+ roots: ScriptInfo[];
+ private resolvedModuleNames;
+ private resolvedTypeReferenceDirectives;
+ private moduleResolutionHost;
+ private getCanonicalFileName;
+ constructor(host: ServerHost, project: Project);
+ private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult);
+ resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
+ resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[];
+ getDefaultLibFileName(): string;
+ getScriptSnapshot(filename: string): ts.IScriptSnapshot;
+ setCompilationSettings(opt: ts.CompilerOptions): void;
+ lineAffectsRefs(filename: string, line: number): boolean;
+ getCompilationSettings(): CompilerOptions;
+ getScriptFileNames(): string[];
+ getScriptKind(fileName: string): ScriptKind;
+ getScriptVersion(filename: string): string;
+ getCurrentDirectory(): string;
+ getScriptIsOpen(filename: string): boolean;
+ removeReferencedFile(info: ScriptInfo): void;
+ getScriptInfo(filename: string): ScriptInfo;
+ addRoot(info: ScriptInfo): void;
+ removeRoot(info: ScriptInfo): void;
+ saveTo(filename: string, tmpfilename: string): void;
+ reloadScript(filename: string, tmpfilename: string, cb: () => any): void;
+ editScript(filename: string, start: number, end: number, newText: string): void;
+ fileExists(path: string): boolean;
+ directoryExists(path: string): boolean;
+ getDirectories(path: string): string[];
+ readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[];
+ readFile(path: string, encoding?: string): string;
+ lineToTextSpan(filename: string, line: number): ts.TextSpan;
+ lineOffsetToPosition(filename: string, line: number, offset: number): number;
+ positionToLineOffset(filename: string, position: number, lineIndex?: LineIndex): ILineInfo;
+ getLineIndex(filename: string): LineIndex;
+ }
+ interface ProjectOptions {
+ files?: string[];
+ wildcardDirectories?: ts.MapLike;
+ compilerOptions?: ts.CompilerOptions;
+ }
+ class Project {
+ projectService: ProjectService;
+ projectOptions: ProjectOptions;
+ languageServiceDiabled: boolean;
+ compilerService: CompilerService;
+ projectFilename: string;
+ projectFileWatcher: FileWatcher;
+ directoryWatcher: FileWatcher;
+ directoriesWatchedForWildcards: Map;
+ directoriesWatchedForTsconfig: string[];
+ program: ts.Program;
+ filenameToSourceFile: Map;
+ updateGraphSeq: number;
+ openRefCount: number;
+ constructor(projectService: ProjectService, projectOptions?: ProjectOptions, languageServiceDiabled?: boolean);
+ enableLanguageService(): void;
+ disableLanguageService(): void;
+ addOpenRef(): void;
+ deleteOpenRef(): number;
+ openReferencedFile(filename: string): ScriptInfo;
+ getRootFiles(): string[];
+ getFileNames(): string[];
+ getSourceFile(info: ScriptInfo): SourceFile;
+ getSourceFileFromName(filename: string, requireOpen?: boolean): SourceFile;
+ isRoot(info: ScriptInfo): boolean;
+ removeReferencedFile(info: ScriptInfo): void;
+ updateFileMap(): void;
+ finishGraph(): void;
+ updateGraph(): void;
+ isConfiguredProject(): string;
+ addRoot(info: ScriptInfo): void;
+ removeRoot(info: ScriptInfo): void;
+ filesToString(): string;
+ setProjectOptions(projectOptions: ProjectOptions): void;
+ }
+ interface ProjectOpenResult {
+ success?: boolean;
+ errorMsg?: string;
+ project?: Project;
+ }
+ function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[];
+ type ProjectServiceEvent = {
+ eventName: "context";
+ data: {
+ project: Project;
+ fileName: string;
+ };
+ } | {
+ eventName: "configFileDiag";
+ data: {
+ triggerFile?: string;
+ configFileName: string;
+ diagnostics: Diagnostic[];
+ };
+ };
+ interface ProjectServiceEventHandler {
+ (event: ProjectServiceEvent): void;
+ }
+ interface HostConfiguration {
+ formatCodeOptions: ts.FormatCodeOptions;
+ hostInfo: string;
+ }
+ class ProjectService {
+ host: ServerHost;
+ psLogger: Logger;
+ eventHandler: ProjectServiceEventHandler;
+ filenameToScriptInfo: Map;
+ openFileRoots: ScriptInfo[];
+ inferredProjects: Project[];
+ configuredProjects: Project[];
+ openFilesReferenced: ScriptInfo[];
+ openFileRootsConfigured: ScriptInfo[];
+ directoryWatchersForTsconfig: Map;
+ directoryWatchersRefCount: Map;
+ hostConfiguration: HostConfiguration;
+ timerForDetectingProjectFileListChanges: Map;
+ constructor(host: ServerHost, psLogger: Logger, eventHandler?: ProjectServiceEventHandler);
+ addDefaultHostConfiguration(): void;
+ getFormatCodeOptions(file?: string): FormatCodeOptions;
+ watchedFileChanged(fileName: string): void;
+ directoryWatchedForSourceFilesChanged(project: Project, fileName: string): void;
+ startTimerForDetectingProjectFileListChanges(project: Project): void;
+ handleProjectFileListChanges(project: Project): void;
+ reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile?: string): void;
+ directoryWatchedForTsconfigChanged(fileName: string): void;
+ getCanonicalFileName(fileName: string): string;
+ watchedProjectConfigFileChanged(project: Project): void;
+ log(msg: string, type?: string): void;
+ setHostConfiguration(args: ts.server.protocol.ConfigureRequestArguments): void;
+ closeLog(): void;
+ createInferredProject(root: ScriptInfo): Project;
+ fileDeletedInFilesystem(info: ScriptInfo): void;
+ updateConfiguredProjectList(): void;
+ removeProject(project: Project): void;
+ setConfiguredProjectRoot(info: ScriptInfo): boolean;
+ addOpenFile(info: ScriptInfo): void;
+ closeOpenFile(info: ScriptInfo): void;
+ findReferencingProjects(info: ScriptInfo, excludedProject?: Project): Project[];
+ reloadProjects(): void;
+ updateProjectStructure(): void;
+ getScriptInfo(filename: string): ScriptInfo;
+ openFile(fileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo;
+ findConfigFile(searchPath: string): string;
+ openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind): {
+ configFileName?: string;
+ configFileErrors?: Diagnostic[];
+ };
+ openOrUpdateConfiguredProjectForFile(fileName: string): {
+ configFileName?: string;
+ configFileErrors?: Diagnostic[];
+ };
+ closeClientFile(filename: string): void;
+ getProjectForFile(filename: string): Project;
+ printProjectsForFile(filename: string): void;
+ printProjects(): void;
+ configProjectIsActive(fileName: string): boolean;
+ findConfiguredProjectByConfigFile(configFileName: string): Project;
+ configFileToProjectOptions(configFilename: string): {
+ projectOptions?: ProjectOptions;
+ errors: Diagnostic[];
+ };
+ private exceedTotalNonTsFileSizeLimit(fileNames);
+ openConfigFile(configFilename: string, clientFileName?: string): {
+ project?: Project;
+ errors: Diagnostic[];
+ };
+ updateConfiguredProject(project: Project): Diagnostic[];
+ createProject(projectFilename: string, projectOptions?: ProjectOptions, languageServiceDisabled?: boolean): Project;
+ }
+ class CompilerService {
+ project: Project;
+ host: LSHost;
+ languageService: ts.LanguageService;
+ classifier: ts.Classifier;
+ settings: ts.CompilerOptions;
+ documentRegistry: DocumentRegistry;
+ constructor(project: Project, opt?: ts.CompilerOptions);
+ setCompilerOptions(opt: ts.CompilerOptions): void;
+ isExternalModule(filename: string): boolean;
+ static getDefaultFormatCodeOptions(host: ServerHost): ts.FormatCodeOptions;
+ }
interface LineCollection {
charCount(): number;
lineCount(): number;
@@ -9873,17 +9566,15 @@ declare namespace ts.server {
changes: TextChange[];
versions: LineIndexSnapshot[];
minVersion: number;
- private host;
private currentVersion;
+ private host;
static changeNumberThreshold: number;
static changeLengthThreshold: number;
static maxVersions: number;
- private versionToIndex(version);
- private currentVersionToIndex();
edit(pos: number, deleteLen: number, insertedText?: string): void;
latest(): LineIndexSnapshot;
latestVersion(): number;
- reloadFromFile(filename: string): void;
+ reloadFromFile(filename: string, cb?: () => any): void;
reload(script: string): void;
getSnapshot(): LineIndexSnapshot;
getTextChangesBetweenVersions(oldVersion: number, newVersion: number): TextChangeRange;
@@ -9952,7 +9643,10 @@ declare namespace ts.server {
}
class LineLeaf implements LineCollection {
text: string;
+ udata: any;
constructor(text: string);
+ setUdata(data: any): void;
+ getUdata(): any;
isLeaf(): boolean;
walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void;
charCount(): number;
@@ -9986,7 +9680,6 @@ declare namespace ts {
getNewLine?(): string;
getProjectVersion?(): string;
useCaseSensitiveFileNames?(): boolean;
- getTypeRootsVersion?(): number;
readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string;
readFile(path: string, encoding?: string): string;
fileExists(path: string): boolean;
@@ -10082,7 +9775,6 @@ declare namespace ts {
trace(s: string): void;
error(s: string): void;
getProjectVersion(): string;
- getTypeRootsVersion(): number;
useCaseSensitiveFileNames(): boolean;
getCompilationSettings(): CompilerOptions;
getScriptFileNames(): string[];
@@ -10132,4 +9824,4 @@ declare namespace ts {
declare namespace TypeScript.Services {
const TypeScriptServicesFactory: typeof ts.TypeScriptServicesFactory;
}
-declare const toolsVersion = "2.0";
+declare const toolsVersion = "2.1";
diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js
index e6d64b93a0c..a8fa909efcc 100644
--- a/lib/tsserverlibrary.js
+++ b/lib/tsserverlibrary.js
@@ -150,7 +150,6 @@ var ts;
contains: contains,
remove: remove,
forEachValue: forEachValueInMap,
- getKeys: getKeys,
clear: clear
};
function forEachValueInMap(f) {
@@ -158,13 +157,6 @@ var ts;
f(key, files[key]);
}
}
- function getKeys() {
- var keys = [];
- for (var key in files) {
- keys.push(key);
- }
- return keys;
- }
function get(path) {
return files[toKey(path)];
}
@@ -541,22 +533,16 @@ var ts;
: undefined;
}
ts.lastOrUndefined = lastOrUndefined;
- function binarySearch(array, value, comparer) {
- if (!array || array.length === 0) {
- return -1;
- }
+ function binarySearch(array, value) {
var low = 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) {
+ if (midValue === value) {
return middle;
}
- else if (comparer(midValue, value) > 0) {
+ else if (midValue > value) {
high = middle - 1;
}
else {
@@ -1026,45 +1012,10 @@ var ts;
return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1;
}
ts.isUrl = isUrl;
- function isExternalModuleNameRelative(moduleName) {
- return /^\.\.?($|[\\/])/.test(moduleName);
- }
- ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
- function getEmitScriptTarget(compilerOptions) {
- return compilerOptions.target || 0;
- }
- ts.getEmitScriptTarget = getEmitScriptTarget;
- function getEmitModuleKind(compilerOptions) {
- return typeof compilerOptions.module === "number" ?
- compilerOptions.module :
- getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS;
- }
- ts.getEmitModuleKind = getEmitModuleKind;
- function hasZeroOrOneAsteriskCharacter(str) {
- var seenAsterisk = false;
- for (var i = 0; i < str.length; i++) {
- if (str.charCodeAt(i) === 42) {
- if (!seenAsterisk) {
- seenAsterisk = true;
- }
- else {
- return false;
- }
- }
- }
- return true;
- }
- ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
function isRootedDiskPath(path) {
return getRootLength(path) !== 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
- function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
- return !isRootedDiskPath(absoluteOrRelativePath)
- ? absoluteOrRelativePath
- : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false);
- }
- ts.convertToRelativePath = convertToRelativePath;
function normalizedPathComponents(path, rootLength) {
var normalizedParts = getNormalizedParts(path, rootLength);
return [path.substr(0, rootLength)].concat(normalizedParts);
@@ -1438,14 +1389,6 @@ var ts;
return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
ts.getSupportedExtensions = getSupportedExtensions;
- function hasJavaScriptFileExtension(fileName) {
- return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
- }
- ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
- function hasTypeScriptFileExtension(fileName) {
- return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
- }
- ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension;
function isSupportedSourceFileName(fileName, compilerOptions) {
if (!fileName) {
return false;
@@ -1624,10 +1567,6 @@ var ts;
: (function (fileName) { return fileName.toLowerCase(); });
}
ts.createGetCanonicalFileName = createGetCanonicalFileName;
- function positionIsSynthesized(pos) {
- return !(pos >= 0);
- }
- ts.positionIsSynthesized = positionIsSynthesized;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -2058,37 +1997,18 @@ var ts;
realpath: realpath
};
}
- function recursiveCreateDirectory(directoryPath, sys) {
- var basePath = ts.getDirectoryPath(directoryPath);
- var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath);
- if (shouldCreateParent) {
- recursiveCreateDirectory(basePath, sys);
- }
- if (shouldCreateParent || !sys.directoryExists(directoryPath)) {
- sys.createDirectory(directoryPath);
- }
- }
- var sys;
if (typeof ChakraHost !== "undefined") {
- sys = getChakraSystem();
+ return getChakraSystem();
}
else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
- sys = getWScriptSystem();
+ return getWScriptSystem();
}
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
- sys = getNodeSystem();
+ return getNodeSystem();
}
- if (sys) {
- var originalWriteFile_1 = sys.writeFile;
- sys.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);
- };
+ else {
+ return undefined;
}
- return sys;
})();
})(ts || (ts = {}));
var ts;
@@ -2808,7 +2728,6 @@ var ts;
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." },
Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." },
- Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -4415,13 +4334,11 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
ts.optionDeclarations = [
{
name: "charset",
type: "string"
},
- ts.compileOnSaveCommandLineOption,
{
name: "declaration",
shortName: "d",
@@ -5045,11 +4962,10 @@ var ts;
return parseConfigFileTextToJson(fileName, text);
}
ts.readConfigFile = readConfigFile;
- function parseConfigFileTextToJson(fileName, jsonText, stripComments) {
- if (stripComments === void 0) { stripComments = true; }
+ function parseConfigFileTextToJson(fileName, jsonText) {
try {
- var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText;
- return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} };
+ var jsonTextWithoutComments = removeComments(jsonText);
+ return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} };
}
catch (e) {
return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) };
@@ -5183,15 +5099,13 @@ var ts;
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,
typingOptions: typingOptions,
raw: json,
errors: errors,
- wildcardDirectories: wildcardDirectories,
- compileOnSave: compileOnSave
+ wildcardDirectories: wildcardDirectories
};
function tryExtendsName(extendedConfig) {
if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) {
@@ -5269,17 +5183,6 @@ var ts;
var _b;
}
ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
- 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;
- }
- ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson;
function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
var errors = [];
var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
@@ -5293,9 +5196,7 @@ var ts;
}
ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
- var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
- ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true }
- : {};
+ var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {};
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
return options;
}
@@ -5494,381 +5395,6 @@ var ts;
}
})(ts || (ts = {}));
var ts;
-(function (ts) {
- var JsTyping;
- (function (JsTyping) {
- ;
- ;
- var safeList;
- var EmptySafeList = ts.createMap();
- function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) {
- var inferredTypings = ts.createMap();
- if (!typingOptions || !typingOptions.enableAutoDiscovery) {
- return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
- }
- fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) {
- var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f));
- return kind === 1 || kind === 2;
- });
- if (!safeList) {
- var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
- safeList = result.config ? ts.createMap(result.config) : EmptySafeList;
- }
- var filesToWatch = [];
- var searchDirs = [];
- var exclude = [];
- mergeTypings(typingOptions.include);
- exclude = typingOptions.exclude || [];
- var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath);
- if (projectRootPath !== undefined) {
- 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);
- for (var name_7 in packageNameToTypingLocation) {
- if (name_7 in inferredTypings && !inferredTypings[name_7]) {
- inferredTypings[name_7] = packageNameToTypingLocation[name_7];
- }
- }
- for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) {
- var excludeTypingName = exclude_1[_a];
- delete inferredTypings[excludeTypingName];
- }
- var newTypingNames = [];
- var cachedTypingPaths = [];
- for (var typing in inferredTypings) {
- if (inferredTypings[typing] !== undefined) {
- cachedTypingPaths.push(inferredTypings[typing]);
- }
- else {
- newTypingNames.push(typing);
- }
- }
- return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
- function mergeTypings(typingNames) {
- if (!typingNames) {
- return;
- }
- for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) {
- var typing = typingNames_1[_i];
- if (!(typing in inferredTypings)) {
- inferredTypings[typing] = undefined;
- }
- }
- }
- function getTypingNamesFromJson(jsonPath, filesToWatch) {
- var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); });
- if (result.config) {
- var jsonConfig = result.config;
- filesToWatch.push(jsonPath);
- if (jsonConfig.dependencies) {
- mergeTypings(ts.getOwnKeys(jsonConfig.dependencies));
- }
- if (jsonConfig.devDependencies) {
- mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies));
- }
- if (jsonConfig.optionalDependencies) {
- mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies));
- }
- if (jsonConfig.peerDependencies) {
- mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies));
- }
- }
- }
- function getTypingNamesFromSourceFileNames(fileNames) {
- var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension);
- var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); });
- var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); });
- if (safeList !== EmptySafeList) {
- mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; }));
- }
- var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; });
- if (hasJsxFile) {
- mergeTypings(["react"]);
- }
- }
- function getTypingNamesFromNodeModuleFolder(nodeModulesPath) {
- if (!host.directoryExists(nodeModulesPath)) {
- return;
- }
- var typingNames = [];
- var fileNames = host.readDirectory(nodeModulesPath, [".json"], undefined, undefined, 2);
- for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
- var fileName = fileNames_2[_i];
- var normalizedFileName = ts.normalizePath(fileName);
- if (ts.getBaseFileName(normalizedFileName) !== "package.json") {
- continue;
- }
- var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- if (!result.config) {
- continue;
- }
- var packageJson = result.config;
- if (packageJson._requiredBy &&
- ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
- continue;
- }
- if (!packageJson.name) {
- continue;
- }
- if (packageJson.typings) {
- var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName));
- inferredTypings[packageJson.name] = absolutePath;
- }
- else {
- typingNames.push(packageJson.name);
- }
- }
- mergeTypings(typingNames);
- }
- }
- JsTyping.discoverTypings = discoverTypings;
- })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- (function (LogLevel) {
- LogLevel[LogLevel["terse"] = 0] = "terse";
- LogLevel[LogLevel["normal"] = 1] = "normal";
- LogLevel[LogLevel["requestTime"] = 2] = "requestTime";
- LogLevel[LogLevel["verbose"] = 3] = "verbose";
- })(server.LogLevel || (server.LogLevel = {}));
- var LogLevel = server.LogLevel;
- server.emptyArray = [];
- var Msg;
- (function (Msg) {
- Msg.Err = "Err";
- Msg.Info = "Info";
- Msg.Perf = "Perf";
- })(Msg = server.Msg || (server.Msg = {}));
- function getProjectRootPath(project) {
- switch (project.projectKind) {
- case server.ProjectKind.Configured:
- return ts.getDirectoryPath(project.getProjectName());
- case server.ProjectKind.Inferred:
- return "";
- case server.ProjectKind.External:
- var projectName = ts.normalizeSlashes(project.getProjectName());
- return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName;
- }
- }
- function createInstallTypingsRequest(project, typingOptions, cachePath) {
- return {
- projectName: project.getProjectName(),
- fileNames: project.getFileNames(),
- compilerOptions: project.getCompilerOptions(),
- typingOptions: typingOptions,
- projectRootPath: getProjectRootPath(project),
- cachePath: cachePath,
- kind: "discover"
- };
- }
- server.createInstallTypingsRequest = createInstallTypingsRequest;
- var Errors;
- (function (Errors) {
- function ThrowNoProject() {
- throw new Error("No Project.");
- }
- Errors.ThrowNoProject = ThrowNoProject;
- function ThrowProjectLanguageServiceDisabled() {
- throw new Error("The project's language service is disabled.");
- }
- Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled;
- function ThrowProjectDoesNotContainDocument(fileName, project) {
- throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'");
- }
- Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument;
- })(Errors = server.Errors || (server.Errors = {}));
- function getDefaultFormatCodeSettings(host) {
- return {
- indentSize: 4,
- tabSize: 4,
- newLineCharacter: host.newLine || "\n",
- convertTabsToSpaces: true,
- indentStyle: ts.IndentStyle.Smart,
- insertSpaceAfterCommaDelimiter: true,
- insertSpaceAfterSemicolonInForStatements: true,
- insertSpaceBeforeAndAfterBinaryOperators: true,
- insertSpaceAfterKeywordsInControlFlowStatements: true,
- insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
- insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
- insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
- insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
- placeOpenBraceOnNewLineForFunctions: false,
- placeOpenBraceOnNewLineForControlBlocks: false
- };
- }
- server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings;
- function mergeMaps(target, source) {
- for (var key in source) {
- if (ts.hasProperty(source, key)) {
- target[key] = source[key];
- }
- }
- }
- server.mergeMaps = mergeMaps;
- function removeItemFromSet(items, itemToRemove) {
- if (items.length === 0) {
- return;
- }
- var index = items.indexOf(itemToRemove);
- if (index < 0) {
- return;
- }
- if (index === items.length - 1) {
- items.pop();
- }
- else {
- items[index] = items.pop();
- }
- }
- server.removeItemFromSet = removeItemFromSet;
- function toNormalizedPath(fileName) {
- return ts.normalizePath(fileName);
- }
- server.toNormalizedPath = toNormalizedPath;
- function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) {
- var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory);
- return getCanonicalFileName(f);
- }
- server.normalizedPathToPath = normalizedPathToPath;
- function asNormalizedPath(fileName) {
- return fileName;
- }
- server.asNormalizedPath = asNormalizedPath;
- function createNormalizedPathMap() {
- var map = Object.create(null);
- return {
- get: function (path) {
- return map[path];
- },
- set: function (path, value) {
- map[path] = value;
- },
- contains: function (path) {
- return ts.hasProperty(map, path);
- },
- remove: function (path) {
- delete map[path];
- }
- };
- }
- server.createNormalizedPathMap = createNormalizedPathMap;
- function throwLanguageServiceIsDisabledError() {
- throw new Error("LanguageService is disabled");
- }
- server.nullLanguageService = {
- cleanupSemanticCache: function () { return throwLanguageServiceIsDisabledError(); },
- getSyntacticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); },
- getSemanticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); },
- getCompilerOptionsDiagnostics: function () { return throwLanguageServiceIsDisabledError(); },
- getSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); },
- getEncodedSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); },
- getSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); },
- getEncodedSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); },
- getCompletionsAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- findReferences: function () { return throwLanguageServiceIsDisabledError(); },
- getCompletionEntryDetails: function () { return throwLanguageServiceIsDisabledError(); },
- getQuickInfoAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- findRenameLocations: function () { return throwLanguageServiceIsDisabledError(); },
- getNameOrDottedNameSpan: function () { return throwLanguageServiceIsDisabledError(); },
- getBreakpointStatementAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getBraceMatchingAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getSignatureHelpItems: function () { return throwLanguageServiceIsDisabledError(); },
- getDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getRenameInfo: function () { return throwLanguageServiceIsDisabledError(); },
- getTypeDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getReferencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getDocumentHighlights: function () { return throwLanguageServiceIsDisabledError(); },
- getOccurrencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getNavigateToItems: function () { return throwLanguageServiceIsDisabledError(); },
- getNavigationBarItems: function () { return throwLanguageServiceIsDisabledError(); },
- getOutliningSpans: function () { return throwLanguageServiceIsDisabledError(); },
- getTodoComments: function () { return throwLanguageServiceIsDisabledError(); },
- getIndentationAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getFormattingEditsForRange: function () { return throwLanguageServiceIsDisabledError(); },
- getFormattingEditsForDocument: function () { return throwLanguageServiceIsDisabledError(); },
- getFormattingEditsAfterKeystroke: function () { return throwLanguageServiceIsDisabledError(); },
- getDocCommentTemplateAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- isValidBraceCompletionAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getEmitOutput: function () { return throwLanguageServiceIsDisabledError(); },
- getProgram: function () { return throwLanguageServiceIsDisabledError(); },
- getNonBoundSourceFile: function () { return throwLanguageServiceIsDisabledError(); },
- dispose: function () { return throwLanguageServiceIsDisabledError(); },
- getCompletionEntrySymbol: function () { return throwLanguageServiceIsDisabledError(); },
- getImplementationAtPosition: function () { return throwLanguageServiceIsDisabledError(); },
- getSourceFile: function () { return throwLanguageServiceIsDisabledError(); }
- };
- server.nullLanguageServiceHost = {
- setCompilationSettings: function () { return undefined; },
- notifyFileRemoved: function () { return undefined; }
- };
- function isInferredProjectName(name) {
- return /dev\/null\/inferredProject\d+\*/.test(name);
- }
- server.isInferredProjectName = isInferredProjectName;
- function makeInferredProjectName(counter) {
- return "/dev/null/inferredProject" + counter + "*";
- }
- server.makeInferredProjectName = makeInferredProjectName;
- var ThrottledOperations = (function () {
- function ThrottledOperations(host) {
- this.host = host;
- this.pendingTimeouts = ts.createMap();
- }
- ThrottledOperations.prototype.schedule = function (operationId, delay, cb) {
- if (ts.hasProperty(this.pendingTimeouts, operationId)) {
- this.host.clearTimeout(this.pendingTimeouts[operationId]);
- }
- this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb);
- };
- ThrottledOperations.run = function (self, operationId, cb) {
- delete self.pendingTimeouts[operationId];
- cb();
- };
- return ThrottledOperations;
- }());
- server.ThrottledOperations = ThrottledOperations;
- var GcTimer = (function () {
- function GcTimer(host, delay, logger) {
- this.host = host;
- this.delay = delay;
- this.logger = logger;
- }
- GcTimer.prototype.scheduleCollect = function () {
- if (!this.host.gc || this.timerId != undefined) {
- return;
- }
- this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this);
- };
- GcTimer.run = function (self) {
- self.timerId = undefined;
- var log = self.logger.hasLevel(LogLevel.requestTime);
- var before = log && self.host.getMemoryUsage();
- self.host.gc();
- if (log) {
- var after = self.host.getMemoryUsage();
- self.logger.perftrc("GC::before " + before + ", after " + after);
- }
- };
- return GcTimer;
- }());
- server.GcTimer = GcTimer;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
(function (ts) {
ts.externalHelpersModuleNameText = "tslib";
function getDeclarationOfKind(symbol, kind) {
@@ -6504,9 +6030,9 @@ var ts;
return;
default:
if (isFunctionLike(node)) {
- var name_8 = node.name;
- if (name_8 && name_8.kind === 140) {
- traverse(name_8.expression);
+ var name_7 = node.name;
+ if (name_7 && name_7.kind === 140) {
+ traverse(name_7.expression);
return;
}
}
@@ -6917,6 +6443,10 @@ var ts;
return false;
}
ts.isPartOfExpression = isPartOfExpression;
+ function isExternalModuleNameRelative(moduleName) {
+ return /^\.\.?($|[\\/])/.test(moduleName);
+ }
+ ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
var moduleState = ts.getModuleInstanceState(node);
return moduleState === 1 ||
@@ -7163,8 +6693,8 @@ var ts;
}
}
else if (param.name.kind === 69) {
- var name_9 = param.name.text;
- var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_9; });
+ var name_8 = param.name.text;
+ var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_8; });
if (paramTags) {
return paramTags;
}
@@ -7514,10 +7044,14 @@ var ts;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(node) {
- return ts.positionIsSynthesized(node.pos)
- || ts.positionIsSynthesized(node.end);
+ return positionIsSynthesized(node.pos)
+ || positionIsSynthesized(node.end);
}
ts.nodeIsSynthesized = nodeIsSynthesized;
+ function positionIsSynthesized(pos) {
+ return !(pos >= 0);
+ }
+ ts.positionIsSynthesized = positionIsSynthesized;
function getOriginalNode(node) {
if (node) {
while (node.original !== undefined) {
@@ -7953,16 +7487,28 @@ var ts;
function getDeclarationEmitOutputFilePath(sourceFile, host) {
var options = host.getCompilerOptions();
var outputDir = options.declarationDir || options.outDir;
- var path = outputDir
- ? getSourceFilePathInNewDir(sourceFile, host, outputDir)
- : sourceFile.fileName;
- return ts.removeFileExtension(path) + ".d.ts";
+ if (options.declaration) {
+ var path = outputDir
+ ? getSourceFilePathInNewDir(sourceFile, host, outputDir)
+ : sourceFile.fileName;
+ return ts.removeFileExtension(path) + ".d.ts";
+ }
}
ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
+ function getEmitScriptTarget(compilerOptions) {
+ return compilerOptions.target || 0;
+ }
+ ts.getEmitScriptTarget = getEmitScriptTarget;
+ function getEmitModuleKind(compilerOptions) {
+ return typeof compilerOptions.module === "number" ?
+ compilerOptions.module :
+ getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS;
+ }
+ ts.getEmitModuleKind = getEmitModuleKind;
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- var moduleKind = ts.getEmitModuleKind(options);
+ var moduleKind = getEmitModuleKind(options);
var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
var sourceFiles = host.getSourceFiles();
return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule);
@@ -7979,7 +7525,7 @@ var ts;
function isBundleEmitNonExternalModule(sourceFile) {
return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile);
}
- function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) {
+ function forEachTransformedEmitFile(host, sourceFiles, action) {
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
onBundledEmit(host, sourceFiles);
@@ -8006,7 +7552,7 @@ var ts;
}
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && emitOnlyDtsFiles ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
+ var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false);
}
function onBundledEmit(host, sourceFiles) {
@@ -8022,7 +7568,7 @@ var ts;
function getSourceMapFilePath(jsFilePath, options) {
return options.sourceMap ? jsFilePath + ".map" : undefined;
}
- function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) {
+ function forEachExpectedEmitFile(host, action, targetSourceFile) {
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
onBundledEmit(host);
@@ -8049,19 +7595,18 @@ var ts;
}
}
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
var emitFileNames = {
jsFilePath: jsFilePath,
sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
- declarationFilePath: declarationFilePath
+ declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined
};
- action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles);
+ action(emitFileNames, [sourceFile], false);
}
function onBundledEmit(host) {
var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) &&
!host.isSourceFileFromExternalLibrary(sourceFile) &&
(!ts.isExternalModule(sourceFile) ||
- !!ts.getEmitModuleKind(options)); });
+ !!getEmitModuleKind(options)); });
if (bundledSources.length) {
var jsFilePath = options.outFile || options.out;
var emitFileNames = {
@@ -8069,7 +7614,7 @@ var ts;
sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined
};
- action(emitFileNames, bundledSources, true, emitOnlyDtsFiles);
+ action(emitFileNames, bundledSources, true);
}
}
}
@@ -8426,6 +7971,14 @@ var ts;
return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined;
}
ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
+ function hasJavaScriptFileExtension(fileName) {
+ return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
+ function hasTypeScriptFileExtension(fileName) {
+ return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension;
function tryExtractTypeScriptExtension(fileName) {
return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
}
@@ -8516,6 +8069,12 @@ var ts;
return result;
}
ts.convertToBase64 = convertToBase64;
+ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
+ return !ts.isRootedDiskPath(absoluteOrRelativePath)
+ ? absoluteOrRelativePath
+ : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false);
+ }
+ ts.convertToRelativePath = convertToRelativePath;
var carriageReturnLineFeed = "\r\n";
var lineFeed = "\n";
function getNewLineCharacter(options) {
@@ -8604,9 +8163,9 @@ var ts;
if (syntaxKindCache[kind]) {
return syntaxKindCache[kind];
}
- for (var name_10 in syntaxKindEnum) {
- if (syntaxKindEnum[name_10] === kind) {
- return syntaxKindCache[kind] = kind.toString() + " (" + name_10 + ")";
+ for (var name_9 in syntaxKindEnum) {
+ if (syntaxKindEnum[name_9] === kind) {
+ return syntaxKindCache[kind] = kind.toString() + " (" + name_9 + ")";
}
}
}
@@ -8616,7 +8175,7 @@ var ts;
}
ts.formatSyntaxKind = formatSyntaxKind;
function movePos(pos, value) {
- return ts.positionIsSynthesized(pos) ? -1 : pos + value;
+ return positionIsSynthesized(pos) ? -1 : pos + value;
}
ts.movePos = movePos;
function createRange(pos, end) {
@@ -8685,7 +8244,7 @@ var ts;
}
ts.positionsAreOnSameLine = positionsAreOnSameLine;
function getStartPositionOfRange(range, sourceFile) {
- return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
+ return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
}
ts.getStartPositionOfRange = getStartPositionOfRange;
function collectExternalModuleInfo(sourceFile, resolver) {
@@ -8722,8 +8281,8 @@ var ts;
else {
for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) {
var specifier = _c[_b];
- var name_11 = (specifier.propertyName || specifier.name).text;
- (exportSpecifiers[name_11] || (exportSpecifiers[name_11] = [])).push(specifier);
+ var name_10 = (specifier.propertyName || specifier.name).text;
+ (exportSpecifiers[name_10] || (exportSpecifiers[name_10] = [])).push(specifier);
}
}
break;
@@ -9443,600 +9002,6 @@ var ts;
ts.getCombinedNodeFlags = getCombinedNodeFlags;
})(ts || (ts = {}));
var ts;
-(function (ts) {
- function trace(host, message) {
- host.trace(ts.formatMessage.apply(undefined, arguments));
- }
- ts.trace = trace;
- function isTraceEnabled(compilerOptions, host) {
- return compilerOptions.traceResolution && host.trace !== undefined;
- }
- ts.isTraceEnabled = isTraceEnabled;
- function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) {
- return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
- }
- ts.createResolvedModule = createResolvedModule;
- function moduleHasNonRelativeName(moduleName) {
- return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
- }
- function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
- var jsonContent = readJson(packageJsonPath, state.host);
- function tryReadFromField(fieldName) {
- if (ts.hasProperty(jsonContent, fieldName)) {
- var typesFile = jsonContent[fieldName];
- if (typeof typesFile === "string") {
- var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1);
- }
- return typesFilePath_1;
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
- }
- }
- }
- }
- var typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
- if (typesFilePath) {
- return typesFilePath;
- }
- if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main);
- }
- var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main));
- return mainFilePath;
- }
- return undefined;
- }
- function readJson(path, host) {
- try {
- var jsonText = host.readFile(path);
- return jsonText ? JSON.parse(jsonText) : {};
- }
- catch (e) {
- return {};
- }
- }
- var typeReferenceExtensions = [".d.ts"];
- 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();
- }
- return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
- }
- ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
- function getDefaultTypeRoots(currentDirectory, host) {
- if (!host.directoryExists) {
- return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
- }
- var typeRoots;
- while (true) {
- var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes);
- if (host.directoryExists(atTypes)) {
- (typeRoots || (typeRoots = [])).push(atTypes);
- }
- var parent_6 = ts.getDirectoryPath(currentDirectory);
- if (parent_6 === currentDirectory) {
- break;
- }
- currentDirectory = parent_6;
- }
- return typeRoots;
- }
- var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
- function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
- var traceEnabled = isTraceEnabled(options, host);
- var moduleResolutionState = {
- compilerOptions: options,
- host: host,
- skipTsx: true,
- 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 = [];
- if (typeRoots && typeRoots.length) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
- }
- var primarySearchPaths = typeRoots;
- for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) {
- var typeRoot = primarySearchPaths_1[_i];
- var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
- var candidateDirectory = ts.getDirectoryPath(candidate);
- var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState);
- if (resolvedFile_1) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true);
- }
- return {
- resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 },
- failedLookupLocations: failedLookupLocations
- };
- }
- }
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
- }
- }
- var resolvedFile;
- var initialLocationForSecondaryLookup;
- if (containingFile) {
- initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile);
- }
- if (initialLocationForSecondaryLookup !== undefined) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
- }
- resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false);
- if (traceEnabled) {
- if (resolvedFile) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
- }
- else {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
- }
- }
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
- }
- }
- return {
- resolvedTypeReferenceDirective: resolvedFile
- ? { primary: false, resolvedFileName: resolvedFile }
- : undefined,
- failedLookupLocations: failedLookupLocations
- };
- }
- ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
- function getAutomaticTypeDirectiveNames(options, host) {
- if (options.types) {
- return options.types;
- }
- 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));
- var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
- if (!isNotNeededPackage) {
- result.push(ts.getBaseFileName(normalized));
- }
- }
- }
- }
- }
- }
- return result;
- }
- ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
- function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
- }
- 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]);
- }
- }
- var result;
- switch (moduleResolution) {
- case ts.ModuleResolutionKind.NodeJs:
- result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
- case ts.ModuleResolutionKind.Classic:
- result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
- }
- 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;
- }
- ts.resolveModuleName = resolveModuleName;
- function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
- if (moduleHasNonRelativeName(moduleName)) {
- return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
- }
- else {
- return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
- }
- }
- function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
- if (!state.compilerOptions.rootDirs) {
- return undefined;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
- }
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- var matchedRootDir;
- var matchedNormalizedPrefix;
- for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
- var rootDir = _a[_i];
- var normalizedRoot = ts.normalizePath(rootDir);
- if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
- normalizedRoot += ts.directorySeparator;
- }
- var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
- (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
- }
- if (isLongestMatchingPrefix) {
- matchedNormalizedPrefix = normalizedRoot;
- matchedRootDir = rootDir;
- }
- }
- if (matchedNormalizedPrefix) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
- }
- var suffix = candidate.substr(matchedNormalizedPrefix.length);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
- }
- var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
- if (resolvedFileName) {
- return resolvedFileName;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
- }
- for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
- var rootDir = _c[_b];
- if (rootDir === matchedRootDir) {
- continue;
- }
- var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
- }
- var baseDirectory = ts.getDirectoryPath(candidate_1);
- var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
- if (resolvedFileName_1) {
- return resolvedFileName_1;
- }
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
- }
- }
- return undefined;
- }
- function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) {
- if (!state.compilerOptions.baseUrl) {
- return undefined;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
- }
- var matchedPattern = undefined;
- if (state.compilerOptions.paths) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
- }
- matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
- }
- if (matchedPattern) {
- var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
- var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
- }
- for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) {
- var subst = _a[_i];
- var path = matchedStar ? subst.replace("*", matchedStar) : subst;
- var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
- }
- var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- if (resolvedFileName) {
- return resolvedFileName;
- }
- }
- return undefined;
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
- }
- return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- }
- }
- 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) {
- return patternString;
- }
- }
- return findBestPatternMatch(patterns, function (_) { return _; }, candidate);
- }
- function patternText(_a) {
- var prefix = _a.prefix, suffix = _a.suffix;
- return prefix + "*" + suffix;
- }
- function matchedText(pattern, candidate) {
- ts.Debug.assert(isPatternMatch(pattern, candidate));
- return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
- }
- function findBestPatternMatch(values, getPattern, candidate) {
- var matchedValue = undefined;
- 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;
- }
- ts.findBestPatternMatch = findBestPatternMatch;
- function isPatternMatch(_a, candidate) {
- var prefix = _a.prefix, suffix = _a.suffix;
- return candidate.length >= prefix.length + suffix.length &&
- ts.startsWith(candidate, prefix) &&
- ts.endsWith(candidate, suffix);
- }
- function tryParsePattern(pattern) {
- ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern));
- var indexOfStar = pattern.indexOf("*");
- return indexOfStar === -1 ? undefined : {
- prefix: pattern.substr(0, indexOfStar),
- suffix: pattern.substr(indexOfStar + 1)
- };
- }
- ts.tryParsePattern = tryParsePattern;
- function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var failedLookupLocations = [];
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false };
- var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state);
- var isExternalLibraryImport = false;
- if (!resolvedFileName) {
- if (moduleHasNonRelativeName(moduleName)) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
- }
- resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false);
- isExternalLibraryImport = resolvedFileName !== undefined;
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state);
- }
- }
- if (resolvedFileName && host.realpath) {
- var originalFileName = resolvedFileName;
- resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName));
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName);
- }
- }
- return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
- }
- ts.nodeModuleNameResolver = nodeModuleNameResolver;
- function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
- }
- var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
- return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
- }
- function directoryProbablyExists(directoryName, host) {
- return !host.directoryExists || host.directoryExists(directoryName);
- }
- ts.directoryProbablyExists = directoryProbablyExists;
- function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
- var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
- if (resolvedByAddingExtension) {
- return resolvedByAddingExtension;
- }
- if (ts.hasJavaScriptFileExtension(candidate)) {
- var extensionless = ts.removeFileExtension(candidate);
- if (state.traceEnabled) {
- var extension = candidate.substring(extensionless.length);
- trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
- }
- return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
- }
- }
- function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
- if (!onlyRecordFailures) {
- var directory = ts.getDirectoryPath(candidate);
- if (directory) {
- onlyRecordFailures = !directoryProbablyExists(directory, state.host);
- }
- }
- return ts.forEach(extensions, function (ext) {
- return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state);
- });
- }
- function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) {
- if (!onlyRecordFailures && state.host.fileExists(fileName)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
- }
- return fileName;
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
- }
- failedLookupLocation.push(fileName);
- return undefined;
- }
- }
- function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) {
- var packageJsonPath = pathToPackageJson(candidate);
- var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
- if (directoryExists && state.host.fileExists(packageJsonPath)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
- }
- var typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
- if (typesFile) {
- var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host);
- var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) ||
- tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state);
- if (result) {
- return result;
- }
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field);
- }
- }
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
- }
- failedLookupLocation.push(packageJsonPath);
- }
- return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
- }
- function pathToPackageJson(directory) {
- return ts.combinePaths(directory, "package.json");
- }
- function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) {
- var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
- var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
- var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
- var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions);
- var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
- if (result) {
- return result;
- }
- result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
- if (result) {
- return result;
- }
- }
- function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) {
- directory = ts.normalizeSlashes(directory);
- while (true) {
- var baseName = ts.getBaseFileName(directory);
- if (baseName !== "node_modules") {
- var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
- if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
- return packageResult;
- }
- else {
- var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
- if (typesResult || packageResult) {
- return typesResult || packageResult;
- }
- }
- }
- var parentPath = ts.getDirectoryPath(directory);
- if (parentPath === directory || checkOneLevel) {
- break;
- }
- directory = parentPath;
- }
- return undefined;
- }
- ts.loadModuleFromNodeModules = loadModuleFromNodeModules;
- function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
- var failedLookupLocations = [];
- var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
- if (resolvedFileName) {
- return createResolvedModule(resolvedFileName, false, failedLookupLocations);
- }
- var referencedSourceFile;
- if (moduleHasNonRelativeName(moduleName)) {
- while (true) {
- var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state);
- if (referencedSourceFile) {
- break;
- }
- var parentPath = ts.getDirectoryPath(containingDirectory);
- if (parentPath === containingDirectory) {
- break;
- }
- containingDirectory = parentPath;
- }
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state);
- }
- return referencedSourceFile
- ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations }
- : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
- }
- ts.classicNameResolver = classicNameResolver;
-})(ts || (ts = {}));
-var ts;
(function (ts) {
var NodeConstructor;
var SourceFileConstructor;
@@ -12157,8 +11122,8 @@ var ts;
function getLocalNameForExternalImport(node, sourceFile) {
var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !ts.isDefaultImport(node)) {
- var name_12 = namespaceDeclaration.name;
- return ts.isGeneratedIdentifier(name_12) ? name_12 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name));
+ var name_11 = namespaceDeclaration.name;
+ return ts.isGeneratedIdentifier(name_11) ? name_11 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name));
}
if (node.kind === 230 && node.importClause) {
return getGeneratedNameForNode(node);
@@ -15857,8 +14822,8 @@ var ts;
return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers);
}
if (decorators || modifiers) {
- var name_13 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected);
- return parsePropertyDeclaration(fullStart, decorators, modifiers, name_13, undefined);
+ var name_12 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected);
+ return parsePropertyDeclaration(fullStart, decorators, modifiers, name_12, undefined);
}
ts.Debug.fail("Should not have attempted to parse class member declaration.");
}
@@ -16882,8 +15847,8 @@ var ts;
if (typeExpression.type.kind === 267) {
var jsDocTypeReference = typeExpression.type;
if (jsDocTypeReference.name.kind === 69) {
- var name_14 = jsDocTypeReference.name;
- if (name_14.text === "Object") {
+ var name_13 = jsDocTypeReference.name;
+ if (name_13.text === "Object") {
typedefTag.jsDocTypeLiteral = scanChildTags();
}
}
@@ -16969,14 +15934,14 @@ var ts;
}
var typeParameters = createNodeArray();
while (true) {
- var name_15 = parseJSDocIdentifierName();
+ var name_14 = parseJSDocIdentifierName();
skipWhitespace();
- if (!name_15) {
+ if (!name_14) {
parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected);
return undefined;
}
- var typeParameter = createNode(141, name_15.pos);
- typeParameter.name = name_15;
+ var typeParameter = createNode(141, name_14.pos);
+ typeParameter.name = name_14;
finishNode(typeParameter);
typeParameters.push(typeParameter);
if (token() === 24) {
@@ -18829,12 +17794,12 @@ var ts;
return;
}
else {
- var parent_7 = node.parent;
- if (!ts.isExternalModule(parent_7)) {
+ var parent_6 = node.parent;
+ if (!ts.isExternalModule(parent_6)) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files));
return;
}
- if (!parent_7.isDeclarationFile) {
+ if (!parent_6.isDeclarationFile) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files));
return;
}
@@ -20370,28 +19335,28 @@ var ts;
var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier);
if (targetSymbol) {
- var name_16 = specifier.propertyName || specifier.name;
- if (name_16.text) {
+ var name_15 = specifier.propertyName || specifier.name;
+ if (name_15.text) {
if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
return moduleSymbol;
}
var symbolFromVariable = void 0;
if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) {
- symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_16.text);
+ symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_15.text);
}
else {
- symbolFromVariable = getPropertyOfVariable(targetSymbol, name_16.text);
+ symbolFromVariable = getPropertyOfVariable(targetSymbol, name_15.text);
}
symbolFromVariable = resolveSymbol(symbolFromVariable);
- var symbolFromModule = getExportOfModule(targetSymbol, name_16.text);
- if (!symbolFromModule && allowSyntheticDefaultImports && name_16.text === "default") {
+ var symbolFromModule = getExportOfModule(targetSymbol, name_15.text);
+ if (!symbolFromModule && allowSyntheticDefaultImports && name_15.text === "default") {
symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol);
}
var symbol = symbolFromModule && symbolFromVariable ?
combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
symbolFromModule || symbolFromVariable;
if (!symbol) {
- error(name_16, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_16));
+ error(name_15, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_15));
}
return symbol;
}
@@ -21112,9 +20077,9 @@ var ts;
var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2));
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
- var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
- if (parent_8) {
- walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), false);
+ var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
+ if (parent_7) {
+ walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false);
}
}
if (accessibleSymbolChain) {
@@ -21236,12 +20201,12 @@ var ts;
var length_1 = outerTypeParameters.length;
while (i < length_1) {
var start = i;
- var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
+ var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
do {
i++;
- } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9);
+ } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8);
if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
- writeSymbolTypeReference(parent_9, typeArguments, start, i, flags);
+ writeSymbolTypeReference(parent_8, typeArguments, start, i, flags);
writePunctuation(writer, 21);
}
}
@@ -21630,12 +20595,12 @@ var ts;
if (ts.isExternalModuleAugmentation(node)) {
return true;
}
- var parent_10 = getDeclarationContainer(node);
+ var parent_9 = getDeclarationContainer(node);
if (!(ts.getCombinedModifierFlags(node) & 1) &&
- !(node.kind !== 229 && parent_10.kind !== 256 && ts.isInAmbientContext(parent_10))) {
- return isGlobalSourceFile(parent_10);
+ !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) {
+ return isGlobalSourceFile(parent_9);
}
- return isDeclarationVisible(parent_10);
+ return isDeclarationVisible(parent_9);
case 145:
case 144:
case 149:
@@ -21822,19 +20787,19 @@ var ts;
}
var type;
if (pattern.kind === 167) {
- var name_17 = declaration.propertyName || declaration.name;
- if (isComputedNonLiteralName(name_17)) {
+ var name_16 = declaration.propertyName || declaration.name;
+ if (isComputedNonLiteralName(name_16)) {
return anyType;
}
if (declaration.initializer) {
getContextualType(declaration.initializer);
}
- var text = getTextOfPropertyName(name_17);
+ var text = getTextOfPropertyName(name_16);
type = getTypeOfPropertyOfType(parentType, text) ||
isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) ||
getIndexTypeOfType(parentType, 0);
if (!type) {
- error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_17));
+ error(name_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_16));
return unknownType;
}
}
@@ -27257,11 +26222,11 @@ var ts;
}
if (ts.isBindingPattern(declaration.parent)) {
var parentDeclaration = declaration.parent.parent;
- var name_18 = declaration.propertyName || declaration.name;
+ var name_17 = declaration.propertyName || declaration.name;
if (ts.isVariableLike(parentDeclaration) &&
parentDeclaration.type &&
- !ts.isBindingPattern(name_18)) {
- var text = getTextOfPropertyName(name_18);
+ !ts.isBindingPattern(name_17)) {
+ var text = getTextOfPropertyName(name_17);
if (text) {
return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text);
}
@@ -28301,15 +27266,15 @@ var ts;
return unknownType;
}
if (node.argumentExpression) {
- var name_19 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType);
- if (name_19 !== undefined) {
- var prop = getPropertyOfType(objectType, name_19);
+ var name_18 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType);
+ if (name_18 !== undefined) {
+ var prop = getPropertyOfType(objectType, name_18);
if (prop) {
getNodeLinks(node).resolvedSymbol = prop;
return getTypeOfSymbol(prop);
}
else if (isConstEnum) {
- error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_19, symbolToString(objectType.symbol));
+ error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_18, symbolToString(objectType.symbol));
return unknownType;
}
}
@@ -28410,19 +27375,19 @@ var ts;
for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
var signature = signatures_2[_i];
var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
- var parent_11 = signature.declaration && signature.declaration.parent;
+ var parent_10 = signature.declaration && signature.declaration.parent;
if (!lastSymbol || symbol === lastSymbol) {
- if (lastParent && parent_11 === lastParent) {
+ if (lastParent && parent_10 === lastParent) {
index++;
}
else {
- lastParent = parent_11;
+ lastParent = parent_10;
index = cutoffIndex;
}
}
else {
index = cutoffIndex = result.length;
- lastParent = parent_11;
+ lastParent = parent_10;
}
lastSymbol = symbol;
if (signature.hasLiteralTypes) {
@@ -29725,14 +28690,14 @@ var ts;
}
function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) {
if (property.kind === 253 || property.kind === 254) {
- var name_20 = property.name;
- if (name_20.kind === 140) {
- checkComputedPropertyName(name_20);
+ var name_19 = property.name;
+ if (name_19.kind === 140) {
+ checkComputedPropertyName(name_19);
}
- if (isComputedNonLiteralName(name_20)) {
+ if (isComputedNonLiteralName(name_19)) {
return undefined;
}
- var text = getTextOfPropertyName(name_20);
+ var text = getTextOfPropertyName(name_19);
var type = isTypeAny(objectLiteralType)
? objectLiteralType
: getTypeOfPropertyOfType(objectLiteralType, text) ||
@@ -29747,7 +28712,7 @@ var ts;
}
}
else {
- error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_20));
+ error(name_19, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_19));
}
}
else {
@@ -30396,9 +29361,9 @@ var ts;
else if (parameterName) {
var hasReportedError = false;
for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
- var name_21 = _a[_i].name;
- if (ts.isBindingPattern(name_21) &&
- checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, parameterName, typePredicate.parameterName)) {
+ var name_20 = _a[_i].name;
+ if (ts.isBindingPattern(name_20) &&
+ checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_20, parameterName, typePredicate.parameterName)) {
hasReportedError = true;
break;
}
@@ -30418,9 +29383,9 @@ var ts;
case 156:
case 147:
case 146:
- var parent_12 = node.parent;
- if (node === parent_12.type) {
- return parent_12;
+ var parent_11 = node.parent;
+ if (node === parent_11.type) {
+ return parent_11;
}
}
}
@@ -30430,15 +29395,15 @@ var ts;
if (ts.isOmittedExpression(element)) {
continue;
}
- var name_22 = element.name;
- if (name_22.kind === 69 &&
- name_22.text === predicateVariableName) {
+ var name_21 = element.name;
+ if (name_21.kind === 69 &&
+ name_21.text === predicateVariableName) {
error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
return true;
}
- else if (name_22.kind === 168 ||
- name_22.kind === 167) {
- if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_22, predicateVariableNode, predicateVariableName)) {
+ else if (name_21.kind === 168 ||
+ name_21.kind === 167) {
+ if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, predicateVariableNode, predicateVariableName)) {
return true;
}
}
@@ -31582,8 +30547,8 @@ var ts;
container.kind === 225 ||
container.kind === 256);
if (!namesShareScope) {
- var name_23 = symbolToString(localDeclarationSymbol);
- error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_23, name_23);
+ var name_22 = symbolToString(localDeclarationSymbol);
+ error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_22, name_22);
}
}
}
@@ -31651,12 +30616,12 @@ var ts;
if (node.propertyName && node.propertyName.kind === 140) {
checkComputedPropertyName(node.propertyName);
}
- var parent_13 = node.parent.parent;
- var parentType = getTypeForBindingElementParent(parent_13);
- var name_24 = node.propertyName || node.name;
- var property = getPropertyOfType(parentType, getTextOfPropertyName(name_24));
- if (parent_13.initializer && property && getParentOfSymbol(property)) {
- checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property);
+ var parent_12 = node.parent.parent;
+ var parentType = getTypeForBindingElementParent(parent_12);
+ var name_23 = node.propertyName || node.name;
+ var property = getPropertyOfType(parentType, getTextOfPropertyName(name_23));
+ if (parent_12.initializer && property && getParentOfSymbol(property)) {
+ checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property);
}
}
if (ts.isBindingPattern(node.name)) {
@@ -32853,9 +31818,9 @@ var ts;
break;
case 169:
case 218:
- var name_25 = node.name;
- if (ts.isBindingPattern(name_25)) {
- for (var _b = 0, _c = name_25.elements; _b < _c.length; _b++) {
+ var name_24 = node.name;
+ if (ts.isBindingPattern(name_24)) {
+ for (var _b = 0, _c = name_24.elements; _b < _c.length; _b++) {
var el = _c[_b];
checkModuleAugmentationElement(el, isGlobalAugmentation);
}
@@ -33081,12 +32046,12 @@ var ts;
error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
}
}
- var exports_1 = getExportsOfModule(moduleSymbol);
- for (var id in exports_1) {
+ var exports = getExportsOfModule(moduleSymbol);
+ for (var id in exports) {
if (id === "__export") {
continue;
}
- var _a = exports_1[id], declarations = _a.declarations, flags = _a.flags;
+ var _a = exports[id], declarations = _a.declarations, flags = _a.flags;
if (flags & (1920 | 64 | 384)) {
continue;
}
@@ -33705,9 +32670,9 @@ var ts;
function getRootSymbols(symbol) {
if (symbol.flags & 268435456) {
var symbols_3 = [];
- var name_26 = symbol.name;
+ var name_25 = symbol.name;
ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) {
- var symbol = getPropertyOfType(t, name_26);
+ var symbol = getPropertyOfType(t, name_25);
if (symbol) {
symbols_3.push(symbol);
}
@@ -34014,9 +32979,9 @@ var ts;
}
var location = reference;
if (startInDeclarationContainer) {
- var parent_14 = reference.parent;
- if (ts.isDeclaration(parent_14) && reference === parent_14.name) {
- location = getDeclarationContainer(parent_14);
+ var parent_13 = reference.parent;
+ if (ts.isDeclaration(parent_13) && reference === parent_13.name) {
+ location = getDeclarationContainer(parent_13);
}
}
return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined);
@@ -34125,9 +33090,9 @@ var ts;
}
var current = symbol;
while (true) {
- var parent_15 = getParentOfSymbol(current);
- if (parent_15) {
- current = parent_15;
+ var parent_14 = getParentOfSymbol(current);
+ if (parent_14) {
+ current = parent_14;
}
else {
break;
@@ -34246,26 +33211,26 @@ var ts;
if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) {
var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, undefined);
if (helpersModule) {
- var exports_2 = helpersModule.exports;
+ var exports = helpersModule.exports;
if (requestedExternalEmitHelpers & 1024 && languageVersion < 2) {
- verifyHelperSymbol(exports_2, "__extends", 107455);
+ verifyHelperSymbol(exports, "__extends", 107455);
}
if (requestedExternalEmitHelpers & 16384 && compilerOptions.jsx !== 1) {
- verifyHelperSymbol(exports_2, "__assign", 107455);
+ verifyHelperSymbol(exports, "__assign", 107455);
}
if (requestedExternalEmitHelpers & 2048) {
- verifyHelperSymbol(exports_2, "__decorate", 107455);
+ verifyHelperSymbol(exports, "__decorate", 107455);
if (compilerOptions.emitDecoratorMetadata) {
- verifyHelperSymbol(exports_2, "__metadata", 107455);
+ verifyHelperSymbol(exports, "__metadata", 107455);
}
}
if (requestedExternalEmitHelpers & 4096) {
- verifyHelperSymbol(exports_2, "__param", 107455);
+ verifyHelperSymbol(exports, "__param", 107455);
}
if (requestedExternalEmitHelpers & 8192) {
- verifyHelperSymbol(exports_2, "__awaiter", 107455);
+ verifyHelperSymbol(exports, "__awaiter", 107455);
if (languageVersion < 2) {
- verifyHelperSymbol(exports_2, "__generator", 107455);
+ verifyHelperSymbol(exports, "__generator", 107455);
}
}
}
@@ -34796,10 +33761,10 @@ var ts;
var GetOrSetAccessor = GetAccessor | SetAccessor;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var prop = _a[_i];
- var name_27 = prop.name;
+ var name_26 = prop.name;
if (prop.kind === 193 ||
- name_27.kind === 140) {
- checkGrammarComputedPropertyName(name_27);
+ name_26.kind === 140) {
+ checkGrammarComputedPropertyName(name_26);
}
if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) {
return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
@@ -34815,8 +33780,8 @@ var ts;
var currentKind = void 0;
if (prop.kind === 253 || prop.kind === 254) {
checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
- if (name_27.kind === 8) {
- checkGrammarNumericLiteral(name_27);
+ if (name_26.kind === 8) {
+ checkGrammarNumericLiteral(name_26);
}
currentKind = Property;
}
@@ -34832,7 +33797,7 @@ var ts;
else {
ts.Debug.fail("Unexpected syntax kind:" + prop.kind);
}
- var effectiveName = ts.getPropertyNameForPropertyNameNode(name_27);
+ var effectiveName = ts.getPropertyNameForPropertyNameNode(name_26);
if (effectiveName === undefined) {
continue;
}
@@ -34842,18 +33807,18 @@ var ts;
else {
var existingKind = seen[effectiveName];
if (currentKind === Property && existingKind === Property) {
- grammarErrorOnNode(name_27, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_27));
+ grammarErrorOnNode(name_26, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_26));
}
else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) {
if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) {
seen[effectiveName] = currentKind | existingKind;
}
else {
- return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
+ return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
}
}
else {
- return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
+ return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
}
}
}
@@ -34866,12 +33831,12 @@ var ts;
continue;
}
var jsxAttr = attr;
- var name_28 = jsxAttr.name;
- if (!seen[name_28.text]) {
- seen[name_28.text] = true;
+ var name_27 = jsxAttr.name;
+ if (!seen[name_27.text]) {
+ seen[name_27.text] = true;
}
else {
- return grammarErrorOnNode(name_28, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
+ return grammarErrorOnNode(name_27, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
}
var initializer = jsxAttr.initializer;
if (initializer && initializer.kind === 248 && !initializer.expression) {
@@ -36232,10 +35197,10 @@ var ts;
emitArrayLiteralAssignment(target, value, location);
}
else {
- var name_29 = ts.getMutableClone(target);
- context.setSourceMapRange(name_29, target);
- context.setCommentRange(name_29, target);
- emitAssignment(name_29, value, location, undefined);
+ var name_28 = ts.getMutableClone(target);
+ context.setSourceMapRange(name_28, target);
+ context.setCommentRange(name_28, target);
+ emitAssignment(name_28, value, location, undefined);
}
}
function emitObjectLiteralAssignment(target, value, location) {
@@ -37152,14 +36117,14 @@ var ts;
function serializeEntityNameAsExpression(node, useFallback) {
switch (node.kind) {
case 69:
- var name_30 = ts.getMutableClone(node);
- name_30.flags &= ~8;
- name_30.original = undefined;
- name_30.parent = currentScope;
+ var name_29 = ts.getMutableClone(node);
+ name_29.flags &= ~8;
+ name_29.original = undefined;
+ name_29.parent = currentScope;
if (useFallback) {
- return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_30), ts.createLiteral("undefined")), name_30);
+ return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_29), ts.createLiteral("undefined")), name_29);
}
- return name_30;
+ return name_29;
case 139:
return serializeQualifiedNameAsExpression(node, useFallback);
}
@@ -37674,7 +36639,7 @@ var ts;
}
function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) {
if (node.name) {
- var name_31 = ts.getMutableClone(node.name);
+ var name_30 = ts.getMutableClone(node.name);
emitFlags |= getNodeEmitFlags(node.name);
if (!allowSourceMaps) {
emitFlags |= 1536;
@@ -37683,9 +36648,9 @@ var ts;
emitFlags |= 49152;
}
if (emitFlags) {
- setNodeEmitFlags(name_31, emitFlags);
+ setNodeEmitFlags(name_30, emitFlags);
}
- return name_31;
+ return name_30;
}
else {
return ts.getGeneratedNameForNode(node);
@@ -37775,14 +36740,14 @@ var ts;
}
function substituteShorthandPropertyAssignment(node) {
if (enabledSubstitutions & 2) {
- var name_32 = node.name;
- var exportedName = trySubstituteNamespaceExportedName(name_32);
+ var name_31 = node.name;
+ var exportedName = trySubstituteNamespaceExportedName(name_31);
if (exportedName) {
if (node.objectAssignmentInitializer) {
var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
- return ts.createPropertyAssignment(name_32, initializer, node);
+ return ts.createPropertyAssignment(name_31, initializer, node);
}
- return ts.createPropertyAssignment(name_32, exportedName, node);
+ return ts.createPropertyAssignment(name_31, exportedName, node);
}
}
return node;
@@ -38053,12 +37018,12 @@ var ts;
return getTagName(node.openingElement);
}
else {
- var name_33 = node.tagName;
- if (ts.isIdentifier(name_33) && ts.isIntrinsicJsxName(name_33.text)) {
- return ts.createLiteral(name_33.text);
+ var name_32 = node.tagName;
+ if (ts.isIdentifier(name_32) && ts.isIntrinsicJsxName(name_32.text)) {
+ return ts.createLiteral(name_32.text);
}
else {
- return ts.createExpressionFromEntityName(name_33);
+ return ts.createExpressionFromEntityName(name_32);
}
}
}
@@ -38828,15 +37793,15 @@ var ts;
}
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
- var name_34 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
+ var name_33 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
if (dotDotDotToken) {
continue;
}
- if (ts.isBindingPattern(name_34)) {
- addDefaultValueAssignmentForBindingPattern(statements, parameter, name_34, initializer);
+ if (ts.isBindingPattern(name_33)) {
+ addDefaultValueAssignmentForBindingPattern(statements, parameter, name_33, initializer);
}
else if (initializer) {
- addDefaultValueAssignmentForInitializer(statements, parameter, name_34, initializer);
+ addDefaultValueAssignmentForInitializer(statements, parameter, name_33, initializer);
}
}
}
@@ -39401,8 +38366,8 @@ var ts;
if (!extraVariableDeclarations) {
extraVariableDeclarations = [];
}
- for (var name_35 in currentState.hoistedLocalVariables) {
- var identifier = currentState.hoistedLocalVariables[name_35];
+ for (var name_34 in currentState.hoistedLocalVariables) {
+ var identifier = currentState.hoistedLocalVariables[name_34];
extraVariableDeclarations.push(ts.createVariableDeclaration(identifier));
}
}
@@ -39818,7 +38783,7 @@ var ts;
}
function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) {
if (node.name && !ts.isGeneratedIdentifier(node.name)) {
- var name_36 = ts.getMutableClone(node.name);
+ var name_35 = ts.getMutableClone(node.name);
emitFlags |= getNodeEmitFlags(node.name);
if (!allowSourceMaps) {
emitFlags |= 1536;
@@ -39827,9 +38792,9 @@ var ts;
emitFlags |= 49152;
}
if (emitFlags) {
- setNodeEmitFlags(name_36, emitFlags);
+ setNodeEmitFlags(name_35, emitFlags);
}
- return name_36;
+ return name_35;
}
return ts.getGeneratedNameForNode(node);
}
@@ -40801,9 +39766,9 @@ var ts;
if (ts.isIdentifier(original) && original.parent) {
var declaration = resolver.getReferencedValueDeclaration(original);
if (declaration) {
- var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration)));
- if (name_37) {
- var clone_8 = ts.getMutableClone(name_37);
+ var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration)));
+ if (name_36) {
+ var clone_8 = ts.getMutableClone(name_36);
setSourceMapRange(clone_8, node);
setCommentRange(clone_8, node);
return clone_8;
@@ -41726,16 +40691,16 @@ var ts;
else {
var names = ts.reduceEachChild(node, collectExportMembers, []);
for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
- var name_38 = names_1[_i];
- addExportMemberAssignments(statements, name_38);
+ var name_37 = names_1[_i];
+ addExportMemberAssignments(statements, name_37);
}
}
}
function collectExportMembers(names, node) {
if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) {
- var name_39 = node.name;
- if (ts.isIdentifier(name_39)) {
- names.push(name_39);
+ var name_38 = node.name;
+ if (ts.isIdentifier(name_38)) {
+ names.push(name_38);
}
}
return ts.reduceEachChild(node, collectExportMembers, names);
@@ -41990,12 +40955,12 @@ var ts;
}
}
else if (ts.isImportSpecifier(declaration)) {
- var name_40 = declaration.propertyName || declaration.name;
- if (name_40.originalKeywordKind === 77 && languageVersion <= 0) {
- return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_40.text), node);
+ var name_39 = declaration.propertyName || declaration.name;
+ if (name_39.originalKeywordKind === 77 && languageVersion <= 0) {
+ return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_39.text), node);
}
else {
- return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_40), node);
+ return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_39), node);
}
}
}
@@ -42377,11 +41342,11 @@ var ts;
}
function visitFunctionDeclaration(node) {
if (ts.hasModifier(node, 1)) {
- var name_41 = node.name || ts.getGeneratedNameForNode(node);
- var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_41, undefined, node.parameters, undefined, node.body, node);
+ var name_40 = node.name || ts.getGeneratedNameForNode(node);
+ var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_40, undefined, node.parameters, undefined, node.body, node);
recordExportedFunctionDeclaration(node);
if (!ts.hasModifier(node, 512)) {
- recordExportName(name_41);
+ recordExportName(name_40);
}
ts.setOriginalNode(newNode, node);
node = newNode;
@@ -42392,13 +41357,13 @@ var ts;
function visitExpressionStatement(node) {
var originalNode = ts.getOriginalNode(node);
if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) {
- var name_42 = getDeclarationName(originalNode);
+ var name_41 = getDeclarationName(originalNode);
if (originalNode.kind === 224) {
- hoistVariableDeclaration(name_42);
+ hoistVariableDeclaration(name_41);
}
return [
node,
- createExportStatement(name_42, name_42)
+ createExportStatement(name_41, name_41)
];
}
return node;
@@ -43237,11 +42202,11 @@ var ts;
return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);
function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) {
var declarationFilePath = _a.declarationFilePath;
- emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false);
+ emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);
}
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
- function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) {
+ function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) {
var newLine = host.getNewLine();
var compilerOptions = host.getCompilerOptions();
var write;
@@ -43277,7 +42242,7 @@ var ts;
ts.forEach(sourceFile.referencedFiles, function (fileReference) {
var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference);
if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) {
- if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) {
+ if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) {
addedGlobalFileReference = true;
}
emittedReferencedFiles.push(referencedFile);
@@ -43462,7 +42427,7 @@ var ts;
}
else {
errorNameNode = declaration.name;
- resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer);
errorNameNode = undefined;
}
}
@@ -43474,7 +42439,7 @@ var ts;
}
else {
errorNameNode = signature.name;
- resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer);
errorNameNode = undefined;
}
}
@@ -43647,9 +42612,9 @@ var ts;
var count = 0;
while (true) {
count++;
- var name_43 = baseName + "_" + count;
- if (!(name_43 in currentIdentifiers)) {
- return name_43;
+ var name_42 = baseName + "_" + count;
+ if (!(name_42 in currentIdentifiers)) {
+ return name_42;
}
}
}
@@ -43667,7 +42632,7 @@ var ts;
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic;
- resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer);
write(";");
writeLine();
write(node.isExportEquals ? "export = " : "export default ");
@@ -44073,7 +43038,7 @@ var ts;
}
else {
writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError;
- resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer);
+ resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer);
}
function getHeritageClauseVisibilityError(symbolAccessibilityResult) {
var diagnosticMessage;
@@ -44641,14 +43606,14 @@ var ts;
return emitSourceFile(node);
}
}
- function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) {
+ function writeReferencePath(referencedFile, addBundledFileReference) {
var declFileName;
var addedBundledEmitReference = false;
if (ts.isDeclarationFile(referencedFile)) {
declFileName = referencedFile.fileName;
}
else {
- ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles);
+ ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile);
}
if (declFileName) {
declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false);
@@ -44665,8 +43630,8 @@ var ts;
}
}
}
- function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) {
- var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles);
+ function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) {
+ var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit);
var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit;
if (!emitSkipped) {
var declarationOutput = emitDeclarationResult.referencesOutput
@@ -45346,7 +44311,7 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) {
+ function emitFiles(resolver, host, targetSourceFile) {
var delimiters = createDelimiterMap();
var brackets = createBracketsMap();
var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};";
@@ -45393,7 +44358,7 @@ var ts;
ts.performance.measure("transformTime", "beforeTransform");
var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode;
ts.performance.mark("beforePrint");
- ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile, emitOnlyDtsFiles);
+ ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile);
transformed.dispose();
ts.performance.measure("printTime", "beforePrint");
return {
@@ -45410,7 +44375,7 @@ var ts;
emitSkipped = true;
}
if (declarationFilePath) {
- emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped;
+ emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped;
}
if (!emitSkipped && emittedFilesList) {
emittedFilesList.push(jsFilePath);
@@ -47290,21 +46255,21 @@ var ts;
}
function makeTempVariableName(flags) {
if (flags && !(tempFlags & flags)) {
- var name_44 = flags === 268435456 ? "_i" : "_n";
- if (isUniqueName(name_44)) {
+ var name_43 = flags === 268435456 ? "_i" : "_n";
+ if (isUniqueName(name_43)) {
tempFlags |= flags;
- return name_44;
+ return name_43;
}
}
while (true) {
var count = tempFlags & 268435455;
tempFlags++;
if (count !== 8 && count !== 13) {
- var name_45 = count < 26
+ var name_44 = count < 26
? "_" + String.fromCharCode(97 + count)
: "_" + (count - 26);
- if (isUniqueName(name_45)) {
- return name_45;
+ if (isUniqueName(name_44)) {
+ return name_44;
}
}
}
@@ -47425,7 +46390,7 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- ts.version = "2.0.5";
+ ts.version = "2.1.0";
var emptyArray = [];
function findConfigFile(searchPath, fileExists, configName) {
if (configName === void 0) { configName = "tsconfig.json"; }
@@ -47480,6 +46445,581 @@ var ts;
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}
ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
+ function trace(host, message) {
+ host.trace(ts.formatMessage.apply(undefined, arguments));
+ }
+ function isTraceEnabled(compilerOptions, host) {
+ return compilerOptions.traceResolution && host.trace !== undefined;
+ }
+ function hasZeroOrOneAsteriskCharacter(str) {
+ var seenAsterisk = false;
+ for (var i = 0; i < str.length; i++) {
+ if (str.charCodeAt(i) === 42) {
+ if (!seenAsterisk) {
+ seenAsterisk = true;
+ }
+ else {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+ ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) {
+ return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
+ }
+ function moduleHasNonRelativeName(moduleName) {
+ return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
+ }
+ function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
+ var jsonContent = readJson(packageJsonPath, state.host);
+ function tryReadFromField(fieldName) {
+ if (ts.hasProperty(jsonContent, fieldName)) {
+ var typesFile = jsonContent[fieldName];
+ if (typeof typesFile === "string") {
+ var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1);
+ }
+ return typesFilePath_1;
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
+ }
+ }
+ }
+ }
+ var typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
+ if (typesFilePath) {
+ return typesFilePath;
+ }
+ if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main);
+ }
+ var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main));
+ return mainFilePath;
+ }
+ return undefined;
+ }
+ function readJson(path, host) {
+ try {
+ var jsonText = host.readFile(path);
+ return jsonText ? JSON.parse(jsonText) : {};
+ }
+ catch (e) {
+ return {};
+ }
+ }
+ var typeReferenceExtensions = [".d.ts"];
+ 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();
+ }
+ return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
+ }
+ ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
+ function getDefaultTypeRoots(currentDirectory, host) {
+ if (!host.directoryExists) {
+ return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
+ }
+ var typeRoots;
+ while (true) {
+ var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes);
+ if (host.directoryExists(atTypes)) {
+ (typeRoots || (typeRoots = [])).push(atTypes);
+ }
+ var parent_15 = ts.getDirectoryPath(currentDirectory);
+ if (parent_15 === currentDirectory) {
+ break;
+ }
+ currentDirectory = parent_15;
+ }
+ return typeRoots;
+ }
+ var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
+ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
+ var traceEnabled = isTraceEnabled(options, host);
+ var moduleResolutionState = {
+ compilerOptions: options,
+ host: host,
+ skipTsx: true,
+ 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 = [];
+ if (typeRoots && typeRoots.length) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
+ }
+ var primarySearchPaths = typeRoots;
+ for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) {
+ var typeRoot = primarySearchPaths_1[_i];
+ var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
+ var candidateDirectory = ts.getDirectoryPath(candidate);
+ var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState);
+ if (resolvedFile_1) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true);
+ }
+ return {
+ resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 },
+ failedLookupLocations: failedLookupLocations
+ };
+ }
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
+ }
+ }
+ var resolvedFile;
+ var initialLocationForSecondaryLookup;
+ if (containingFile) {
+ initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile);
+ }
+ if (initialLocationForSecondaryLookup !== undefined) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
+ }
+ resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState);
+ if (traceEnabled) {
+ if (resolvedFile) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
+ }
+ else {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
+ }
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
+ }
+ }
+ return {
+ resolvedTypeReferenceDirective: resolvedFile
+ ? { primary: false, resolvedFileName: resolvedFile }
+ : undefined,
+ failedLookupLocations: failedLookupLocations
+ };
+ }
+ ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
+ function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
+ }
+ 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]);
+ }
+ }
+ var result;
+ switch (moduleResolution) {
+ case ts.ModuleResolutionKind.NodeJs:
+ result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
+ break;
+ case ts.ModuleResolutionKind.Classic:
+ result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
+ break;
+ }
+ 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;
+ }
+ ts.resolveModuleName = resolveModuleName;
+ function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
+ if (moduleHasNonRelativeName(moduleName)) {
+ return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
+ }
+ else {
+ return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
+ }
+ }
+ function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
+ if (!state.compilerOptions.rootDirs) {
+ return undefined;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
+ }
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ var matchedRootDir;
+ var matchedNormalizedPrefix;
+ for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
+ var rootDir = _a[_i];
+ var normalizedRoot = ts.normalizePath(rootDir);
+ if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
+ normalizedRoot += ts.directorySeparator;
+ }
+ var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
+ (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
+ }
+ if (isLongestMatchingPrefix) {
+ matchedNormalizedPrefix = normalizedRoot;
+ matchedRootDir = rootDir;
+ }
+ }
+ if (matchedNormalizedPrefix) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
+ }
+ var suffix = candidate.substr(matchedNormalizedPrefix.length);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
+ }
+ var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
+ if (resolvedFileName) {
+ return resolvedFileName;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
+ }
+ for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
+ var rootDir = _c[_b];
+ if (rootDir === matchedRootDir) {
+ continue;
+ }
+ var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
+ }
+ var baseDirectory = ts.getDirectoryPath(candidate_1);
+ var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
+ if (resolvedFileName_1) {
+ return resolvedFileName_1;
+ }
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
+ }
+ }
+ return undefined;
+ }
+ function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) {
+ if (!state.compilerOptions.baseUrl) {
+ return undefined;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
+ }
+ var matchedPattern = undefined;
+ if (state.compilerOptions.paths) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
+ }
+ matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
+ }
+ if (matchedPattern) {
+ var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
+ var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
+ }
+ for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) {
+ var subst = _a[_i];
+ var path = matchedStar ? subst.replace("*", matchedStar) : subst;
+ var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
+ }
+ var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ if (resolvedFileName) {
+ return resolvedFileName;
+ }
+ }
+ return undefined;
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
+ }
+ return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ }
+ }
+ 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) {
+ return patternString;
+ }
+ }
+ return findBestPatternMatch(patterns, function (_) { return _; }, candidate);
+ }
+ function patternText(_a) {
+ var prefix = _a.prefix, suffix = _a.suffix;
+ return prefix + "*" + suffix;
+ }
+ function matchedText(pattern, candidate) {
+ ts.Debug.assert(isPatternMatch(pattern, candidate));
+ return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
+ }
+ function findBestPatternMatch(values, getPattern, candidate) {
+ var matchedValue = undefined;
+ 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;
+ }
+ ts.findBestPatternMatch = findBestPatternMatch;
+ function isPatternMatch(_a, candidate) {
+ var prefix = _a.prefix, suffix = _a.suffix;
+ return candidate.length >= prefix.length + suffix.length &&
+ ts.startsWith(candidate, prefix) &&
+ ts.endsWith(candidate, suffix);
+ }
+ function tryParsePattern(pattern) {
+ ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
+ var indexOfStar = pattern.indexOf("*");
+ return indexOfStar === -1 ? undefined : {
+ prefix: pattern.substr(0, indexOfStar),
+ suffix: pattern.substr(indexOfStar + 1)
+ };
+ }
+ ts.tryParsePattern = tryParsePattern;
+ function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var failedLookupLocations = [];
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false };
+ var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state);
+ var isExternalLibraryImport = false;
+ if (!resolvedFileName) {
+ if (moduleHasNonRelativeName(moduleName)) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
+ }
+ resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state);
+ isExternalLibraryImport = resolvedFileName !== undefined;
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state);
+ }
+ }
+ if (resolvedFileName && host.realpath) {
+ var originalFileName = resolvedFileName;
+ resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName));
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName);
+ }
+ }
+ return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
+ }
+ ts.nodeModuleNameResolver = nodeModuleNameResolver;
+ function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
+ }
+ var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
+ return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
+ }
+ function directoryProbablyExists(directoryName, host) {
+ return !host.directoryExists || host.directoryExists(directoryName);
+ }
+ ts.directoryProbablyExists = directoryProbablyExists;
+ function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
+ var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
+ if (resolvedByAddingExtension) {
+ return resolvedByAddingExtension;
+ }
+ if (ts.hasJavaScriptFileExtension(candidate)) {
+ var extensionless = ts.removeFileExtension(candidate);
+ if (state.traceEnabled) {
+ var extension = candidate.substring(extensionless.length);
+ trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
+ }
+ return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
+ }
+ }
+ function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
+ if (!onlyRecordFailures) {
+ var directory = ts.getDirectoryPath(candidate);
+ if (directory) {
+ onlyRecordFailures = !directoryProbablyExists(directory, state.host);
+ }
+ }
+ return ts.forEach(extensions, function (ext) {
+ return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state);
+ });
+ }
+ function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) {
+ if (!onlyRecordFailures && state.host.fileExists(fileName)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
+ }
+ return fileName;
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
+ }
+ failedLookupLocation.push(fileName);
+ return undefined;
+ }
+ }
+ function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) {
+ var packageJsonPath = pathToPackageJson(candidate);
+ var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
+ if (directoryExists && state.host.fileExists(packageJsonPath)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
+ }
+ var typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
+ if (typesFile) {
+ var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host);
+ var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) ||
+ tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state);
+ if (result) {
+ return result;
+ }
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field);
+ }
+ }
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
+ }
+ failedLookupLocation.push(packageJsonPath);
+ }
+ return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
+ }
+ function pathToPackageJson(directory) {
+ return ts.combinePaths(directory, "package.json");
+ }
+ function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) {
+ var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
+ var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
+ var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
+ var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions);
+ var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
+ if (result) {
+ return result;
+ }
+ result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
+ if (result) {
+ return result;
+ }
+ }
+ function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) {
+ directory = ts.normalizeSlashes(directory);
+ while (true) {
+ var baseName = ts.getBaseFileName(directory);
+ if (baseName !== "node_modules") {
+ var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
+ if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
+ return packageResult;
+ }
+ else {
+ var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
+ if (typesResult || packageResult) {
+ return typesResult || packageResult;
+ }
+ }
+ }
+ var parentPath = ts.getDirectoryPath(directory);
+ if (parentPath === directory) {
+ break;
+ }
+ directory = parentPath;
+ }
+ return undefined;
+ }
+ function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
+ var failedLookupLocations = [];
+ var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
+ if (resolvedFileName) {
+ return createResolvedModule(resolvedFileName, false, failedLookupLocations);
+ }
+ var referencedSourceFile;
+ if (moduleHasNonRelativeName(moduleName)) {
+ while (true) {
+ var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state);
+ if (referencedSourceFile) {
+ break;
+ }
+ var parentPath = ts.getDirectoryPath(containingDirectory);
+ if (parentPath === containingDirectory) {
+ break;
+ }
+ containingDirectory = parentPath;
+ }
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state);
+ }
+ return referencedSourceFile
+ ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations }
+ : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
+ }
+ ts.classicNameResolver = classicNameResolver;
function createCompilerHost(options, setParentNodes) {
var existingDirectories = ts.createMap();
function getCanonicalFileName(fileName) {
@@ -47641,14 +47181,41 @@ var ts;
var resolutions = [];
var cache = ts.createMap();
for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
- var name_46 = names_2[_i];
- var result = name_46 in cache
- ? cache[name_46]
- : cache[name_46] = loader(name_46, containingFile);
+ var name_45 = names_2[_i];
+ var result = name_45 in cache
+ ? cache[name_45]
+ : cache[name_45] = loader(name_45, containingFile);
resolutions.push(result);
}
return resolutions;
}
+ function getAutomaticTypeDirectiveNames(options, host) {
+ if (options.types) {
+ return options.types;
+ }
+ 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));
+ var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
+ if (!isNotNeededPackage) {
+ result.push(ts.getBaseFileName(normalized));
+ }
+ }
+ }
+ }
+ }
+ }
+ return result;
+ }
+ ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
function createProgram(rootNames, options, host, oldProgram) {
var program;
var files = [];
@@ -47674,7 +47241,7 @@ var ts;
resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); };
}
else {
- var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; };
+ var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; };
resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); };
}
var resolveTypeReferenceDirectiveNamesWorker;
@@ -47682,14 +47249,14 @@ var ts;
resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); };
}
else {
- var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; };
+ var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; };
resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); };
}
var filesByName = ts.createFileMap();
var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined;
if (!tryReuseStructureFromOldProgram()) {
ts.forEach(rootNames, function (name) { return processRootFile(name, false); });
- var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host);
+ var typeReferences = getAutomaticTypeDirectiveNames(options, host);
if (typeReferences) {
var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts");
var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
@@ -47732,8 +47299,7 @@ var ts;
getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
- getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
- dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker
+ getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -47880,19 +47446,16 @@ var ts;
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true));
}
- function dropDiagnosticsProducingTypeChecker() {
- diagnosticsProducingTypeChecker = undefined;
- }
function getTypeChecker() {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
- function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
- return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); });
+ function emit(sourceFile, writeFileCallback, cancellationToken) {
+ return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
}
- function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
+ function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) {
var declarationDiagnostics = [];
if (options.noEmit) {
return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
@@ -47913,7 +47476,7 @@ var ts;
}
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
ts.performance.mark("beforeEmit");
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -48510,7 +48073,7 @@ var ts;
if (!ts.hasProperty(options.paths, key)) {
continue;
}
- if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
+ if (!hasZeroOrOneAsteriskCharacter(key)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key));
}
if (ts.isArray(options.paths[key])) {
@@ -48521,7 +48084,7 @@ var ts;
var subst = _a[_i];
var typeOfSubst = typeof subst;
if (typeOfSubst === "string") {
- if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
+ if (!hasZeroOrOneAsteriskCharacter(subst)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key));
}
}
@@ -49918,7 +49481,7 @@ var ts;
return ts.ensureScriptKind(fileName, scriptKind);
}
ts.getScriptKind = getScriptKind;
- function sanitizeConfigFile(configFileName, content) {
+ function parseAndReEmitConfigJSONFile(content) {
var options = {
fileName: "config.js",
compilerOptions: {
@@ -49929,17 +49492,14 @@ var ts;
};
var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics;
var trimmedOutput = outputText.trim();
+ var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2));
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), false), config = _b.config, error = _b.error;
- return {
- configJsonObject: config || {},
- diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics
- };
+ return { configJsonObject: configJsonObject, diagnostics: diagnostics };
}
- ts.sanitizeConfigFile = sanitizeConfigFile;
+ ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -51217,13 +50777,13 @@ var ts;
function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) {
var entries = [];
var nameTable = ts.getNameTable(sourceFile);
- for (var name_47 in nameTable) {
- if (nameTable[name_47] === position) {
+ for (var name_46 in nameTable) {
+ if (nameTable[name_46] === position) {
continue;
}
- if (!uniqueNames[name_47]) {
- uniqueNames[name_47] = name_47;
- var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_47), compilerOptions.target, true);
+ if (!uniqueNames[name_46]) {
+ uniqueNames[name_46] = name_46;
+ var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, true);
if (displayName) {
var entry = {
name: displayName,
@@ -52282,8 +51842,8 @@ var ts;
if (element.getStart() <= position && position <= element.getEnd()) {
continue;
}
- var name_48 = element.propertyName || element.name;
- existingImportsOrExports[name_48.text] = true;
+ var name_47 = element.propertyName || element.name;
+ existingImportsOrExports[name_47.text] = true;
}
if (!ts.someProperties(existingImportsOrExports)) {
return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; });
@@ -54404,18 +53964,155 @@ var ts;
})(JsDoc = ts.JsDoc || (ts.JsDoc = {}));
})(ts || (ts = {}));
var ts;
+(function (ts) {
+ var JsTyping;
+ (function (JsTyping) {
+ ;
+ ;
+ var safeList;
+ function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) {
+ var inferredTypings = ts.createMap();
+ if (!typingOptions || !typingOptions.enableAutoDiscovery) {
+ return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
+ }
+ fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, undefined, 1, 2); });
+ if (!safeList) {
+ var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
+ safeList = ts.createMap(result.config);
+ }
+ var filesToWatch = [];
+ var searchDirs = [];
+ var exclude = [];
+ mergeTypings(typingOptions.include);
+ exclude = typingOptions.exclude || [];
+ var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath);
+ if (projectRootPath !== undefined) {
+ 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);
+ for (var name_48 in packageNameToTypingLocation) {
+ if (name_48 in inferredTypings && !inferredTypings[name_48]) {
+ inferredTypings[name_48] = packageNameToTypingLocation[name_48];
+ }
+ }
+ for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) {
+ var excludeTypingName = exclude_1[_a];
+ delete inferredTypings[excludeTypingName];
+ }
+ var newTypingNames = [];
+ var cachedTypingPaths = [];
+ for (var typing in inferredTypings) {
+ if (inferredTypings[typing] !== undefined) {
+ cachedTypingPaths.push(inferredTypings[typing]);
+ }
+ else {
+ newTypingNames.push(typing);
+ }
+ }
+ return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
+ function mergeTypings(typingNames) {
+ if (!typingNames) {
+ return;
+ }
+ for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) {
+ var typing = typingNames_1[_i];
+ if (!(typing in inferredTypings)) {
+ inferredTypings[typing] = undefined;
+ }
+ }
+ }
+ function getTypingNamesFromJson(jsonPath, filesToWatch) {
+ var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); });
+ if (result.config) {
+ var jsonConfig = result.config;
+ filesToWatch.push(jsonPath);
+ if (jsonConfig.dependencies) {
+ mergeTypings(ts.getOwnKeys(jsonConfig.dependencies));
+ }
+ if (jsonConfig.devDependencies) {
+ mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies));
+ }
+ if (jsonConfig.optionalDependencies) {
+ mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies));
+ }
+ if (jsonConfig.peerDependencies) {
+ mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies));
+ }
+ }
+ }
+ function getTypingNamesFromSourceFileNames(fileNames) {
+ var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension);
+ var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); });
+ var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); });
+ if (safeList === undefined) {
+ mergeTypings(cleanedTypingNames);
+ }
+ else {
+ mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; }));
+ }
+ var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, undefined, 2); });
+ if (hasJsxFile) {
+ mergeTypings(["react"]);
+ }
+ }
+ function getTypingNamesFromNodeModuleFolder(nodeModulesPath) {
+ if (!host.directoryExists(nodeModulesPath)) {
+ return;
+ }
+ var typingNames = [];
+ var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2);
+ for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
+ var fileName = fileNames_2[_i];
+ var normalizedFileName = ts.normalizePath(fileName);
+ if (ts.getBaseFileName(normalizedFileName) !== "package.json") {
+ continue;
+ }
+ var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ if (!result.config) {
+ continue;
+ }
+ var packageJson = result.config;
+ if (packageJson._requiredBy &&
+ ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
+ continue;
+ }
+ if (!packageJson.name) {
+ continue;
+ }
+ if (packageJson.typings) {
+ var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName));
+ inferredTypings[packageJson.name] = absolutePath;
+ }
+ else {
+ typingNames.push(packageJson.name);
+ }
+ }
+ mergeTypings(typingNames);
+ }
+ }
+ JsTyping.discoverTypings = discoverTypings;
+ })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
+})(ts || (ts = {}));
+var ts;
(function (ts) {
var NavigateTo;
(function (NavigateTo) {
- function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) {
+ function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) {
var patternMatcher = ts.createPatternMatcher(searchValue);
var rawItems = [];
var baseSensitivity = { sensitivity: "base" };
ts.forEach(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) {
- return;
- }
var nameToDeclarations = sourceFile.getNamedDeclarations();
for (var name_49 in nameToDeclarations) {
var declarations = nameToDeclarations[name_49];
@@ -57992,25 +57689,25 @@ var ts;
};
RulesProvider.prototype.createActiveRules = function (options) {
var rules = this.globalRules.HighPriorityCommonRules.slice(0);
- if (options.insertSpaceAfterCommaDelimiter) {
+ if (options.InsertSpaceAfterCommaDelimiter) {
rules.push(this.globalRules.SpaceAfterComma);
}
else {
rules.push(this.globalRules.NoSpaceAfterComma);
}
- if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) {
+ if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) {
rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword);
}
else {
rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword);
}
- if (options.insertSpaceAfterKeywordsInControlFlowStatements) {
+ if (options.InsertSpaceAfterKeywordsInControlFlowStatements) {
rules.push(this.globalRules.SpaceAfterKeywordInControl);
}
else {
rules.push(this.globalRules.NoSpaceAfterKeywordInControl);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) {
rules.push(this.globalRules.SpaceAfterOpenParen);
rules.push(this.globalRules.SpaceBeforeCloseParen);
rules.push(this.globalRules.NoSpaceBetweenParens);
@@ -58020,7 +57717,7 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeCloseParen);
rules.push(this.globalRules.NoSpaceBetweenParens);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) {
rules.push(this.globalRules.SpaceAfterOpenBracket);
rules.push(this.globalRules.SpaceBeforeCloseBracket);
rules.push(this.globalRules.NoSpaceBetweenBrackets);
@@ -58030,7 +57727,7 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeCloseBracket);
rules.push(this.globalRules.NoSpaceBetweenBrackets);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) {
rules.push(this.globalRules.SpaceAfterOpenBrace);
rules.push(this.globalRules.SpaceBeforeCloseBrace);
rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets);
@@ -58040,7 +57737,7 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeCloseBrace);
rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) {
rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail);
}
@@ -58048,7 +57745,7 @@ var ts;
rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) {
rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression);
rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression);
}
@@ -58056,13 +57753,13 @@ var ts;
rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression);
rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression);
}
- if (options.insertSpaceAfterSemicolonInForStatements) {
+ if (options.InsertSpaceAfterSemicolonInForStatements) {
rules.push(this.globalRules.SpaceAfterSemicolonInFor);
}
else {
rules.push(this.globalRules.NoSpaceAfterSemicolonInFor);
}
- if (options.insertSpaceBeforeAndAfterBinaryOperators) {
+ if (options.InsertSpaceBeforeAndAfterBinaryOperators) {
rules.push(this.globalRules.SpaceBeforeBinaryOperator);
rules.push(this.globalRules.SpaceAfterBinaryOperator);
}
@@ -58070,14 +57767,14 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeBinaryOperator);
rules.push(this.globalRules.NoSpaceAfterBinaryOperator);
}
- if (options.placeOpenBraceOnNewLineForControlBlocks) {
+ if (options.PlaceOpenBraceOnNewLineForControlBlocks) {
rules.push(this.globalRules.NewLineBeforeOpenBraceInControl);
}
- if (options.placeOpenBraceOnNewLineForFunctions) {
+ if (options.PlaceOpenBraceOnNewLineForFunctions) {
rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction);
rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock);
}
- if (options.insertSpaceAfterTypeAssertion) {
+ if (options.InsertSpaceAfterTypeAssertion) {
rules.push(this.globalRules.SpaceAfterTypeAssertion);
}
else {
@@ -58248,7 +57945,7 @@ var ts;
break;
}
if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) {
- return options.indentSize;
+ return options.IndentSize;
}
previousLine = line;
child = n;
@@ -58308,12 +58005,12 @@ var ts;
}
function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) {
var indentation = inheritedIndentation;
- var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0;
+ var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0;
if (effectiveParentStartLine === startLine) {
indentation = startLine === lastIndentedLine
? indentationOnLastIndentedLine
: parentDynamicIndentation.getIndentation();
- delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta);
+ delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta);
}
else if (indentation === -1) {
if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
@@ -58385,13 +58082,13 @@ var ts;
recomputeIndentation: function (lineAdded) {
if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) {
if (lineAdded) {
- indentation += options.indentSize;
+ indentation += options.IndentSize;
}
else {
- indentation -= options.indentSize;
+ indentation -= options.IndentSize;
}
if (formatting.SmartIndenter.shouldIndentChildNode(node)) {
- delta = options.indentSize;
+ delta = options.IndentSize;
}
else {
delta = 0;
@@ -58751,7 +58448,7 @@ var ts;
}
var lineDelta = currentStartLine - previousStartLine;
if (lineDelta !== 1) {
- recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter);
+ recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter);
}
break;
case 2:
@@ -58810,14 +58507,14 @@ var ts;
var internedTabsIndentation;
var internedSpacesIndentation;
function getIndentationString(indentation, options) {
- var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize);
+ var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize);
if (resetInternedStrings) {
- internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize };
+ 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;
+ if (!options.ConvertTabsToSpaces) {
+ var tabs = Math.floor(indentation / options.TabSize);
+ var spaces = indentation - tabs * options.TabSize;
var tabString = void 0;
if (!internedTabsIndentation) {
internedTabsIndentation = [];
@@ -58832,13 +58529,13 @@ var ts;
}
else {
var spacesString = void 0;
- var quotient = Math.floor(indentation / options.indentSize);
- var remainder = indentation % options.indentSize;
+ var quotient = Math.floor(indentation / options.IndentSize);
+ var remainder = indentation % options.IndentSize;
if (!internedSpacesIndentation) {
internedSpacesIndentation = [];
}
if (internedSpacesIndentation[quotient] === undefined) {
- spacesString = repeat(" ", options.indentSize * quotient);
+ spacesString = repeat(" ", options.IndentSize * quotient);
internedSpacesIndentation[quotient] = spacesString;
}
else {
@@ -58867,7 +58564,7 @@ var ts;
if (position > sourceFile.text.length) {
return getBaseIndentation(options);
}
- if (options.indentStyle === ts.IndentStyle.None) {
+ if (options.IndentStyle === ts.IndentStyle.None) {
return 0;
}
var precedingToken = ts.findPrecedingToken(position, sourceFile);
@@ -58879,7 +58576,7 @@ var ts;
return 0;
}
var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
- if (options.indentStyle === ts.IndentStyle.Block) {
+ if (options.IndentStyle === ts.IndentStyle.Block) {
var current_1 = position;
while (current_1 > 0) {
var char = sourceFile.text.charCodeAt(current_1);
@@ -58908,7 +58605,7 @@ var ts;
indentationDelta = 0;
}
else {
- indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0;
+ indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0;
}
break;
}
@@ -58918,7 +58615,7 @@ var ts;
}
actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options);
if (actualIndentation !== -1) {
- return actualIndentation + options.indentSize;
+ return actualIndentation + options.IndentSize;
}
previous = current;
current = current.parent;
@@ -58929,15 +58626,15 @@ var ts;
return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options);
}
SmartIndenter.getIndentation = getIndentation;
+ function getBaseIndentation(options) {
+ return options.BaseIndentSize || 0;
+ }
+ SmartIndenter.getBaseIndentation = getBaseIndentation;
function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) {
var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options);
}
SmartIndenter.getIndentationForNode = getIndentationForNode;
- function getBaseIndentation(options) {
- return options.baseIndentSize || 0;
- }
- SmartIndenter.getBaseIndentation = getBaseIndentation;
function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) {
var parent = current.parent;
var parentStart;
@@ -58967,7 +58664,7 @@ var ts;
}
}
if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) {
- indentationDelta += options.indentSize;
+ indentationDelta += options.IndentSize;
}
current = parent;
currentStart = parentStart;
@@ -59145,7 +58842,7 @@ var ts;
break;
}
if (ch === 9) {
- column += options.tabSize + (column % options.tabSize);
+ column += options.TabSize + (column % options.TabSize);
}
else {
column++;
@@ -59709,30 +59406,6 @@ var ts;
getSignatureConstructor: function () { return SignatureObject; }
};
}
- 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;
- }
- ts.toEditorSettings = toEditorSettings;
- function isCamelCase(s) {
- return !s.length || s.charAt(0) === s.charAt(0).toLowerCase();
- }
function displayPartsToString(displayParts) {
if (displayParts) {
return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join("");
@@ -60205,12 +59878,12 @@ var ts;
synchronizeHostData();
return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments);
}
- function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) {
+ function getNavigateToItems(searchValue, maxResultCount, fileName) {
synchronizeHostData();
var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles();
- return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles);
+ return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount);
}
- function getEmitOutput(fileName, emitOnlyDtsFiles) {
+ function getEmitOutput(fileName) {
synchronizeHostData();
var sourceFile = getValidSourceFile(fileName);
var outputFiles = [];
@@ -60221,7 +59894,7 @@ var ts;
text: data
});
}
- var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles);
+ var emitOutput = program.emit(sourceFile, writeFile, cancellationToken);
return {
outputFiles: outputFiles,
emitSkipped: emitOutput.emitSkipped
@@ -60347,35 +60020,31 @@ var ts;
}
function getIndentationAtPosition(fileName, position, editorOptions) {
var start = ts.timestamp();
- var settings = toEditorSettings(editorOptions);
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start));
start = ts.timestamp();
- var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings);
+ var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions);
log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start));
return result;
}
function getFormattingEditsForRange(fileName, start, end, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
- return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options);
}
function getFormattingEditsForDocument(fileName, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
- return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options);
}
function getFormattingEditsAfterKeystroke(fileName, position, key, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
if (key === "}") {
- return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options);
}
else if (key === ";") {
- return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options);
}
else if (key === "\n") {
- return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options);
}
return [];
}
@@ -60564,2279 +60233,43 @@ var ts;
(function (ts) {
var server;
(function (server) {
- var ScriptInfo = (function () {
- function ScriptInfo(host, fileName, content, scriptKind, isOpen, hasMixedContent) {
- if (isOpen === void 0) { isOpen = false; }
- if (hasMixedContent === void 0) { hasMixedContent = false; }
- this.host = host;
- this.fileName = fileName;
- this.scriptKind = scriptKind;
- this.isOpen = isOpen;
- this.hasMixedContent = hasMixedContent;
- this.containingProjects = [];
- this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
- this.svc = server.ScriptVersionCache.fromString(host, content);
- this.scriptKind = scriptKind
- ? scriptKind
- : ts.getScriptKindFromFileName(fileName);
- }
- ScriptInfo.prototype.getFormatCodeSettings = function () {
- return this.formatCodeSettings;
- };
- ScriptInfo.prototype.attachToProject = function (project) {
- var isNew = !this.isAttached(project);
- if (isNew) {
- this.containingProjects.push(project);
- }
- return isNew;
- };
- ScriptInfo.prototype.isAttached = function (project) {
- switch (this.containingProjects.length) {
- case 0: return false;
- case 1: return this.containingProjects[0] === project;
- case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project;
- default: return ts.contains(this.containingProjects, project);
- }
- };
- ScriptInfo.prototype.detachFromProject = function (project) {
- switch (this.containingProjects.length) {
- case 0:
- return;
- case 1:
- if (this.containingProjects[0] === project) {
- this.containingProjects.pop();
- }
- break;
- case 2:
- if (this.containingProjects[0] === project) {
- this.containingProjects[0] = this.containingProjects.pop();
- }
- else if (this.containingProjects[1] === project) {
- this.containingProjects.pop();
- }
- break;
- default:
- server.removeItemFromSet(this.containingProjects, project);
- break;
- }
- };
- ScriptInfo.prototype.detachAllProjects = function () {
- for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) {
- var p = _a[_i];
- p.removeFile(this, false);
- }
- this.containingProjects.length = 0;
- };
- ScriptInfo.prototype.getDefaultProject = function () {
- if (this.containingProjects.length === 0) {
- return server.Errors.ThrowNoProject();
- }
- ts.Debug.assert(this.containingProjects.length !== 0);
- return this.containingProjects[0];
- };
- ScriptInfo.prototype.setFormatOptions = function (formatSettings) {
- if (formatSettings) {
- if (!this.formatCodeSettings) {
- this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host);
- }
- server.mergeMaps(this.formatCodeSettings, formatSettings);
- }
- };
- ScriptInfo.prototype.setWatcher = function (watcher) {
- this.stopWatcher();
- this.fileWatcher = watcher;
- };
- ScriptInfo.prototype.stopWatcher = function () {
- if (this.fileWatcher) {
- this.fileWatcher.close();
- this.fileWatcher = undefined;
- }
- };
- ScriptInfo.prototype.getLatestVersion = function () {
- return this.svc.latestVersion().toString();
- };
- ScriptInfo.prototype.reload = function (script) {
- this.svc.reload(script);
- this.markContainingProjectsAsDirty();
- };
- ScriptInfo.prototype.saveTo = function (fileName) {
- var snap = this.snap();
- this.host.writeFile(fileName, snap.getText(0, snap.getLength()));
- };
- ScriptInfo.prototype.reloadFromFile = function () {
- if (this.hasMixedContent) {
- this.reload("");
- }
- else {
- this.svc.reloadFromFile(this.fileName);
- this.markContainingProjectsAsDirty();
- }
- };
- ScriptInfo.prototype.snap = function () {
- return this.svc.getSnapshot();
- };
- ScriptInfo.prototype.getLineInfo = function (line) {
- var snap = this.snap();
- return snap.index.lineNumberToInfo(line);
- };
- ScriptInfo.prototype.editContent = function (start, end, newText) {
- this.svc.edit(start, end - start, newText);
- this.markContainingProjectsAsDirty();
- };
- ScriptInfo.prototype.markContainingProjectsAsDirty = function () {
- for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) {
- var p = _a[_i];
- p.markAsDirty();
- }
- };
- ScriptInfo.prototype.lineToTextSpan = function (line) {
- var index = this.snap().index;
- var lineInfo = index.lineNumberToInfo(line + 1);
- var len;
- if (lineInfo.leaf) {
- len = lineInfo.leaf.text.length;
- }
- else {
- var nextLineInfo = index.lineNumberToInfo(line + 2);
- len = nextLineInfo.offset - lineInfo.offset;
- }
- return ts.createTextSpan(lineInfo.offset, len);
- };
- ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) {
- var index = this.snap().index;
- var lineInfo = index.lineNumberToInfo(line);
- return (lineInfo.offset + offset - 1);
- };
- ScriptInfo.prototype.positionToLineOffset = function (position) {
- var index = this.snap().index;
- var lineOffset = index.charOffsetToLineNumberAndPos(position);
- return { line: lineOffset.line, offset: lineOffset.offset + 1 };
- };
- return ScriptInfo;
- }());
- server.ScriptInfo = ScriptInfo;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- var LSHost = (function () {
- function LSHost(host, project, cancellationToken) {
- var _this = this;
- this.host = host;
- this.project = project;
- this.cancellationToken = cancellationToken;
- this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames);
- this.resolvedModuleNames = ts.createFileMap();
- this.resolvedTypeReferenceDirectives = ts.createFileMap();
- if (host.trace) {
- this.trace = function (s) { return host.trace(s); };
- }
- this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) {
- var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host);
- if (primaryResult.resolvedModule) {
- if (ts.fileExtensionIsAny(primaryResult.resolvedModule.resolvedFileName, ts.supportedTypeScriptExtensions)) {
- return primaryResult;
- }
- }
- var secondaryLookupFailedLookupLocations = [];
- var globalCache = _this.project.projectService.typingsInstaller.globalTypingsCacheLocation;
- if (_this.project.getTypingOptions().enableAutoDiscovery && globalCache) {
- var traceEnabled = ts.isTraceEnabled(compilerOptions, host);
- if (traceEnabled) {
- ts.trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, _this.project.getProjectName(), moduleName, globalCache);
- }
- var state = { compilerOptions: compilerOptions, host: host, skipTsx: false, traceEnabled: traceEnabled };
- var resolvedName = ts.loadModuleFromNodeModules(moduleName, globalCache, secondaryLookupFailedLookupLocations, state, true);
- if (resolvedName) {
- return ts.createResolvedModule(resolvedName, true, primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations));
- }
- }
- if (!primaryResult.resolvedModule && secondaryLookupFailedLookupLocations.length) {
- primaryResult.failedLookupLocations = primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations);
- }
- return primaryResult;
- };
- }
- LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) {
- var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName);
- var currentResolutionsInFile = cache.get(path);
- var newResolutions = ts.createMap();
- var resolvedModules = [];
- var compilerOptions = this.getCompilationSettings();
- for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
- var name_52 = names_3[_i];
- var resolution = newResolutions[name_52];
- if (!resolution) {
- var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_52];
- if (moduleResolutionIsValid(existingResolution)) {
- resolution = existingResolution;
- }
- else {
- newResolutions[name_52] = resolution = loader(name_52, containingFile, compilerOptions, this);
- }
- }
- ts.Debug.assert(resolution !== undefined);
- resolvedModules.push(getResult(resolution));
- }
- cache.set(path, newResolutions);
- return resolvedModules;
- function moduleResolutionIsValid(resolution) {
- if (!resolution) {
- return false;
- }
- if (getResult(resolution)) {
- return true;
- }
- return resolution.failedLookupLocations.length === 0;
- }
- };
- LSHost.prototype.getProjectVersion = function () {
- return this.project.getProjectVersion();
- };
- LSHost.prototype.getCompilationSettings = function () {
- return this.compilationSettings;
- };
- LSHost.prototype.useCaseSensitiveFileNames = function () {
- return this.host.useCaseSensitiveFileNames;
- };
- LSHost.prototype.getCancellationToken = function () {
- return this.cancellationToken;
- };
- LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
- return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; });
- };
- LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) {
- return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; });
- };
- LSHost.prototype.getDefaultLibFileName = function () {
- var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath()));
- return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings));
- };
- LSHost.prototype.getScriptSnapshot = function (filename) {
- var scriptInfo = this.project.getScriptInfoLSHost(filename);
- if (scriptInfo) {
- return scriptInfo.snap();
- }
- };
- LSHost.prototype.getScriptFileNames = function () {
- return this.project.getRootFilesLSHost();
- };
- LSHost.prototype.getTypeRootsVersion = function () {
- return this.project.typesVersion;
- };
- LSHost.prototype.getScriptKind = function (fileName) {
- var info = this.project.getScriptInfoLSHost(fileName);
- return info && info.scriptKind;
- };
- LSHost.prototype.getScriptVersion = function (filename) {
- var info = this.project.getScriptInfoLSHost(filename);
- return info && info.getLatestVersion();
- };
- LSHost.prototype.getCurrentDirectory = function () {
- return this.host.getCurrentDirectory();
- };
- LSHost.prototype.resolvePath = function (path) {
- return this.host.resolvePath(path);
- };
- LSHost.prototype.fileExists = function (path) {
- return this.host.fileExists(path);
- };
- LSHost.prototype.directoryExists = function (path) {
- return this.host.directoryExists(path);
- };
- LSHost.prototype.readFile = function (fileName) {
- return this.host.readFile(fileName);
- };
- LSHost.prototype.getDirectories = function (path) {
- return this.host.getDirectories(path);
- };
- LSHost.prototype.notifyFileRemoved = function (info) {
- this.resolvedModuleNames.remove(info.path);
- this.resolvedTypeReferenceDirectives.remove(info.path);
- };
- LSHost.prototype.setCompilationSettings = function (opt) {
- this.compilationSettings = opt;
- this.resolvedModuleNames.clear();
- this.resolvedTypeReferenceDirectives.clear();
- };
- return LSHost;
- }());
- server.LSHost = LSHost;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- server.nullTypingsInstaller = {
- enqueueInstallTypingsRequest: function () { },
- attach: function (projectService) { },
- onProjectClosed: function (p) { },
- globalTypingsCacheLocation: undefined
- };
- var TypingsCacheEntry = (function () {
- function TypingsCacheEntry() {
- }
- return TypingsCacheEntry;
- }());
- function setIsEqualTo(arr1, arr2) {
- if (arr1 === arr2) {
- return true;
- }
- if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) {
- return true;
- }
- var set = ts.createMap();
- var unique = 0;
- for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) {
- var v = arr1_1[_i];
- if (set[v] !== true) {
- set[v] = true;
- unique++;
- }
- }
- for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) {
- var v = arr2_1[_a];
- if (!ts.hasProperty(set, v)) {
- return false;
- }
- if (set[v] === true) {
- set[v] = false;
- unique--;
- }
- }
- return unique === 0;
- }
- function typingOptionsChanged(opt1, opt2) {
- return opt1.enableAutoDiscovery !== opt2.enableAutoDiscovery ||
- !setIsEqualTo(opt1.include, opt2.include) ||
- !setIsEqualTo(opt1.exclude, opt2.exclude);
- }
- function compilerOptionsChanged(opt1, opt2) {
- return opt1.allowJs != opt2.allowJs;
- }
- function toTypingsArray(arr) {
- arr.sort();
- return arr;
- }
- var TypingsCache = (function () {
- function TypingsCache(installer) {
- this.installer = installer;
- this.perProjectCache = ts.createMap();
- }
- TypingsCache.prototype.getTypingsForProject = function (project, forceRefresh) {
- var typingOptions = project.getTypingOptions();
- if (!typingOptions || !typingOptions.enableAutoDiscovery) {
- return server.emptyArray;
- }
- var entry = this.perProjectCache[project.getProjectName()];
- var result = entry ? entry.typings : server.emptyArray;
- if (forceRefresh || !entry || typingOptionsChanged(typingOptions, entry.typingOptions) || compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions)) {
- this.perProjectCache[project.getProjectName()] = {
- compilerOptions: project.getCompilerOptions(),
- typingOptions: typingOptions,
- typings: result,
- poisoned: true
- };
- this.installer.enqueueInstallTypingsRequest(project, typingOptions);
- }
- return result;
- };
- TypingsCache.prototype.invalidateCachedTypingsForProject = function (project) {
- var typingOptions = project.getTypingOptions();
- if (!typingOptions.enableAutoDiscovery) {
- return;
- }
- this.installer.enqueueInstallTypingsRequest(project, typingOptions);
- };
- TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typingOptions, newTypings) {
- this.perProjectCache[projectName] = {
- compilerOptions: compilerOptions,
- typingOptions: typingOptions,
- typings: toTypingsArray(newTypings),
- poisoned: false
- };
- };
- TypingsCache.prototype.onProjectClosed = function (project) {
- delete this.perProjectCache[project.getProjectName()];
- this.installer.onProjectClosed(project);
- };
- return TypingsCache;
- }());
- server.TypingsCache = TypingsCache;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- var crypto = require("crypto");
- function shouldEmitFile(scriptInfo) {
- return !scriptInfo.hasMixedContent;
- }
- server.shouldEmitFile = shouldEmitFile;
- var BuilderFileInfo = (function () {
- function BuilderFileInfo(scriptInfo, project) {
- this.scriptInfo = scriptInfo;
- this.project = project;
- }
- BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () {
- var sourceFile = this.getSourceFile();
- return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile);
- };
- BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) {
- for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
- var statement = _a[_i];
- if (statement.kind !== 225 || statement.name.kind !== 9) {
- return false;
- }
- }
- return true;
- };
- BuilderFileInfo.prototype.computeHash = function (text) {
- return crypto.createHash("md5")
- .update(text)
- .digest("base64");
- };
- BuilderFileInfo.prototype.getSourceFile = function () {
- return this.project.getSourceFile(this.scriptInfo.path);
- };
- BuilderFileInfo.prototype.updateShapeSignature = function () {
- var sourceFile = this.getSourceFile();
- if (!sourceFile) {
- return true;
- }
- var lastSignature = this.lastCheckedShapeSignature;
- if (sourceFile.isDeclarationFile) {
- this.lastCheckedShapeSignature = this.computeHash(sourceFile.text);
- }
- else {
- var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true);
- if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) {
- this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text);
- }
- }
- return !lastSignature || this.lastCheckedShapeSignature !== lastSignature;
- };
- return BuilderFileInfo;
- }());
- server.BuilderFileInfo = BuilderFileInfo;
- var AbstractBuilder = (function () {
- function AbstractBuilder(project, ctor) {
- this.project = project;
- this.ctor = ctor;
- this.fileInfos = ts.createFileMap();
- }
- AbstractBuilder.prototype.getFileInfo = function (path) {
- return this.fileInfos.get(path);
- };
- AbstractBuilder.prototype.getOrCreateFileInfo = function (path) {
- var fileInfo = this.getFileInfo(path);
- if (!fileInfo) {
- var scriptInfo = this.project.getScriptInfo(path);
- fileInfo = new this.ctor(scriptInfo, this.project);
- this.setFileInfo(path, fileInfo);
- }
- return fileInfo;
- };
- AbstractBuilder.prototype.getFileInfoPaths = function () {
- return this.fileInfos.getKeys();
- };
- AbstractBuilder.prototype.setFileInfo = function (path, info) {
- this.fileInfos.set(path, info);
- };
- AbstractBuilder.prototype.removeFileInfo = function (path) {
- this.fileInfos.remove(path);
- };
- AbstractBuilder.prototype.forEachFileInfo = function (action) {
- this.fileInfos.forEachValue(function (path, value) { return action(value); });
- };
- AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) {
- var fileInfo = this.getFileInfo(scriptInfo.path);
- if (!fileInfo) {
- return false;
- }
- var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles;
- if (!emitSkipped) {
- var projectRootPath = this.project.getProjectRootPath();
- for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) {
- var outputFile = outputFiles_1[_i];
- var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName));
- writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark);
- }
- }
- return !emitSkipped;
- };
- return AbstractBuilder;
- }());
- var NonModuleBuilder = (function (_super) {
- __extends(NonModuleBuilder, _super);
- function NonModuleBuilder(project) {
- _super.call(this, project, BuilderFileInfo);
- this.project = project;
- }
- NonModuleBuilder.prototype.onProjectUpdateGraph = function () {
- };
- NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) {
- var info = this.getOrCreateFileInfo(scriptInfo.path);
- var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName];
- if (info.updateShapeSignature()) {
- var options = this.project.getCompilerOptions();
- if (options && (options.out || options.outFile)) {
- return singleFileResult;
- }
- return this.project.getAllEmittableFiles();
- }
- return singleFileResult;
- };
- return NonModuleBuilder;
- }(AbstractBuilder));
- var ModuleBuilderFileInfo = (function (_super) {
- __extends(ModuleBuilderFileInfo, _super);
- function ModuleBuilderFileInfo() {
- _super.apply(this, arguments);
- this.references = [];
- this.referencedBy = [];
- }
- ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) {
- var l = lf.scriptInfo.fileName;
- var r = rf.scriptInfo.fileName;
- return (l < r ? -1 : (l > r ? 1 : 0));
- };
- ;
- ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) {
- if (array.length === 0) {
- array.push(fileInfo);
- return;
- }
- var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos);
- if (insertIndex < 0) {
- array.splice(~insertIndex, 0, fileInfo);
- }
- };
- ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) {
- if (!array || array.length === 0) {
- return;
- }
- if (array[0] === fileInfo) {
- array.splice(0, 1);
- return;
- }
- var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos);
- if (removeIndex >= 0) {
- array.splice(removeIndex, 1);
- }
- };
- ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) {
- ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo);
- };
- ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) {
- ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo);
- };
- ModuleBuilderFileInfo.prototype.removeFileReferences = function () {
- for (var _i = 0, _a = this.references; _i < _a.length; _i++) {
- var reference = _a[_i];
- reference.removeReferencedBy(this);
- }
- this.references = [];
- };
- return ModuleBuilderFileInfo;
- }(BuilderFileInfo));
- var ModuleBuilder = (function (_super) {
- __extends(ModuleBuilder, _super);
- function ModuleBuilder(project) {
- _super.call(this, project, ModuleBuilderFileInfo);
- this.project = project;
- }
- ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) {
- var _this = this;
- if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) {
- return [];
- }
- var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path);
- if (referencedFilePaths.length > 0) {
- return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos);
- }
- return [];
- };
- ModuleBuilder.prototype.onProjectUpdateGraph = function () {
- this.ensureProjectDependencyGraphUpToDate();
- };
- ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () {
- var _this = this;
- if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) {
- var currentScriptInfos = this.project.getScriptInfos();
- for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) {
- var scriptInfo = currentScriptInfos_1[_i];
- var fileInfo = this.getOrCreateFileInfo(scriptInfo.path);
- this.updateFileReferences(fileInfo);
- }
- this.forEachFileInfo(function (fileInfo) {
- if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) {
- fileInfo.removeFileReferences();
- _this.removeFileInfo(fileInfo.scriptInfo.path);
- }
- });
- this.projectVersionForDependencyGraph = this.project.getProjectVersion();
- }
- };
- ModuleBuilder.prototype.updateFileReferences = function (fileInfo) {
- if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) {
- return;
- }
- var newReferences = this.getReferencedFileInfos(fileInfo);
- var oldReferences = fileInfo.references;
- var oldIndex = 0;
- var newIndex = 0;
- while (oldIndex < oldReferences.length && newIndex < newReferences.length) {
- var oldReference = oldReferences[oldIndex];
- var newReference = newReferences[newIndex];
- var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference);
- if (compare < 0) {
- oldReference.removeReferencedBy(fileInfo);
- oldIndex++;
- }
- else if (compare > 0) {
- newReference.addReferencedBy(fileInfo);
- newIndex++;
- }
- else {
- oldIndex++;
- newIndex++;
- }
- }
- for (var i = oldIndex; i < oldReferences.length; i++) {
- oldReferences[i].removeReferencedBy(fileInfo);
- }
- for (var i = newIndex; i < newReferences.length; i++) {
- newReferences[i].addReferencedBy(fileInfo);
- }
- fileInfo.references = newReferences;
- fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion();
- };
- ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) {
- this.ensureProjectDependencyGraphUpToDate();
- var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName];
- var fileInfo = this.getFileInfo(scriptInfo.path);
- if (!fileInfo || !fileInfo.updateShapeSignature()) {
- return singleFileResult;
- }
- if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) {
- return this.project.getAllEmittableFiles();
- }
- var options = this.project.getCompilerOptions();
- if (options && (options.isolatedModules || options.out || options.outFile)) {
- return singleFileResult;
- }
- var queue = fileInfo.referencedBy.slice(0);
- var fileNameSet = ts.createMap();
- fileNameSet[scriptInfo.fileName] = scriptInfo;
- while (queue.length > 0) {
- var processingFileInfo = queue.pop();
- if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) {
- for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) {
- var potentialFileInfo = _a[_i];
- if (!fileNameSet[potentialFileInfo.scriptInfo.fileName]) {
- queue.push(potentialFileInfo);
- }
- }
- }
- fileNameSet[processingFileInfo.scriptInfo.fileName] = processingFileInfo.scriptInfo;
- }
- var result = [];
- for (var fileName in fileNameSet) {
- if (shouldEmitFile(fileNameSet[fileName])) {
- result.push(fileName);
- }
- }
- return result;
- };
- return ModuleBuilder;
- }(AbstractBuilder));
- function createBuilder(project) {
- var moduleKind = project.getCompilerOptions().module;
- switch (moduleKind) {
- case ts.ModuleKind.None:
- return new NonModuleBuilder(project);
- default:
- return new ModuleBuilder(project);
- }
- }
- server.createBuilder = createBuilder;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- (function (ProjectKind) {
- ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred";
- ProjectKind[ProjectKind["Configured"] = 1] = "Configured";
- ProjectKind[ProjectKind["External"] = 2] = "External";
- })(server.ProjectKind || (server.ProjectKind = {}));
- var ProjectKind = server.ProjectKind;
- function remove(items, item) {
- var index = items.indexOf(item);
- if (index >= 0) {
- items.splice(index, 1);
- }
- }
- function isJsOrDtsFile(info) {
- return info.scriptKind === 1 || info.scriptKind == 2 || ts.fileExtensionIs(info.fileName, ".d.ts");
- }
- function allRootFilesAreJsOrDts(project) {
- return project.getRootScriptInfos().every(isJsOrDtsFile);
- }
- server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts;
- function allFilesAreJsOrDts(project) {
- return project.getScriptInfos().every(isJsOrDtsFile);
- }
- server.allFilesAreJsOrDts = allFilesAreJsOrDts;
- var Project = (function () {
- function Project(projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) {
- this.projectKind = projectKind;
- this.projectService = projectService;
- this.documentRegistry = documentRegistry;
- this.languageServiceEnabled = languageServiceEnabled;
- this.compilerOptions = compilerOptions;
- this.compileOnSaveEnabled = compileOnSaveEnabled;
- this.rootFiles = [];
- this.rootFilesMap = ts.createFileMap();
- this.lastReportedVersion = 0;
- this.projectStructureVersion = 0;
- this.projectStateVersion = 0;
- this.typesVersion = 0;
- if (!this.compilerOptions) {
- this.compilerOptions = ts.getDefaultCompilerOptions();
- this.compilerOptions.allowNonTsExtensions = true;
- this.compilerOptions.allowJs = true;
- }
- else if (hasExplicitListOfFiles) {
- this.compilerOptions.allowNonTsExtensions = true;
- }
- if (languageServiceEnabled) {
- this.enableLanguageService();
- }
- else {
- this.disableLanguageService();
- }
- this.builder = server.createBuilder(this);
- this.markAsDirty();
- }
- Project.prototype.isJsOnlyProject = function () {
- this.updateGraph();
- return allFilesAreJsOrDts(this);
- };
- Project.prototype.getProjectErrors = function () {
- return this.projectErrors;
- };
- Project.prototype.getLanguageService = function (ensureSynchronized) {
- if (ensureSynchronized === void 0) { ensureSynchronized = true; }
- if (ensureSynchronized) {
- this.updateGraph();
- }
- return this.languageService;
- };
- Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) {
- if (!this.languageServiceEnabled) {
- return [];
- }
- this.updateGraph();
- return this.builder.getFilesAffectedBy(scriptInfo);
- };
- Project.prototype.getProjectVersion = function () {
- return this.projectStateVersion.toString();
- };
- Project.prototype.enableLanguageService = function () {
- var lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken);
- lsHost.setCompilationSettings(this.compilerOptions);
- this.languageService = ts.createLanguageService(lsHost, this.documentRegistry);
- this.lsHost = lsHost;
- this.languageServiceEnabled = true;
- };
- Project.prototype.disableLanguageService = function () {
- this.languageService = server.nullLanguageService;
- this.lsHost = server.nullLanguageServiceHost;
- this.languageServiceEnabled = false;
- };
- Project.prototype.getSourceFile = function (path) {
- if (!this.program) {
- return undefined;
- }
- return this.program.getSourceFileByPath(path);
- };
- Project.prototype.updateTypes = function () {
- this.typesVersion++;
- this.markAsDirty();
- this.updateGraph();
- };
- Project.prototype.close = function () {
- if (this.program) {
- for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) {
- var f = _a[_i];
- var info = this.projectService.getScriptInfo(f.fileName);
- info.detachFromProject(this);
- }
- }
- else {
- for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) {
- var root = _c[_b];
- root.detachFromProject(this);
- }
- }
- this.rootFiles = undefined;
- this.rootFilesMap = undefined;
- this.program = undefined;
- this.languageService.dispose();
- };
- Project.prototype.getCompilerOptions = function () {
- return this.compilerOptions;
- };
- Project.prototype.hasRoots = function () {
- return this.rootFiles && this.rootFiles.length > 0;
- };
- Project.prototype.getRootFiles = function () {
- return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; });
- };
- Project.prototype.getRootFilesLSHost = function () {
- var result = [];
- if (this.rootFiles) {
- for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) {
- var f = _a[_i];
- result.push(f.fileName);
- }
- if (this.typingFiles) {
- for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) {
- var f = _c[_b];
- result.push(f);
- }
- }
- }
- return result;
- };
- Project.prototype.getRootScriptInfos = function () {
- return this.rootFiles;
- };
- Project.prototype.getScriptInfos = function () {
- var _this = this;
- return ts.map(this.program.getSourceFiles(), function (sourceFile) { return _this.getScriptInfoLSHost(sourceFile.path); });
- };
- Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) {
- if (!this.languageServiceEnabled) {
- return undefined;
- }
- return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles);
- };
- Project.prototype.getFileNames = function () {
- if (!this.program) {
- return [];
- }
- if (!this.languageServiceEnabled) {
- var rootFiles = this.getRootFiles();
- if (this.compilerOptions) {
- var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions);
- if (defaultLibrary) {
- (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary));
- }
- }
- return rootFiles;
- }
- var sourceFiles = this.program.getSourceFiles();
- return sourceFiles.map(function (sourceFile) { return server.asNormalizedPath(sourceFile.fileName); });
- };
- Project.prototype.getAllEmittableFiles = function () {
- if (!this.languageServiceEnabled) {
- return [];
- }
- var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions);
- var infos = this.getScriptInfos();
- var result = [];
- for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
- var info = infos_1[_i];
- if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) {
- result.push(info.fileName);
- }
- }
- return result;
- };
- Project.prototype.containsScriptInfo = function (info) {
- return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined);
- };
- Project.prototype.containsFile = function (filename, requireOpen) {
- var info = this.projectService.getScriptInfoForNormalizedPath(filename);
- if (info && (info.isOpen || !requireOpen)) {
- return this.containsScriptInfo(info);
- }
- };
- Project.prototype.isRoot = function (info) {
- return this.rootFilesMap && this.rootFilesMap.contains(info.path);
- };
- Project.prototype.addRoot = function (info) {
- if (!this.isRoot(info)) {
- this.rootFiles.push(info);
- this.rootFilesMap.set(info.path, info);
- info.attachToProject(this);
- this.markAsDirty();
- }
- };
- Project.prototype.removeFile = function (info, detachFromProject) {
- if (detachFromProject === void 0) { detachFromProject = true; }
- this.removeRootFileIfNecessary(info);
- this.lsHost.notifyFileRemoved(info);
- if (detachFromProject) {
- info.detachFromProject(this);
- }
- this.markAsDirty();
- };
- Project.prototype.markAsDirty = function () {
- this.projectStateVersion++;
- };
- Project.prototype.updateGraph = function () {
- if (!this.languageServiceEnabled) {
- return true;
- }
- var hasChanges = this.updateGraphWorker();
- var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, hasChanges);
- if (this.setTypings(cachedTypings)) {
- hasChanges = this.updateGraphWorker() || hasChanges;
- }
- if (hasChanges) {
- this.projectStructureVersion++;
- }
- return !hasChanges;
- };
- Project.prototype.setTypings = function (typings) {
- if (ts.arrayIsEqualTo(this.typingFiles, typings)) {
- return false;
- }
- this.typingFiles = typings;
- this.markAsDirty();
- return true;
- };
- Project.prototype.updateGraphWorker = function () {
- var oldProgram = this.program;
- this.program = this.languageService.getProgram();
- var hasChanges = false;
- if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) {
- hasChanges = true;
- if (oldProgram) {
- for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) {
- var f = _a[_i];
- if (this.program.getSourceFileByPath(f.path)) {
- continue;
- }
- var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName);
- if (scriptInfoToDetach) {
- scriptInfoToDetach.detachFromProject(this);
- }
- }
- }
- }
- this.builder.onProjectUpdateGraph();
- return hasChanges;
- };
- Project.prototype.getScriptInfoLSHost = function (fileName) {
- var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false);
- if (scriptInfo) {
- scriptInfo.attachToProject(this);
- }
- return scriptInfo;
- };
- Project.prototype.getScriptInfoForNormalizedPath = function (fileName) {
- var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false);
- if (scriptInfo && !scriptInfo.isAttached(this)) {
- return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this);
- }
- return scriptInfo;
- };
- Project.prototype.getScriptInfo = function (uncheckedFileName) {
- return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
- };
- Project.prototype.filesToString = function () {
- if (!this.program) {
- return "";
- }
+ var spaceCache = [];
+ function generateSpaces(n) {
+ if (!spaceCache[n]) {
var strBuilder = "";
- for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) {
- var file = _a[_i];
- strBuilder += file.fileName + "\n";
+ for (var i = 0; i < n; i++) {
+ strBuilder += " ";
}
- return strBuilder;
- };
- Project.prototype.setCompilerOptions = function (compilerOptions) {
- if (compilerOptions) {
- if (this.projectKind === ProjectKind.Inferred) {
- compilerOptions.allowJs = true;
- }
- compilerOptions.allowNonTsExtensions = true;
- this.compilerOptions = compilerOptions;
- this.lsHost.setCompilationSettings(compilerOptions);
- this.markAsDirty();
- }
- };
- Project.prototype.reloadScript = function (filename) {
- var script = this.projectService.getScriptInfoForNormalizedPath(filename);
- if (script) {
- ts.Debug.assert(script.isAttached(this));
- script.reloadFromFile();
- return true;
- }
- return false;
- };
- Project.prototype.getChangesSinceVersion = function (lastKnownVersion) {
- this.updateGraph();
- var info = {
- projectName: this.getProjectName(),
- version: this.projectStructureVersion,
- isInferred: this.projectKind === ProjectKind.Inferred,
- options: this.getCompilerOptions()
- };
- if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
- if (this.projectStructureVersion == this.lastReportedVersion) {
- return { info: info, projectErrors: this.projectErrors };
- }
- var lastReportedFileNames = this.lastReportedFileNames;
- var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; });
- var added = [];
- var removed = [];
- for (var id in currentFiles) {
- if (!ts.hasProperty(lastReportedFileNames, id)) {
- added.push(id);
- }
- }
- for (var id in lastReportedFileNames) {
- if (!ts.hasProperty(currentFiles, id)) {
- removed.push(id);
- }
- }
- this.lastReportedFileNames = currentFiles;
- this.lastReportedVersion = this.projectStructureVersion;
- return { info: info, changes: { added: added, removed: removed }, projectErrors: this.projectErrors };
- }
- else {
- var projectFileNames = this.getFileNames();
- this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; });
- this.lastReportedVersion = this.projectStructureVersion;
- return { info: info, files: projectFileNames, projectErrors: this.projectErrors };
- }
- };
- Project.prototype.getReferencedFiles = function (path) {
- var _this = this;
- if (!this.languageServiceEnabled) {
- return [];
- }
- var sourceFile = this.getSourceFile(path);
- if (!sourceFile) {
- return [];
- }
- var referencedFiles = ts.createMap();
- if (sourceFile.imports && sourceFile.imports.length > 0) {
- var checker = this.program.getTypeChecker();
- for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
- var importName = _a[_i];
- var symbol = checker.getSymbolAtLocation(importName);
- if (symbol && symbol.declarations && symbol.declarations[0]) {
- var declarationSourceFile = symbol.declarations[0].getSourceFile();
- if (declarationSourceFile) {
- referencedFiles[declarationSourceFile.path] = true;
- }
- }
- }
- }
- var currentDirectory = ts.getDirectoryPath(path);
- var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames);
- if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
- for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
- var referencedFile = _c[_b];
- var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName);
- referencedFiles[referencedPath] = true;
- }
- }
- if (sourceFile.resolvedTypeReferenceDirectiveNames) {
- for (var typeName in sourceFile.resolvedTypeReferenceDirectiveNames) {
- var resolvedTypeReferenceDirective = sourceFile.resolvedTypeReferenceDirectiveNames[typeName];
- if (!resolvedTypeReferenceDirective) {
- continue;
- }
- var fileName = resolvedTypeReferenceDirective.resolvedFileName;
- var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
- referencedFiles[typeFilePath] = true;
- }
- }
- var allFileNames = ts.map(Object.keys(referencedFiles), function (key) { return key; });
- return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); });
- };
- Project.prototype.removeRootFileIfNecessary = function (info) {
- if (this.isRoot(info)) {
- remove(this.rootFiles, info);
- this.rootFilesMap.remove(info.path);
- }
- };
- return Project;
- }());
- server.Project = Project;
- var InferredProject = (function (_super) {
- __extends(InferredProject, _super);
- function InferredProject(projectService, documentRegistry, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) {
- _super.call(this, ProjectKind.Inferred, projectService, documentRegistry, undefined, languageServiceEnabled, compilerOptions, compileOnSaveEnabled);
- this.compileOnSaveEnabled = compileOnSaveEnabled;
- this.directoriesWatchedForTsconfig = [];
- this.inferredProjectName = server.makeInferredProjectName(InferredProject.NextId);
- InferredProject.NextId++;
+ spaceCache[n] = strBuilder;
}
- InferredProject.prototype.getProjectName = function () {
- return this.inferredProjectName;
- };
- InferredProject.prototype.getProjectRootPath = function () {
- if (this.projectService.useSingleInferredProject) {
- return undefined;
- }
- var rootFiles = this.getRootFiles();
- return ts.getDirectoryPath(rootFiles[0]);
- };
- InferredProject.prototype.close = function () {
- _super.prototype.close.call(this);
- for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) {
- var directory = _a[_i];
- this.projectService.stopWatchingDirectory(directory);
- }
- };
- InferredProject.prototype.getTypingOptions = function () {
- return {
- enableAutoDiscovery: allRootFilesAreJsOrDts(this),
- include: [],
- exclude: []
- };
- };
- return InferredProject;
- }(Project));
- InferredProject.NextId = 1;
- server.InferredProject = InferredProject;
- var ConfiguredProject = (function (_super) {
- __extends(ConfiguredProject, _super);
- function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) {
- _super.call(this, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled);
- this.configFileName = configFileName;
- this.wildcardDirectories = wildcardDirectories;
- this.compileOnSaveEnabled = compileOnSaveEnabled;
- this.openRefCount = 0;
- }
- ConfiguredProject.prototype.getProjectRootPath = function () {
- return ts.getDirectoryPath(this.configFileName);
- };
- ConfiguredProject.prototype.setProjectErrors = function (projectErrors) {
- this.projectErrors = projectErrors;
- };
- ConfiguredProject.prototype.setTypingOptions = function (newTypingOptions) {
- this.typingOptions = newTypingOptions;
- };
- ConfiguredProject.prototype.getTypingOptions = function () {
- return this.typingOptions;
- };
- ConfiguredProject.prototype.getProjectName = function () {
- return this.configFileName;
- };
- ConfiguredProject.prototype.watchConfigFile = function (callback) {
- var _this = this;
- this.projectFileWatcher = this.projectService.host.watchFile(this.configFileName, function (_) { return callback(_this); });
- };
- ConfiguredProject.prototype.watchTypeRoots = function (callback) {
- var _this = this;
- var roots = this.getEffectiveTypeRoots();
- var watchers = [];
- for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
- var root = roots_1[_i];
- this.projectService.logger.info("Add type root watcher for: " + root);
- watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false));
- }
- this.typeRootsWatchers = watchers;
- };
- ConfiguredProject.prototype.watchConfigDirectory = function (callback) {
- var _this = this;
- if (this.directoryWatcher) {
- return;
- }
- var directoryToWatch = ts.getDirectoryPath(this.configFileName);
- this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch);
- this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true);
- };
- ConfiguredProject.prototype.watchWildcards = function (callback) {
- var _this = this;
- if (!this.wildcardDirectories) {
- return;
- }
- var configDirectoryPath = ts.getDirectoryPath(this.configFileName);
- this.directoriesWatchedForWildcards = ts.reduceProperties(this.wildcardDirectories, function (watchers, flag, directory) {
- if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) {
- var recursive = (flag & 1) !== 0;
- _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory);
- watchers[directory] = _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive);
- }
- return watchers;
- }, {});
- };
- ConfiguredProject.prototype.stopWatchingDirectory = function () {
- if (this.directoryWatcher) {
- this.directoryWatcher.close();
- this.directoryWatcher = undefined;
- }
- };
- ConfiguredProject.prototype.close = function () {
- _super.prototype.close.call(this);
- if (this.projectFileWatcher) {
- this.projectFileWatcher.close();
- }
- if (this.typeRootsWatchers) {
- for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) {
- var watcher = _a[_i];
- watcher.close();
- }
- this.typeRootsWatchers = undefined;
- }
- for (var id in this.directoriesWatchedForWildcards) {
- this.directoriesWatchedForWildcards[id].close();
- }
- this.directoriesWatchedForWildcards = undefined;
- this.stopWatchingDirectory();
- };
- ConfiguredProject.prototype.addOpenRef = function () {
- this.openRefCount++;
- };
- ConfiguredProject.prototype.deleteOpenRef = function () {
- this.openRefCount--;
- return this.openRefCount;
- };
- ConfiguredProject.prototype.getEffectiveTypeRoots = function () {
- return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || [];
- };
- return ConfiguredProject;
- }(Project));
- server.ConfiguredProject = ConfiguredProject;
- var ExternalProject = (function (_super) {
- __extends(ExternalProject, _super);
- function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) {
- _super.call(this, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled);
- this.externalProjectName = externalProjectName;
- this.compileOnSaveEnabled = compileOnSaveEnabled;
- this.projectFilePath = projectFilePath;
- }
- ExternalProject.prototype.getProjectRootPath = function () {
- if (this.projectFilePath) {
- return ts.getDirectoryPath(this.projectFilePath);
- }
- return ts.getDirectoryPath(ts.normalizeSlashes(this.externalProjectName));
- };
- ExternalProject.prototype.getTypingOptions = function () {
- return this.typingOptions;
- };
- ExternalProject.prototype.setProjectErrors = function (projectErrors) {
- this.projectErrors = projectErrors;
- };
- ExternalProject.prototype.setTypingOptions = function (newTypingOptions) {
- if (!newTypingOptions) {
- newTypingOptions = {
- enableAutoDiscovery: allRootFilesAreJsOrDts(this),
- include: [],
- exclude: []
- };
- }
- else {
- if (newTypingOptions.enableAutoDiscovery === undefined) {
- newTypingOptions.enableAutoDiscovery = allRootFilesAreJsOrDts(this);
- }
- if (!newTypingOptions.include) {
- newTypingOptions.include = [];
- }
- if (!newTypingOptions.exclude) {
- newTypingOptions.exclude = [];
- }
- }
- this.typingOptions = newTypingOptions;
- };
- ExternalProject.prototype.getProjectName = function () {
- return this.externalProjectName;
- };
- return ExternalProject;
- }(Project));
- server.ExternalProject = ExternalProject;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
- function combineProjectOutput(projects, action, comparer, areEqual) {
- var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer);
- return projects.length > 1 ? ts.deduplicate(result, areEqual) : result;
+ return spaceCache[n];
}
- server.combineProjectOutput = combineProjectOutput;
- var fileNamePropertyReader = {
- getFileName: function (x) { return x; },
- getScriptKind: function (_) { return undefined; },
- hasMixedContent: function (_) { return false; }
- };
- var externalFilePropertyReader = {
- getFileName: function (x) { return x.fileName; },
- getScriptKind: function (x) { return x.scriptKind; },
- hasMixedContent: function (x) { return x.hasMixedContent; }
- };
- function findProjectByName(projectName, projects) {
- for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) {
- var proj = projects_1[_i];
- if (proj.getProjectName() === projectName) {
- return proj;
+ server.generateSpaces = generateSpaces;
+ function generateIndentString(n, editorOptions) {
+ if (editorOptions.ConvertTabsToSpaces) {
+ return generateSpaces(n);
+ }
+ else {
+ var result = "";
+ for (var i = 0; i < Math.floor(n / editorOptions.TabSize); i++) {
+ result += "\t";
}
+ for (var i = 0; i < n % editorOptions.TabSize; i++) {
+ result += " ";
+ }
+ return result;
}
}
- function createFileNotFoundDiagnostic(fileName) {
- return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName);
- }
- function isRootFileInInferredProject(info) {
- if (info.containingProjects.length === 0) {
- return false;
- }
- return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info);
- }
- var DirectoryWatchers = (function () {
- function DirectoryWatchers(projectService) {
- this.projectService = projectService;
- this.directoryWatchersForTsconfig = ts.createMap();
- this.directoryWatchersRefCount = ts.createMap();
- }
- DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) {
- this.directoryWatchersRefCount[directory]--;
- if (this.directoryWatchersRefCount[directory] === 0) {
- this.projectService.logger.info("Close directory watcher for: " + directory);
- this.directoryWatchersForTsconfig[directory].close();
- delete this.directoryWatchersForTsconfig[directory];
- }
- };
- DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) {
- var currentPath = ts.getDirectoryPath(fileName);
- var parentPath = ts.getDirectoryPath(currentPath);
- while (currentPath != parentPath) {
- if (!this.directoryWatchersForTsconfig[currentPath]) {
- this.projectService.logger.info("Add watcher for: " + currentPath);
- this.directoryWatchersForTsconfig[currentPath] = this.projectService.host.watchDirectory(currentPath, callback);
- this.directoryWatchersRefCount[currentPath] = 1;
- }
- else {
- this.directoryWatchersRefCount[currentPath] += 1;
- }
- project.directoriesWatchedForTsconfig.push(currentPath);
- currentPath = parentPath;
- parentPath = ts.getDirectoryPath(parentPath);
- }
- };
- return DirectoryWatchers;
- }());
- var ProjectService = (function () {
- function ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler) {
- if (typingsInstaller === void 0) { typingsInstaller = server.nullTypingsInstaller; }
- this.host = host;
- this.logger = logger;
- this.cancellationToken = cancellationToken;
- this.useSingleInferredProject = useSingleInferredProject;
- this.typingsInstaller = typingsInstaller;
- this.eventHandler = eventHandler;
- this.filenameToScriptInfo = ts.createFileMap();
- this.externalProjectToConfiguredProjectMap = ts.createMap();
- this.externalProjects = [];
- this.inferredProjects = [];
- this.configuredProjects = [];
- this.openFiles = [];
- this.toCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
- this.directoryWatchers = new DirectoryWatchers(this);
- this.throttledOperations = new server.ThrottledOperations(host);
- this.typingsInstaller.attach(this);
- this.typingsCache = new server.TypingsCache(this.typingsInstaller);
- this.hostConfiguration = {
- formatCodeOptions: server.getDefaultFormatCodeSettings(this.host),
- hostInfo: "Unknown host"
- };
- this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory());
- }
- ProjectService.prototype.getChangedFiles_TestOnly = function () {
- return this.changedFiles;
- };
- ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () {
- this.ensureInferredProjectsUpToDate();
- };
- ProjectService.prototype.updateTypingsForProject = function (response) {
- var project = this.findProject(response.projectName);
- if (!project) {
- return;
- }
- switch (response.kind) {
- case "set":
- this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.typings);
- project.updateGraph();
- break;
- case "invalidate":
- this.typingsCache.invalidateCachedTypingsForProject(project);
- break;
- }
- };
- ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) {
- this.compilerOptionsForInferredProjects = projectCompilerOptions;
- this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave;
- for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
- var proj = _a[_i];
- proj.setCompilerOptions(projectCompilerOptions);
- proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave;
- }
- this.updateProjectGraphs(this.inferredProjects);
- };
- ProjectService.prototype.stopWatchingDirectory = function (directory) {
- this.directoryWatchers.stopWatchingDirectory(directory);
- };
- ProjectService.prototype.findProject = function (projectName) {
- if (projectName === undefined) {
- return undefined;
- }
- if (server.isInferredProjectName(projectName)) {
- this.ensureInferredProjectsUpToDate();
- return findProjectByName(projectName, this.inferredProjects);
- }
- return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName));
- };
- ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) {
- if (refreshInferredProjects) {
- this.ensureInferredProjectsUpToDate();
- }
- var scriptInfo = this.getScriptInfoForNormalizedPath(fileName);
- return scriptInfo && scriptInfo.getDefaultProject();
- };
- ProjectService.prototype.ensureInferredProjectsUpToDate = function () {
- if (this.changedFiles) {
- var projectsToUpdate = void 0;
- if (this.changedFiles.length === 1) {
- projectsToUpdate = this.changedFiles[0].containingProjects;
- }
- else {
- projectsToUpdate = [];
- for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) {
- var f = _a[_i];
- projectsToUpdate = projectsToUpdate.concat(f.containingProjects);
- }
- }
- this.updateProjectGraphs(projectsToUpdate);
- this.changedFiles = undefined;
- }
- };
- ProjectService.prototype.findContainingExternalProject = function (fileName) {
- for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) {
- var proj = _a[_i];
- if (proj.containsFile(fileName)) {
- return proj;
- }
- }
- return undefined;
- };
- ProjectService.prototype.getFormatCodeOptions = function (file) {
- var formatCodeSettings;
- if (file) {
- var info = this.getScriptInfoForNormalizedPath(file);
- if (info) {
- formatCodeSettings = info.getFormatCodeSettings();
- }
- }
- return formatCodeSettings || this.hostConfiguration.formatCodeOptions;
- };
- ProjectService.prototype.updateProjectGraphs = function (projects) {
- var shouldRefreshInferredProjects = false;
- for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) {
- var p = projects_2[_i];
- if (!p.updateGraph()) {
- shouldRefreshInferredProjects = true;
- }
- }
- if (shouldRefreshInferredProjects) {
- this.refreshInferredProjects();
- }
- };
- ProjectService.prototype.onSourceFileChanged = function (fileName) {
- var info = this.getScriptInfoForNormalizedPath(fileName);
- if (!info) {
- this.logger.info("Error: got watch notification for unknown file: " + fileName);
- return;
- }
- if (!this.host.fileExists(fileName)) {
- this.handleDeletedFile(info);
- }
- else {
- if (info && (!info.isOpen)) {
- info.reloadFromFile();
- this.updateProjectGraphs(info.containingProjects);
- }
- }
- };
- ProjectService.prototype.handleDeletedFile = function (info) {
- this.logger.info(info.fileName + " deleted");
- info.stopWatcher();
- if (!info.isOpen) {
- this.filenameToScriptInfo.remove(info.path);
- var containingProjects = info.containingProjects.slice();
- info.detachAllProjects();
- this.updateProjectGraphs(containingProjects);
- if (!this.eventHandler) {
- return;
- }
- for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) {
- var openFile = _a[_i];
- this.eventHandler({ eventName: "context", data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } });
- }
- }
- this.printProjects();
- };
- ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) {
- var _this = this;
- this.logger.info("Type root file " + fileName + " changed");
- this.throttledOperations.schedule(project.configFileName + " * type root", 250, function () {
- project.updateTypes();
- _this.updateConfiguredProject(project);
- _this.refreshInferredProjects();
- });
- };
- ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) {
- var _this = this;
- if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) {
- return;
- }
- this.logger.info("Detected source file changes: " + fileName);
- this.throttledOperations.schedule(project.configFileName, 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project); });
- };
- ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project) {
- var _this = this;
- var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors;
- this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors);
- var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); }));
- var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); }));
- if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) {
- this.logger.info("Updating configured project");
- this.updateConfiguredProject(project);
- this.refreshInferredProjects();
- }
- };
- ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) {
- this.logger.info("Config file changed: " + project.configFileName);
- this.updateConfiguredProject(project);
- this.refreshInferredProjects();
- };
- ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) {
- if (ts.getBaseFileName(fileName) != "tsconfig.json") {
- this.logger.info(fileName + " is not tsconfig.json");
- return;
- }
- var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors;
- this.reportConfigFileDiagnostics(fileName, configFileErrors);
- this.logger.info("Detected newly added tsconfig file: " + fileName);
- this.reloadProjects();
- };
- ProjectService.prototype.getCanonicalFileName = function (fileName) {
- var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
- return ts.normalizePath(name);
- };
- ProjectService.prototype.removeProject = function (project) {
- this.logger.info("remove project: " + project.getRootFiles().toString());
- project.close();
- switch (project.projectKind) {
- case server.ProjectKind.External:
- server.removeItemFromSet(this.externalProjects, project);
- break;
- case server.ProjectKind.Configured:
- server.removeItemFromSet(this.configuredProjects, project);
- break;
- case server.ProjectKind.Inferred:
- server.removeItemFromSet(this.inferredProjects, project);
- break;
- }
- };
- ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) {
- var externalProject = this.findContainingExternalProject(info.fileName);
- if (externalProject) {
- if (addToListOfOpenFiles) {
- this.openFiles.push(info);
- }
- return;
- }
- var foundConfiguredProject = false;
- for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) {
- var p = _a[_i];
- if (p.projectKind === server.ProjectKind.Configured) {
- foundConfiguredProject = true;
- if (addToListOfOpenFiles) {
- (p).addOpenRef();
- }
- }
- }
- if (foundConfiguredProject) {
- if (addToListOfOpenFiles) {
- this.openFiles.push(info);
- }
- return;
- }
- if (info.containingProjects.length === 0) {
- var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info);
- if (!this.useSingleInferredProject) {
- for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) {
- var f = _c[_b];
- if (f.containingProjects.length === 0) {
- continue;
- }
- var defaultProject = f.getDefaultProject();
- if (isRootFileInInferredProject(info) && defaultProject !== inferredProject && inferredProject.containsScriptInfo(f)) {
- this.removeProject(defaultProject);
- f.attachToProject(inferredProject);
- }
- }
- }
- }
- if (addToListOfOpenFiles) {
- this.openFiles.push(info);
- }
- };
- ProjectService.prototype.closeOpenFile = function (info) {
- info.reloadFromFile();
- server.removeItemFromSet(this.openFiles, info);
- info.isOpen = false;
- var projectsToRemove;
- for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) {
- var p = _a[_i];
- if (p.projectKind === server.ProjectKind.Configured) {
- if (p.deleteOpenRef() === 0) {
- (projectsToRemove || (projectsToRemove = [])).push(p);
- }
- }
- else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) {
- (projectsToRemove || (projectsToRemove = [])).push(p);
- }
- }
- if (projectsToRemove) {
- for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) {
- var project = projectsToRemove_1[_b];
- this.removeProject(project);
- }
- var orphanFiles = void 0;
- for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) {
- var f = _d[_c];
- if (f.containingProjects.length === 0) {
- (orphanFiles || (orphanFiles = [])).push(f);
- }
- }
- if (orphanFiles) {
- for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) {
- var f = orphanFiles_1[_e];
- this.assignScriptInfoToInferredProjectIfNecessary(f, false);
- }
- }
- }
- if (info.containingProjects.length === 0) {
- this.filenameToScriptInfo.remove(info.path);
- }
- };
- ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) {
- var searchPath = ts.getDirectoryPath(fileName);
- this.logger.info("Search path: " + searchPath);
- var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath));
- if (!configFileName) {
- this.logger.info("No config files found.");
- return {};
- }
- this.logger.info("Config file name: " + configFileName);
- var project = this.findConfiguredProjectByProjectName(configFileName);
- if (!project) {
- var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors;
- if (!success) {
- return { configFileName: configFileName, configFileErrors: errors };
- }
- this.logger.info("Opened configuration file " + configFileName);
- if (errors && errors.length > 0) {
- return { configFileName: configFileName, configFileErrors: errors };
- }
- }
- else {
- this.updateConfiguredProject(project);
- }
- return { configFileName: configFileName };
- };
- ProjectService.prototype.findConfigFile = function (searchPath) {
- while (true) {
- var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json"));
- if (this.host.fileExists(tsconfigFileName)) {
- return tsconfigFileName;
- }
- var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json"));
- if (this.host.fileExists(jsconfigFileName)) {
- return jsconfigFileName;
- }
- var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath));
- if (parentPath === searchPath) {
- break;
- }
- searchPath = parentPath;
- }
- return undefined;
- };
- ProjectService.prototype.printProjects = function () {
- if (!this.logger.hasLevel(server.LogLevel.verbose)) {
- return;
- }
- this.logger.startGroup();
- var counter = 0;
- counter = printProjects(this.logger, this.externalProjects, counter);
- counter = printProjects(this.logger, this.configuredProjects, counter);
- counter = printProjects(this.logger, this.inferredProjects, counter);
- this.logger.info("Open files: ");
- for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) {
- var rootFile = _a[_i];
- this.logger.info(rootFile.fileName);
- }
- this.logger.endGroup();
- function printProjects(logger, projects, counter) {
- for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) {
- var project = projects_3[_i];
- project.updateGraph();
- logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter);
- logger.info(project.filesToString());
- logger.info("-----------------------------------------------");
- counter++;
- }
- return counter;
- }
- };
- ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) {
- return findProjectByName(configFileName, this.configuredProjects);
- };
- ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) {
- return findProjectByName(projectFileName, this.externalProjects);
- };
- ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) {
- configFilename = ts.normalizePath(configFilename);
- var configFileContent = this.host.readFile(configFilename);
- var errors;
- var result = ts.parseConfigFileTextToJson(configFilename, configFileContent);
- var config = result.config;
- if (result.error) {
- var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics;
- config = sanitizedConfig;
- errors = diagnostics.length ? diagnostics : [result.error];
- }
- var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename);
- if (parsedCommandLine.errors.length) {
- errors = ts.concatenate(errors, parsedCommandLine.errors);
- }
- ts.Debug.assert(!!parsedCommandLine.fileNames);
- if (parsedCommandLine.fileNames.length === 0) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename));
- return { success: false, configFileErrors: errors };
- }
- var projectOptions = {
- files: parsedCommandLine.fileNames,
- compilerOptions: parsedCommandLine.options,
- configHasFilesProperty: config["files"] !== undefined,
- wildcardDirectories: ts.createMap(parsedCommandLine.wildcardDirectories),
- typingOptions: parsedCommandLine.typingOptions,
- compileOnSave: parsedCommandLine.compileOnSave
- };
- return { success: true, projectOptions: projectOptions, configFileErrors: errors };
- };
- ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (options, fileNames, propertyReader) {
- if (options && options.disableSizeLimit || !this.host.getFileSize) {
- return false;
- }
- var totalNonTsFileSize = 0;
- for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) {
- var f = fileNames_3[_i];
- var fileName = propertyReader.getFileName(f);
- if (ts.hasTypeScriptFileExtension(fileName)) {
- continue;
- }
- totalNonTsFileSize += this.host.getFileSize(fileName);
- if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) {
- return true;
- }
- }
- return false;
- };
- ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typingOptions) {
- var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, options, !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave);
- this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typingOptions, undefined);
- this.externalProjects.push(project);
- return project;
- };
- ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) {
- if (diagnostics && diagnostics.length > 0) {
- this.eventHandler({
- eventName: "configFileDiag",
- data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile }
- });
- }
- };
- ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) {
- var _this = this;
- var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader);
- var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave);
- this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors);
- project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); });
- if (!sizeLimitExceeded) {
- this.watchConfigDirectoryForProject(project, projectOptions);
- }
- project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); });
- project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); });
- this.configuredProjects.push(project);
- return project;
- };
- ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) {
- var _this = this;
- if (!options.configHasFilesProperty) {
- project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); });
- }
- };
- ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typingOptions, configFileErrors) {
- var errors;
- for (var _i = 0, files_4 = files; _i < files_4.length; _i++) {
- var f = files_4[_i];
- var rootFilename = propertyReader.getFileName(f);
- var scriptKind = propertyReader.getScriptKind(f);
- var hasMixedContent = propertyReader.hasMixedContent(f);
- if (this.host.fileExists(rootFilename)) {
- var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent);
- project.addRoot(info);
- }
- else {
- (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename));
- }
- }
- project.setProjectErrors(ts.concatenate(configFileErrors, errors));
- project.setTypingOptions(typingOptions);
- project.updateGraph();
- };
- ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) {
- var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName);
- var projectOptions = conversionResult.success
- ? conversionResult.projectOptions
- : { files: [], compilerOptions: {} };
- var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName);
- return {
- success: conversionResult.success,
- project: project,
- errors: project.getProjectErrors()
- };
- };
- ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors) {
- var oldRootScriptInfos = project.getRootScriptInfos();
- var newRootScriptInfos = [];
- var newRootScriptInfoMap = server.createNormalizedPathMap();
- var projectErrors;
- var rootFilesChanged = false;
- for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) {
- var f = newUncheckedFiles_1[_i];
- var newRootFile = propertyReader.getFileName(f);
- if (!this.host.fileExists(newRootFile)) {
- (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile));
- continue;
- }
- var normalizedPath = server.toNormalizedPath(newRootFile);
- var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath);
- if (!scriptInfo || !project.isRoot(scriptInfo)) {
- rootFilesChanged = true;
- if (!scriptInfo) {
- var scriptKind = propertyReader.getScriptKind(f);
- var hasMixedContent = propertyReader.hasMixedContent(f);
- scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent);
- }
- }
- newRootScriptInfos.push(scriptInfo);
- newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo);
- }
- if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) {
- var toAdd = void 0;
- var toRemove = void 0;
- for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) {
- var oldFile = oldRootScriptInfos_1[_a];
- if (!newRootScriptInfoMap.contains(oldFile.fileName)) {
- (toRemove || (toRemove = [])).push(oldFile);
- }
- }
- for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) {
- var newFile = newRootScriptInfos_1[_b];
- if (!project.isRoot(newFile)) {
- (toAdd || (toAdd = [])).push(newFile);
- }
- }
- if (toRemove) {
- for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) {
- var f = toRemove_1[_c];
- project.removeFile(f);
- }
- }
- if (toAdd) {
- for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) {
- var f = toAdd_1[_d];
- if (f.isOpen && isRootFileInInferredProject(f)) {
- var inferredProject = f.containingProjects[0];
- inferredProject.removeFile(f);
- if (!inferredProject.hasRoots()) {
- this.removeProject(inferredProject);
- }
- }
- project.addRoot(f);
- }
- }
- }
- project.setCompilerOptions(newOptions);
- project.setTypingOptions(newTypingOptions);
- if (compileOnSave !== undefined) {
- project.compileOnSaveEnabled = compileOnSave;
- }
- project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors));
- project.updateGraph();
- };
- ProjectService.prototype.updateConfiguredProject = function (project) {
- if (!this.host.fileExists(project.configFileName)) {
- this.logger.info("Config file deleted");
- this.removeProject(project);
- return;
- }
- var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors;
- if (!success) {
- this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors);
- return configFileErrors;
- }
- if (this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) {
- project.setCompilerOptions(projectOptions.compilerOptions);
- if (!project.languageServiceEnabled) {
- return;
- }
- project.disableLanguageService();
- project.stopWatchingDirectory();
- }
- else {
- if (!project.languageServiceEnabled) {
- project.enableLanguageService();
- }
- this.watchConfigDirectoryForProject(project, projectOptions);
- this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typingOptions, projectOptions.compileOnSave, configFileErrors);
- }
- };
- ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) {
- var _this = this;
- var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length;
- var project = useExistingProject
- ? this.inferredProjects[0]
- : new server.InferredProject(this, this.documentRegistry, true, this.compilerOptionsForInferredProjects, this.compileOnSaveForInferredProjects);
- project.addRoot(root);
- this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); });
- project.updateGraph();
- if (!useExistingProject) {
- this.inferredProjects.push(project);
- }
- return project;
- };
- ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) {
- return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind);
- };
- ProjectService.prototype.getScriptInfo = function (uncheckedFileName) {
- return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
- };
- ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) {
- var _this = this;
- var info = this.getScriptInfoForNormalizedPath(fileName);
- if (!info) {
- var content = void 0;
- if (this.host.fileExists(fileName)) {
- content = fileContent || (hasMixedContent ? "" : this.host.readFile(fileName));
- }
- if (!content) {
- if (openedByClient) {
- content = "";
- }
- }
- if (content !== undefined) {
- info = new server.ScriptInfo(this.host, fileName, content, scriptKind, openedByClient, hasMixedContent);
- this.filenameToScriptInfo.set(info.path, info);
- if (!info.isOpen && !hasMixedContent) {
- info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); }));
- }
- }
- }
- if (info) {
- if (fileContent !== undefined) {
- info.reload(fileContent);
- }
- if (openedByClient) {
- info.isOpen = true;
- }
- }
- return info;
- };
- ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) {
- return this.filenameToScriptInfo.get(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName));
- };
- ProjectService.prototype.setHostConfiguration = function (args) {
- if (args.file) {
- var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file));
- if (info) {
- info.setFormatOptions(args.formatOptions);
- this.logger.info("Host configuration update for file " + args.file);
- }
- }
- else {
- if (args.hostInfo !== undefined) {
- this.hostConfiguration.hostInfo = args.hostInfo;
- this.logger.info("Host information " + args.hostInfo);
- }
- if (args.formatOptions) {
- server.mergeMaps(this.hostConfiguration.formatCodeOptions, args.formatOptions);
- this.logger.info("Format host information updated");
- }
- }
- };
- ProjectService.prototype.closeLog = function () {
- this.logger.close();
- };
- ProjectService.prototype.reloadProjects = function () {
- this.logger.info("reload projects.");
- for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) {
- var info = _a[_i];
- this.openOrUpdateConfiguredProjectForFile(info.fileName);
- }
- this.refreshInferredProjects();
- };
- ProjectService.prototype.refreshInferredProjects = function () {
- this.logger.info("updating project structure from ...");
- this.printProjects();
- var orphantedFiles = [];
- for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) {
- var info = _a[_i];
- if (info.containingProjects.length === 0) {
- orphantedFiles.push(info);
- }
- else {
- if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) {
- var inferredProject = info.containingProjects[0];
- ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred);
- inferredProject.removeFile(info);
- if (!inferredProject.hasRoots()) {
- this.removeProject(inferredProject);
- }
- }
- }
- }
- for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) {
- var f = orphantedFiles_1[_b];
- this.assignScriptInfoToInferredProjectIfNecessary(f, false);
- }
- for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) {
- var p = _d[_c];
- p.updateGraph();
- }
- this.printProjects();
- };
- ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) {
- return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind);
- };
- ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) {
- var _a = this.findContainingExternalProject(fileName)
- ? {}
- : this.openOrUpdateConfiguredProjectForFile(fileName), _b = _a.configFileName, configFileName = _b === void 0 ? undefined : _b, _c = _a.configFileErrors, configFileErrors = _c === void 0 ? undefined : _c;
- var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent);
- this.assignScriptInfoToInferredProjectIfNecessary(info, true);
- this.printProjects();
- return { configFileName: configFileName, configFileErrors: configFileErrors };
- };
- ProjectService.prototype.closeClientFile = function (uncheckedFileName) {
- var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
- if (info) {
- this.closeOpenFile(info);
- info.isOpen = false;
- }
- this.printProjects();
- };
- ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) {
- var _loop_3 = function (proj) {
- var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; });
- result.push(proj.getChangesSinceVersion(knownProject && knownProject.version));
- };
- for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) {
- var proj = currentProjects_1[_i];
- _loop_3(proj);
- }
- };
- ProjectService.prototype.synchronizeProjectList = function (knownProjects) {
- var files = [];
- this.collectChanges(knownProjects, this.externalProjects, files);
- this.collectChanges(knownProjects, this.configuredProjects, files);
- this.collectChanges(knownProjects, this.inferredProjects, files);
- return files;
- };
- ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) {
- var recordChangedFiles = changedFiles && !openFiles && !closedFiles;
- if (openFiles) {
- for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) {
- var file = openFiles_1[_i];
- var scriptInfo = this.getScriptInfo(file.fileName);
- ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen);
- var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName);
- this.openClientFileWithNormalizedPath(normalizedPath, file.content, file.scriptKind, file.hasMixedContent);
- }
- }
- if (changedFiles) {
- for (var _a = 0, changedFiles_1 = changedFiles; _a < changedFiles_1.length; _a++) {
- var file = changedFiles_1[_a];
- var scriptInfo = this.getScriptInfo(file.fileName);
- ts.Debug.assert(!!scriptInfo);
- for (var i = file.changes.length - 1; i >= 0; i--) {
- var change = file.changes[i];
- scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
- }
- if (recordChangedFiles) {
- if (!this.changedFiles) {
- this.changedFiles = [scriptInfo];
- }
- else if (this.changedFiles.indexOf(scriptInfo) < 0) {
- this.changedFiles.push(scriptInfo);
- }
- }
- }
- }
- if (closedFiles) {
- for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) {
- var file = closedFiles_1[_b];
- this.closeClientFile(file);
- }
- }
- if (openFiles || closedFiles) {
- this.refreshInferredProjects();
- }
- };
- ProjectService.prototype.closeConfiguredProject = function (configFile) {
- var configuredProject = this.findConfiguredProjectByProjectName(configFile);
- if (configuredProject && configuredProject.deleteOpenRef() === 0) {
- this.removeProject(configuredProject);
- }
- };
- ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) {
- if (suppressRefresh === void 0) { suppressRefresh = false; }
- var fileName = server.toNormalizedPath(uncheckedFileName);
- var configFiles = this.externalProjectToConfiguredProjectMap[fileName];
- if (configFiles) {
- var shouldRefreshInferredProjects = false;
- for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) {
- var configFile = configFiles_1[_i];
- if (this.closeConfiguredProject(configFile)) {
- shouldRefreshInferredProjects = true;
- }
- }
- delete this.externalProjectToConfiguredProjectMap[fileName];
- if (shouldRefreshInferredProjects && !suppressRefresh) {
- this.refreshInferredProjects();
- }
- }
- else {
- var externalProject = this.findExternalProjectByProjectName(uncheckedFileName);
- if (externalProject) {
- this.removeProject(externalProject);
- if (!suppressRefresh) {
- this.refreshInferredProjects();
- }
- }
- }
- };
- ProjectService.prototype.openExternalProject = function (proj) {
- var tsConfigFiles;
- var rootFiles = [];
- for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) {
- var file = _a[_i];
- var normalized = server.toNormalizedPath(file.fileName);
- if (ts.getBaseFileName(normalized) === "tsconfig.json") {
- (tsConfigFiles || (tsConfigFiles = [])).push(normalized);
- }
- else {
- rootFiles.push(file);
- }
- }
- if (tsConfigFiles) {
- tsConfigFiles.sort();
- }
- var externalProject = this.findExternalProjectByProjectName(proj.projectFileName);
- var exisingConfigFiles;
- if (externalProject) {
- if (!tsConfigFiles) {
- this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, proj.options, proj.typingOptions, proj.options.compileOnSave, undefined);
- return;
- }
- this.closeExternalProject(proj.projectFileName, true);
- }
- else if (this.externalProjectToConfiguredProjectMap[proj.projectFileName]) {
- if (!tsConfigFiles) {
- this.closeExternalProject(proj.projectFileName, true);
- }
- else {
- var oldConfigFiles = this.externalProjectToConfiguredProjectMap[proj.projectFileName];
- var iNew = 0;
- var iOld = 0;
- while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) {
- var newConfig = tsConfigFiles[iNew];
- var oldConfig = oldConfigFiles[iOld];
- if (oldConfig < newConfig) {
- this.closeConfiguredProject(oldConfig);
- iOld++;
- }
- else if (oldConfig > newConfig) {
- iNew++;
- }
- else {
- (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig);
- iOld++;
- iNew++;
- }
- }
- for (var i = iOld; i < oldConfigFiles.length; i++) {
- this.closeConfiguredProject(oldConfigFiles[i]);
- }
- }
- }
- if (tsConfigFiles) {
- this.externalProjectToConfiguredProjectMap[proj.projectFileName] = tsConfigFiles;
- for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) {
- var tsconfigFile = tsConfigFiles_1[_b];
- var project = this.findConfiguredProjectByProjectName(tsconfigFile);
- if (!project) {
- var result = this.openConfigFile(tsconfigFile);
- project = result.success && result.project;
- }
- if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) {
- project.addOpenRef();
- }
- }
- }
- else {
- delete this.externalProjectToConfiguredProjectMap[proj.projectFileName];
- this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typingOptions);
- }
- this.refreshInferredProjects();
- };
- return ProjectService;
- }());
- server.ProjectService = ProjectService;
- })(server = ts.server || (ts.server = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var server;
- (function (server) {
- function hrTimeToMilliseconds(time) {
- var seconds = time[0];
- var nanoseconds = time[1];
- return ((1e9 * seconds) + nanoseconds) / 1000000.0;
- }
+ server.generateIndentString = generateIndentString;
function compareNumber(a, b) {
- return a - b;
+ if (a < b) {
+ return -1;
+ }
+ else if (a === b) {
+ return 0;
+ }
+ else
+ return 1;
}
function compareFileStart(a, b) {
if (a.file < b.file) {
@@ -62855,10 +60288,9 @@ var ts;
}
}
function formatDiag(fileName, project, diag) {
- var scriptInfo = project.getScriptInfoForNormalizedPath(fileName);
return {
- start: scriptInfo.positionToLineOffset(diag.start),
- end: scriptInfo.positionToLineOffset(diag.start + diag.length),
+ start: project.compilerService.host.positionToLineOffset(fileName, diag.start),
+ end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length),
text: ts.flattenDiagnosticMessageText(diag.messageText, "\n")
};
}
@@ -62870,9 +60302,8 @@ var ts;
};
}
function allEditsBeforePos(edits, pos) {
- for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
- var edit = edits_1[_i];
- if (ts.textSpanEnd(edit.span) >= pos) {
+ for (var i = 0, len = edits.length; i < len; i++) {
+ if (ts.textSpanEnd(edits[i].span) >= pos) {
return false;
}
}
@@ -62881,153 +60312,73 @@ var ts;
var CommandNames;
(function (CommandNames) {
CommandNames.Brace = "brace";
- CommandNames.BraceFull = "brace-full";
- CommandNames.BraceCompletion = "braceCompletion";
CommandNames.Change = "change";
CommandNames.Close = "close";
CommandNames.Completions = "completions";
- CommandNames.CompletionsFull = "completions-full";
CommandNames.CompletionDetails = "completionEntryDetails";
- CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList";
- CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile";
CommandNames.Configure = "configure";
CommandNames.Definition = "definition";
- CommandNames.DefinitionFull = "definition-full";
CommandNames.Exit = "exit";
CommandNames.Format = "format";
CommandNames.Formatonkey = "formatonkey";
- CommandNames.FormatFull = "format-full";
- CommandNames.FormatonkeyFull = "formatonkey-full";
- CommandNames.FormatRangeFull = "formatRange-full";
CommandNames.Geterr = "geterr";
CommandNames.GeterrForProject = "geterrForProject";
+ CommandNames.Implementation = "implementation";
CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync";
CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync";
CommandNames.NavBar = "navbar";
- CommandNames.NavBarFull = "navbar-full";
CommandNames.Navto = "navto";
- CommandNames.NavtoFull = "navto-full";
CommandNames.Occurrences = "occurrences";
CommandNames.DocumentHighlights = "documentHighlights";
- CommandNames.DocumentHighlightsFull = "documentHighlights-full";
CommandNames.Open = "open";
CommandNames.Quickinfo = "quickinfo";
- CommandNames.QuickinfoFull = "quickinfo-full";
CommandNames.References = "references";
- CommandNames.ReferencesFull = "references-full";
CommandNames.Reload = "reload";
CommandNames.Rename = "rename";
- CommandNames.RenameInfoFull = "rename-full";
- CommandNames.RenameLocationsFull = "renameLocations-full";
CommandNames.Saveto = "saveto";
CommandNames.SignatureHelp = "signatureHelp";
- CommandNames.SignatureHelpFull = "signatureHelp-full";
CommandNames.TypeDefinition = "typeDefinition";
CommandNames.ProjectInfo = "projectInfo";
CommandNames.ReloadProjects = "reloadProjects";
CommandNames.Unknown = "unknown";
- CommandNames.OpenExternalProject = "openExternalProject";
- CommandNames.OpenExternalProjects = "openExternalProjects";
- CommandNames.CloseExternalProject = "closeExternalProject";
- CommandNames.SynchronizeProjectList = "synchronizeProjectList";
- CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles";
- CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full";
- CommandNames.Cleanup = "cleanup";
- CommandNames.OutliningSpans = "outliningSpans";
- CommandNames.TodoComments = "todoComments";
- CommandNames.Indentation = "indentation";
- CommandNames.DocCommentTemplate = "docCommentTemplate";
- CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full";
- CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan";
- CommandNames.BreakpointStatement = "breakpointStatement";
- CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects";
})(CommandNames = server.CommandNames || (server.CommandNames = {}));
- function formatMessage(msg, logger, byteLength, newLine) {
- var verboseLogging = logger.hasLevel(server.LogLevel.verbose);
- var json = JSON.stringify(msg);
- if (verboseLogging) {
- logger.info(msg.type + ": " + json);
- }
- var len = byteLength(json, "utf8");
- return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine;
- }
- server.formatMessage = formatMessage;
+ var Errors;
+ (function (Errors) {
+ Errors.NoProject = new Error("No Project.");
+ Errors.ProjectLanguageServiceDisabled = new Error("The project's language service is disabled.");
+ })(Errors || (Errors = {}));
var Session = (function () {
- function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents) {
+ function Session(host, byteLength, hrtime, logger) {
var _this = this;
this.host = host;
- this.typingsInstaller = typingsInstaller;
this.byteLength = byteLength;
this.hrtime = hrtime;
this.logger = logger;
- this.canUseEvents = canUseEvents;
this.changeSeq = 0;
this.handlers = ts.createMap((_a = {},
- _a[CommandNames.OpenExternalProject] = function (request) {
- _this.projectService.openExternalProject(request.arguments);
- return _this.requiredResponse(true);
- },
- _a[CommandNames.OpenExternalProjects] = function (request) {
- for (var _i = 0, _a = request.arguments.projects; _i < _a.length; _i++) {
- var proj = _a[_i];
- _this.projectService.openExternalProject(proj);
- }
- return _this.requiredResponse(true);
- },
- _a[CommandNames.CloseExternalProject] = function (request) {
- _this.projectService.closeExternalProject(request.arguments.projectFileName);
- return _this.requiredResponse(true);
- },
- _a[CommandNames.SynchronizeProjectList] = function (request) {
- var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects);
- if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) {
- return _this.requiredResponse(result);
- }
- var converted = ts.map(result, function (p) {
- if (!p.projectErrors || p.projectErrors.length === 0) {
- return p;
- }
- return {
- info: p.info,
- changes: p.changes,
- files: p.files,
- projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined)
- };
- });
- return _this.requiredResponse(converted);
- },
- _a[CommandNames.ApplyChangedToOpenFiles] = function (request) {
- _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles);
- _this.changeSeq++;
- return _this.requiredResponse(true);
- },
_a[CommandNames.Exit] = function () {
_this.exit();
- return _this.notRequired();
+ return { responseRequired: false };
},
_a[CommandNames.Definition] = function (request) {
- return _this.requiredResponse(_this.getDefinition(request.arguments, true));
- },
- _a[CommandNames.DefinitionFull] = function (request) {
- return _this.requiredResponse(_this.getDefinition(request.arguments, false));
+ var defArgs = request.arguments;
+ return { response: _this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true };
},
_a[CommandNames.TypeDefinition] = function (request) {
- return _this.requiredResponse(_this.getTypeDefinition(request.arguments));
+ var defArgs = request.arguments;
+ return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true };
+ },
+ _a[CommandNames.Implementation] = function (request) {
+ var implArgs = request.arguments;
+ return { response: _this.getImplementation(implArgs.line, implArgs.offset, implArgs.file), responseRequired: true };
},
_a[CommandNames.References] = function (request) {
- return _this.requiredResponse(_this.getReferences(request.arguments, true));
- },
- _a[CommandNames.ReferencesFull] = function (request) {
- return _this.requiredResponse(_this.getReferences(request.arguments, false));
+ var defArgs = request.arguments;
+ return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true };
},
_a[CommandNames.Rename] = function (request) {
- return _this.requiredResponse(_this.getRenameLocations(request.arguments, true));
- },
- _a[CommandNames.RenameLocationsFull] = function (request) {
- return _this.requiredResponse(_this.getRenameLocations(request.arguments, false));
- },
- _a[CommandNames.RenameInfoFull] = function (request) {
- return _this.requiredResponse(_this.getRenameInfo(request.arguments));
+ var renameArgs = request.arguments;
+ return { response: _this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true };
},
_a[CommandNames.Open] = function (request) {
var openArgs = request.arguments;
@@ -63046,81 +60397,34 @@ var ts;
scriptKind = 2;
break;
}
- _this.openClientFile(server.toNormalizedPath(openArgs.file), openArgs.fileContent, scriptKind);
- return _this.notRequired();
+ _this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind);
+ return { responseRequired: false };
},
_a[CommandNames.Quickinfo] = function (request) {
- return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true));
- },
- _a[CommandNames.QuickinfoFull] = function (request) {
- return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false));
- },
- _a[CommandNames.OutliningSpans] = function (request) {
- return _this.requiredResponse(_this.getOutliningSpans(request.arguments));
- },
- _a[CommandNames.TodoComments] = function (request) {
- return _this.requiredResponse(_this.getTodoComments(request.arguments));
- },
- _a[CommandNames.Indentation] = function (request) {
- return _this.requiredResponse(_this.getIndentation(request.arguments));
- },
- _a[CommandNames.NameOrDottedNameSpan] = function (request) {
- return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments));
- },
- _a[CommandNames.BreakpointStatement] = function (request) {
- return _this.requiredResponse(_this.getBreakpointStatement(request.arguments));
- },
- _a[CommandNames.BraceCompletion] = function (request) {
- return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments));
- },
- _a[CommandNames.DocCommentTemplate] = function (request) {
- return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments));
+ var quickinfoArgs = request.arguments;
+ return { response: _this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true };
},
_a[CommandNames.Format] = function (request) {
- return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments));
+ var formatArgs = request.arguments;
+ return { response: _this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true };
},
_a[CommandNames.Formatonkey] = function (request) {
- return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments));
- },
- _a[CommandNames.FormatFull] = function (request) {
- return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments));
- },
- _a[CommandNames.FormatonkeyFull] = function (request) {
- return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments));
- },
- _a[CommandNames.FormatRangeFull] = function (request) {
- return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments));
+ var formatOnKeyArgs = request.arguments;
+ return { response: _this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true };
},
_a[CommandNames.Completions] = function (request) {
- return _this.requiredResponse(_this.getCompletions(request.arguments, true));
- },
- _a[CommandNames.CompletionsFull] = function (request) {
- return _this.requiredResponse(_this.getCompletions(request.arguments, false));
+ var completionsArgs = request.arguments;
+ return { response: _this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true };
},
_a[CommandNames.CompletionDetails] = function (request) {
- return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments));
- },
- _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) {
- return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments));
- },
- _a[CommandNames.CompileOnSaveEmitFile] = function (request) {
- return _this.requiredResponse(_this.emitFile(request.arguments));
+ var completionDetailsArgs = request.arguments;
+ return {
+ response: _this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true
+ };
},
_a[CommandNames.SignatureHelp] = function (request) {
- return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true));
- },
- _a[CommandNames.SignatureHelpFull] = function (request) {
- return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false));
- },
- _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) {
- return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments));
- },
- _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) {
- return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments));
- },
- _a[CommandNames.Cleanup] = function (request) {
- _this.cleanup();
- return _this.requiredResponse(true);
+ var signatureHelpArgs = request.arguments;
+ return { response: _this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true };
},
_a[CommandNames.SemanticDiagnosticsSync] = function (request) {
return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments));
@@ -63137,71 +60441,64 @@ var ts;
return { response: _this.getDiagnosticsForProject(delay, file), responseRequired: false };
},
_a[CommandNames.Change] = function (request) {
- _this.change(request.arguments);
- return _this.notRequired();
+ var changeArgs = request.arguments;
+ _this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file);
+ return { responseRequired: false };
},
_a[CommandNames.Configure] = function (request) {
- _this.projectService.setHostConfiguration(request.arguments);
+ var configureArgs = request.arguments;
+ _this.projectService.setHostConfiguration(configureArgs);
_this.output(undefined, CommandNames.Configure, request.seq);
- return _this.notRequired();
+ return { responseRequired: false };
},
_a[CommandNames.Reload] = function (request) {
- _this.reload(request.arguments, request.seq);
- return _this.requiredResponse({ reloadFinished: true });
+ var reloadArgs = request.arguments;
+ _this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq);
+ return { response: { reloadFinished: true }, responseRequired: true };
},
_a[CommandNames.Saveto] = function (request) {
var savetoArgs = request.arguments;
_this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile);
- return _this.notRequired();
+ return { responseRequired: false };
},
_a[CommandNames.Close] = function (request) {
var closeArgs = request.arguments;
_this.closeClientFile(closeArgs.file);
- return _this.notRequired();
+ return { responseRequired: false };
},
_a[CommandNames.Navto] = function (request) {
- return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true));
- },
- _a[CommandNames.NavtoFull] = function (request) {
- return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false));
+ var navtoArgs = request.arguments;
+ return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount, navtoArgs.currentFileOnly), responseRequired: true };
},
_a[CommandNames.Brace] = function (request) {
- return _this.requiredResponse(_this.getBraceMatching(request.arguments, true));
- },
- _a[CommandNames.BraceFull] = function (request) {
- return _this.requiredResponse(_this.getBraceMatching(request.arguments, false));
+ var braceArguments = request.arguments;
+ return { response: _this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true };
},
_a[CommandNames.NavBar] = function (request) {
- return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true));
- },
- _a[CommandNames.NavBarFull] = function (request) {
- return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false));
+ var navBarArgs = request.arguments;
+ return { response: _this.getNavigationBarItems(navBarArgs.file), responseRequired: true };
},
_a[CommandNames.Occurrences] = function (request) {
- return _this.requiredResponse(_this.getOccurrences(request.arguments));
+ var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file;
+ return { response: _this.getOccurrences(line, offset, fileName), responseRequired: true };
},
_a[CommandNames.DocumentHighlights] = function (request) {
- return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true));
- },
- _a[CommandNames.DocumentHighlightsFull] = function (request) {
- return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false));
- },
- _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) {
- return _this.requiredResponse(_this.setCompilerOptionsForInferredProjects(request.arguments));
+ var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file, filesToSearch = _a.filesToSearch;
+ return { response: _this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true };
},
_a[CommandNames.ProjectInfo] = function (request) {
- return _this.requiredResponse(_this.getProjectInfo(request.arguments));
+ var _a = request.arguments, file = _a.file, needFileNameList = _a.needFileNameList;
+ return { response: _this.getProjectInfo(file, needFileNameList), responseRequired: true };
},
_a[CommandNames.ReloadProjects] = function (request) {
- _this.projectService.reloadProjects();
- return _this.notRequired();
+ _this.reloadProjects();
+ return { responseRequired: false };
},
_a));
- var eventHandler = canUseEvents
- ? function (event) { return _this.handleEvent(event); }
- : undefined;
- this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler);
- this.gcTimer = new server.GcTimer(host, 7000, logger);
+ this.projectService =
+ new server.ProjectService(host, logger, function (event) {
+ _this.handleEvent(event);
+ });
var _a;
}
Session.prototype.handleEvent = function (event) {
@@ -63209,7 +60506,7 @@ var ts;
switch (event.eventName) {
case "context":
var _a = event.data, project = _a.project, fileName = _a.fileName;
- this.projectService.logger.info("got context event, updating diagnostics for " + fileName);
+ this.projectService.log("got context event, updating diagnostics for" + fileName, "Info");
this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100);
break;
case "configFileDiag":
@@ -63218,23 +60515,26 @@ var ts;
}
};
Session.prototype.logError = function (err, cmd) {
+ var typedErr = err;
var msg = "Exception on executing command " + cmd;
- if (err.message) {
- msg += ":\n" + err.message;
- if (err.stack) {
- msg += "\n" + err.stack;
+ if (typedErr.message) {
+ msg += ":\n" + typedErr.message;
+ if (typedErr.stack) {
+ msg += "\n" + typedErr.stack;
}
}
- this.logger.msg(msg, server.Msg.Err);
+ this.projectService.log(msg);
+ };
+ Session.prototype.sendLineToClient = function (line) {
+ this.host.write(line + this.host.newLine);
};
Session.prototype.send = function (msg) {
- if (msg.type === "event" && !this.canUseEvents) {
- if (this.logger.hasLevel(server.LogLevel.verbose)) {
- this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg));
- }
- return;
+ var json = JSON.stringify(msg);
+ if (this.logger.isVerbose()) {
+ this.logger.info(msg.type + ": " + json);
}
- this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine));
+ this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) +
+ "\r\n\r\n" + json);
};
Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) {
var bakedDiags = ts.map(diagnostics, formatConfigFileDiag);
@@ -63259,7 +60559,7 @@ var ts;
};
this.send(ev);
};
- Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) {
+ Session.prototype.response = function (info, cmdName, reqSeq, errorMsg) {
if (reqSeq === void 0) { reqSeq = 0; }
var res = {
seq: 0,
@@ -63276,9 +60576,13 @@ var ts;
}
this.send(res);
};
+ Session.prototype.output = function (body, commandName, requestSequence, errorMessage) {
+ if (requestSequence === void 0) { requestSequence = 0; }
+ this.response(body, commandName, requestSequence, errorMessage);
+ };
Session.prototype.semanticCheck = function (file, project) {
try {
- var diags = project.getLanguageService().getSemanticDiagnostics(file);
+ var diags = project.compilerService.languageService.getSemanticDiagnostics(file);
if (diags) {
var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); });
this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag");
@@ -63290,7 +60594,7 @@ var ts;
};
Session.prototype.syntacticCheck = function (file, project) {
try {
- var diags = project.getLanguageService().getSyntacticDiagnostics(file);
+ var diags = project.compilerService.languageService.getSyntacticDiagnostics(file);
if (diags) {
var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); });
this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag");
@@ -63300,12 +60604,15 @@ var ts;
this.logError(err, "syntactic check");
}
};
+ Session.prototype.reloadProjects = function () {
+ this.projectService.reloadProjects();
+ };
Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) {
var _this = this;
if (ms === void 0) { ms = 1500; }
- this.host.setTimeout(function () {
+ setTimeout(function () {
if (matchSeq(seq)) {
- _this.projectService.refreshInferredProjects();
+ _this.projectService.updateProjectStructure();
}
}, ms);
};
@@ -63318,10 +60625,10 @@ var ts;
followMs = ms;
}
if (this.errorTimer) {
- this.host.clearTimeout(this.errorTimer);
+ clearTimeout(this.errorTimer);
}
if (this.immediateId) {
- this.host.clearImmediate(this.immediateId);
+ clearImmediate(this.immediateId);
this.immediateId = undefined;
}
var index = 0;
@@ -63329,13 +60636,13 @@ var ts;
if (matchSeq(seq)) {
var checkSpec_1 = checkList[index];
index++;
- if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) {
+ if (checkSpec_1.project.getSourceFileFromName(checkSpec_1.fileName, requireOpen)) {
_this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project);
- _this.immediateId = _this.host.setImmediate(function () {
+ _this.immediateId = setImmediate(function () {
_this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project);
_this.immediateId = undefined;
if (checkList.length > index) {
- _this.errorTimer = _this.host.setTimeout(checkOne, followMs);
+ _this.errorTimer = setTimeout(checkOne, followMs);
}
else {
_this.errorTimer = undefined;
@@ -63345,111 +60652,78 @@ var ts;
}
};
if ((checkList.length > index) && (matchSeq(seq))) {
- this.errorTimer = this.host.setTimeout(checkOne, ms);
+ this.errorTimer = setTimeout(checkOne, ms);
}
};
- Session.prototype.cleanProjects = function (caption, projects) {
- if (!projects) {
- return;
+ Session.prototype.getDefinition = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
}
- this.logger.info("cleaning " + caption);
- for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) {
- var p = projects_4[_i];
- p.getLanguageService(false).cleanupSemanticCache();
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var definitions = compilerService.languageService.getDefinitionAtPosition(file, position);
+ if (!definitions) {
+ return undefined;
}
- };
- Session.prototype.cleanup = function () {
- this.cleanProjects("inferred projects", this.projectService.inferredProjects);
- this.cleanProjects("configured projects", this.projectService.configuredProjects);
- this.cleanProjects("external projects", this.projectService.externalProjects);
- if (this.host.gc) {
- this.logger.info("host.gc()");
- this.host.gc();
- }
- };
- Session.prototype.getEncodedSemanticClassifications = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- return project.getLanguageService().getEncodedSemanticClassifications(file, args);
- };
- Session.prototype.getProject = function (projectFileName) {
- return projectFileName && this.projectService.findProject(projectFileName);
- };
- Session.prototype.getCompilerOptionsDiagnostics = function (args) {
- var project = this.getProject(args.projectFileName);
- return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined);
- };
- Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) {
- var _this = this;
- return diagnostics.map(function (d) { return ({
- message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine),
- start: d.start,
- length: d.length,
- category: ts.DiagnosticCategory[d.category].toLowerCase(),
- code: d.code,
- startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start),
- endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length)
+ return definitions.map(function (def) { return ({
+ file: def.fileName,
+ start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start),
+ end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan))
}); });
};
- Session.prototype.getDiagnosticsWorker = function (args, selector, includeLinePosition) {
- var _a = this.getFileAndProject(args), project = _a.project, file = _a.file;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var diagnostics = selector(project, file);
- return includeLinePosition
- ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo)
- : diagnostics.map(function (d) { return formatDiag(file, project, d); });
- };
- Session.prototype.getDefinition = function (args, simplifiedResult) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var definitions = project.getLanguageService().getDefinitionAtPosition(file, position);
+ Session.prototype.getTypeDefinition = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position);
if (!definitions) {
return undefined;
}
- if (simplifiedResult) {
- return definitions.map(function (def) {
- var defScriptInfo = project.getScriptInfo(def.fileName);
- return {
- file: def.fileName,
- start: defScriptInfo.positionToLineOffset(def.textSpan.start),
- end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan))
- };
- });
- }
- else {
- return definitions;
- }
+ return definitions.map(function (def) { return ({
+ file: def.fileName,
+ start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start),
+ end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan))
+ }); });
};
- Session.prototype.getTypeDefinition = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position);
- if (!definitions) {
+ Session.prototype.getImplementation = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var implementations = compilerService.languageService.getImplementationAtPosition(file, compilerService.host.lineOffsetToPosition(file, line, offset));
+ if (!implementations) {
return undefined;
}
- return definitions.map(function (def) {
- var defScriptInfo = project.getScriptInfo(def.fileName);
- return {
- file: def.fileName,
- start: defScriptInfo.positionToLineOffset(def.textSpan.start),
- end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan))
- };
- });
+ return implementations.map(function (impl) { return ({
+ file: impl.fileName,
+ start: compilerService.host.positionToLineOffset(impl.fileName, impl.textSpan.start),
+ end: compilerService.host.positionToLineOffset(impl.fileName, ts.textSpanEnd(impl.textSpan))
+ }); });
};
- Session.prototype.getOccurrences = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position);
+ Session.prototype.getOccurrences = function (line, offset, fileName) {
+ fileName = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(fileName);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(fileName, line, offset);
+ var occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position);
if (!occurrences) {
return undefined;
}
return occurrences.map(function (occurrence) {
var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan;
- var scriptInfo = project.getScriptInfo(fileName);
- var start = scriptInfo.positionToLineOffset(textSpan.start);
- var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan));
+ var start = compilerService.host.positionToLineOffset(fileName, textSpan.start);
+ var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan));
return {
start: start,
end: end,
@@ -63458,142 +60732,115 @@ var ts;
};
});
};
+ Session.prototype.getDiagnosticsWorker = function (args, selector) {
+ var file = ts.normalizePath(args.file);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project) {
+ throw Errors.NoProject;
+ }
+ if (project.languageServiceDiabled) {
+ throw Errors.ProjectLanguageServiceDisabled;
+ }
+ var diagnostics = selector(project, file);
+ return ts.map(diagnostics, function (originalDiagnostic) { return formatDiag(file, project, originalDiagnostic); });
+ };
Session.prototype.getSyntacticDiagnosticsSync = function (args) {
- return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition);
+ return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSyntacticDiagnostics(file); });
};
Session.prototype.getSemanticDiagnosticsSync = function (args) {
- return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition);
+ return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSemanticDiagnostics(file); });
};
- Session.prototype.getDocumentHighlights = function (args, simplifiedResult) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch);
+ Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) {
+ fileName = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(fileName);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(fileName, line, offset);
+ var documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch);
if (!documentHighlights) {
return undefined;
}
- if (simplifiedResult) {
- return documentHighlights.map(convertToDocumentHighlightsItem);
- }
- else {
- return documentHighlights;
- }
+ return documentHighlights.map(convertToDocumentHighlightsItem);
function convertToDocumentHighlightsItem(documentHighlights) {
var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans;
- var scriptInfo = project.getScriptInfo(fileName);
return {
file: fileName,
highlightSpans: highlightSpans.map(convertHighlightSpan)
};
function convertHighlightSpan(highlightSpan) {
var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind;
- var start = scriptInfo.positionToLineOffset(textSpan.start);
- var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan));
+ var start = compilerService.host.positionToLineOffset(fileName, textSpan.start);
+ var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan));
return { start: start, end: end, kind: kind };
}
}
};
- Session.prototype.setCompilerOptionsForInferredProjects = function (args) {
- this.projectService.setCompilerOptionsForInferredProjects(args.options);
- };
- Session.prototype.getProjectInfo = function (args) {
- return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList);
- };
- Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) {
- var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project;
+ Session.prototype.getProjectInfo = function (fileName, needFileNameList) {
+ fileName = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(fileName);
+ if (!project) {
+ throw Errors.NoProject;
+ }
var projectInfo = {
- configFileName: project.getProjectName(),
- languageServiceDisabled: !project.languageServiceEnabled,
- fileNames: needFileNameList ? project.getFileNames() : undefined
+ configFileName: project.projectFilename,
+ languageServiceDisabled: project.languageServiceDiabled
};
+ if (needFileNameList) {
+ projectInfo.fileNames = project.getFileNames();
+ }
return projectInfo;
};
- Session.prototype.getRenameInfo = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- return project.getLanguageService().getRenameInfo(file, position);
- };
- Session.prototype.getProjects = function (args) {
- var projects;
- if (args.projectFileName) {
- var project = this.getProject(args.projectFileName);
- if (project) {
- projects = [project];
- }
+ Session.prototype.getRenameLocations = function (line, offset, fileName, findInComments, findInStrings) {
+ var file = ts.normalizePath(fileName);
+ var info = this.projectService.getScriptInfo(file);
+ var projects = this.projectService.findReferencingProjects(info);
+ var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; });
+ if (projectsWithLanguageServiceEnabeld.length === 0) {
+ throw Errors.NoProject;
}
- else {
- var scriptInfo = this.projectService.getScriptInfo(args.file);
- projects = scriptInfo.containingProjects;
+ var defaultProject = projectsWithLanguageServiceEnabeld[0];
+ var defaultProjectCompilerService = defaultProject.compilerService;
+ var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset);
+ var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position);
+ if (!renameInfo) {
+ return undefined;
}
- projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; });
- if (!projects || !projects.length) {
- return server.Errors.ThrowNoProject();
+ if (!renameInfo.canRename) {
+ return {
+ info: renameInfo,
+ locs: []
+ };
}
- return projects;
- };
- Session.prototype.getRenameLocations = function (args, simplifiedResult) {
- var file = server.toNormalizedPath(args.file);
- var info = this.projectService.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, info);
- var projects = this.getProjects(args);
- if (simplifiedResult) {
- var defaultProject = projects[0];
- var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position);
- if (!renameInfo) {
- return undefined;
+ var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) {
+ var compilerService = project.compilerService;
+ var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments);
+ if (!renameLocations) {
+ return [];
}
- if (!renameInfo.canRename) {
- return {
- info: renameInfo,
- locs: []
- };
- }
- var fileSpans = server.combineProjectOutput(projects, function (project) {
- var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments);
- if (!renameLocations) {
- return [];
+ return renameLocations.map(function (location) { return ({
+ file: location.fileName,
+ start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start),
+ end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan))
+ }); });
+ }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; });
+ var locs = fileSpans.reduce(function (accum, cur) {
+ var curFileAccum;
+ if (accum.length > 0) {
+ curFileAccum = accum[accum.length - 1];
+ if (curFileAccum.file !== cur.file) {
+ curFileAccum = undefined;
}
- return renameLocations.map(function (location) {
- var locationScriptInfo = project.getScriptInfo(location.fileName);
- return {
- file: location.fileName,
- start: locationScriptInfo.positionToLineOffset(location.textSpan.start),
- end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan))
- };
- });
- }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; });
- var locs = fileSpans.reduce(function (accum, cur) {
- var curFileAccum;
- if (accum.length > 0) {
- curFileAccum = accum[accum.length - 1];
- if (curFileAccum.file !== cur.file) {
- curFileAccum = undefined;
- }
- }
- if (!curFileAccum) {
- curFileAccum = { file: cur.file, locs: [] };
- accum.push(curFileAccum);
- }
- curFileAccum.locs.push({ start: cur.start, end: cur.end });
- return accum;
- }, []);
- return { info: renameInfo, locs: locs };
- }
- else {
- return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo);
- }
- function renameLocationIsEqualTo(a, b) {
- if (a === b) {
- return true;
}
- if (!a || !b) {
- return false;
+ if (!curFileAccum) {
+ curFileAccum = { file: cur.file, locs: [] };
+ accum.push(curFileAccum);
}
- return a.fileName === b.fileName &&
- a.textSpan.start === b.textSpan.start &&
- a.textSpan.length === b.textSpan.length;
- }
+ curFileAccum.locs.push({ start: cur.start, end: cur.end });
+ return accum;
+ }, []);
+ return { info: renameInfo, locs: locs };
function compareRenameLocation(a, b) {
if (a.file < b.file) {
return -1;
@@ -63614,51 +60861,51 @@ var ts;
}
}
};
- Session.prototype.getReferences = function (args, simplifiedResult) {
- var file = server.toNormalizedPath(args.file);
- var projects = this.getProjects(args);
- var defaultProject = projects[0];
- var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- if (simplifiedResult) {
- var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position);
- if (!nameInfo) {
- return undefined;
+ Session.prototype.getReferences = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var info = this.projectService.getScriptInfo(file);
+ var projects = this.projectService.findReferencingProjects(info);
+ var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; });
+ if (projectsWithLanguageServiceEnabeld.length === 0) {
+ throw Errors.NoProject;
+ }
+ var defaultProject = projectsWithLanguageServiceEnabeld[0];
+ var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset);
+ var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position);
+ if (!nameInfo) {
+ return undefined;
+ }
+ var displayString = ts.displayPartsToString(nameInfo.displayParts);
+ var nameSpan = nameInfo.textSpan;
+ var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset;
+ var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan));
+ var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) {
+ var compilerService = project.compilerService;
+ var references = compilerService.languageService.getReferencesAtPosition(file, position);
+ if (!references) {
+ return [];
}
- var displayString = ts.displayPartsToString(nameInfo.displayParts);
- var nameSpan = nameInfo.textSpan;
- var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset;
- var nameText = scriptInfo.snap().getText(nameSpan.start, ts.textSpanEnd(nameSpan));
- var refs = server.combineProjectOutput(projects, function (project) {
- var references = project.getLanguageService().getReferencesAtPosition(file, position);
- if (!references) {
- return [];
- }
- return references.map(function (ref) {
- var refScriptInfo = project.getScriptInfo(ref.fileName);
- var start = refScriptInfo.positionToLineOffset(ref.textSpan.start);
- var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1);
- var lineText = refScriptInfo.snap().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, "");
- return {
- file: ref.fileName,
- start: start,
- lineText: lineText,
- end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)),
- isWriteAccess: ref.isWriteAccess,
- isDefinition: ref.isDefinition
- };
- });
- }, compareFileStart, areReferencesResponseItemsForTheSameLocation);
- return {
- refs: refs,
- symbolName: nameText,
- symbolStartOffset: nameColStart,
- symbolDisplayString: displayString
- };
- }
- else {
- return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined);
- }
+ return references.map(function (ref) {
+ var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start);
+ var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1);
+ var snap = compilerService.host.getScriptSnapshot(ref.fileName);
+ var lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, "");
+ return {
+ file: ref.fileName,
+ start: start,
+ lineText: lineText,
+ end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)),
+ isWriteAccess: ref.isWriteAccess,
+ isDefinition: ref.isDefinition
+ };
+ });
+ }, compareFileStart, areReferencesResponseItemsForTheSameLocation);
+ return {
+ refs: refs,
+ symbolName: nameText,
+ symbolStartOffset: nameColStart,
+ symbolDisplayString: displayString
+ };
function areReferencesResponseItemsForTheSameLocation(a, b) {
if (a && b) {
return a.file === b.file &&
@@ -63669,152 +60916,102 @@ var ts;
}
};
Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) {
- var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors;
+ var file = ts.normalizePath(fileName);
+ var _a = this.projectService.openClientFile(file, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors;
if (configFileErrors) {
this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors);
}
};
- Session.prototype.getPosition = function (args, scriptInfo) {
- return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset);
- };
- Session.prototype.getFileAndProject = function (args, errorOnMissingProject) {
- if (errorOnMissingProject === void 0) { errorOnMissingProject = true; }
- return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject);
- };
- Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) {
- if (errorOnMissingProject === void 0) { errorOnMissingProject = true; }
- return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject);
- };
- Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) {
- var file = server.toNormalizedPath(uncheckedFileName);
- var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects);
- if (!project && errorOnMissingProject) {
- return server.Errors.ThrowNoProject();
+ Session.prototype.getQuickInfo = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
}
- return { file: file, project: project };
- };
- Session.prototype.getOutliningSpans = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- return project.getLanguageService(false).getOutliningSpans(file);
- };
- Session.prototype.getTodoComments = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- return project.getLanguageService().getTodoComments(file, args.descriptors);
- };
- Session.prototype.getDocCommentTemplate = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position);
- };
- Session.prototype.getIndentation = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file));
- var options = args.options || this.projectService.getFormatCodeOptions(file);
- var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options);
- return { position: position, indentation: indentation };
- };
- Session.prototype.getBreakpointStatement = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file));
- return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position);
- };
- Session.prototype.getNameOrDottedNameSpan = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file));
- return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position);
- };
- Session.prototype.isValidBraceCompletion = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file));
- return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0));
- };
- Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo));
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position);
if (!quickInfo) {
return undefined;
}
- if (simplifiedResult) {
- var displayString = ts.displayPartsToString(quickInfo.displayParts);
- var docString = ts.displayPartsToString(quickInfo.documentation);
- return {
- kind: quickInfo.kind,
- kindModifiers: quickInfo.kindModifiers,
- start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start),
- end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)),
- displayString: displayString,
- documentation: docString
- };
- }
- else {
- return quickInfo;
- }
+ var displayString = ts.displayPartsToString(quickInfo.displayParts);
+ var docString = ts.displayPartsToString(quickInfo.documentation);
+ return {
+ kind: quickInfo.kind,
+ kindModifiers: quickInfo.kindModifiers,
+ start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start),
+ end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)),
+ displayString: displayString,
+ documentation: docString
+ };
};
- Session.prototype.getFormattingEditsForRange = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset);
- var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
- var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file));
+ Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var startPosition = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset);
+ var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file));
if (!edits) {
return undefined;
}
return edits.map(function (edit) {
return {
- start: scriptInfo.positionToLineOffset(edit.span.start),
- end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)),
+ start: compilerService.host.positionToLineOffset(file, edit.span.start),
+ end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)),
newText: edit.newText ? edit.newText : ""
};
});
};
- Session.prototype.getFormattingEditsForRangeFull = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var options = args.options || this.projectService.getFormatCodeOptions(file);
- return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options);
- };
- Session.prototype.getFormattingEditsForDocumentFull = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var options = args.options || this.projectService.getFormatCodeOptions(file);
- return project.getLanguageService(false).getFormattingEditsForDocument(file, options);
- };
- Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var options = args.options || this.projectService.getFormatCodeOptions(file);
- return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options);
- };
- Session.prototype.getFormattingEditsAfterKeystroke = function (args) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = scriptInfo.lineOffsetToPosition(args.line, args.offset);
+ Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
var formatOptions = this.projectService.getFormatCodeOptions(file);
- var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions);
- if ((args.key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) {
- var lineInfo = scriptInfo.getLineInfo(args.line);
- if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) {
- var lineText = lineInfo.leaf.text;
- if (lineText.search("\\S") < 0) {
- var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions);
- var hasIndent = 0;
- var i = void 0, len = void 0;
- for (i = 0, len = lineText.length; i < len; i++) {
- if (lineText.charAt(i) == " ") {
- hasIndent++;
+ var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions);
+ if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) {
+ var scriptInfo = compilerService.host.getScriptInfo(file);
+ if (scriptInfo) {
+ var lineInfo = scriptInfo.getLineInfo(line);
+ if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) {
+ var lineText = lineInfo.leaf.text;
+ if (lineText.search("\\S") < 0) {
+ var editorOptions = {
+ BaseIndentSize: formatOptions.BaseIndentSize,
+ IndentSize: formatOptions.IndentSize,
+ TabSize: formatOptions.TabSize,
+ NewLineCharacter: formatOptions.NewLineCharacter,
+ ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces,
+ IndentStyle: ts.IndentStyle.Smart
+ };
+ var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions);
+ var hasIndent = 0;
+ var i = void 0, len = void 0;
+ for (i = 0, len = lineText.length; i < len; i++) {
+ if (lineText.charAt(i) == " ") {
+ hasIndent++;
+ }
+ else if (lineText.charAt(i) == "\t") {
+ hasIndent += editorOptions.TabSize;
+ }
+ else {
+ break;
+ }
}
- else if (lineText.charAt(i) == "\t") {
- hasIndent += formatOptions.tabSize;
+ if (preferredIndent !== hasIndent) {
+ var firstNoWhiteSpacePosition = lineInfo.offset + i;
+ edits.push({
+ span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition),
+ newText: generateIndentString(preferredIndent, editorOptions)
+ });
}
- else {
- break;
- }
- }
- if (preferredIndent !== hasIndent) {
- var firstNoWhiteSpacePosition = lineInfo.offset + i;
- edits.push({
- span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition),
- newText: ts.formatting.getIndentationString(preferredIndent, formatOptions)
- });
}
}
}
@@ -63824,111 +61021,89 @@ var ts;
}
return edits.map(function (edit) {
return {
- start: scriptInfo.positionToLineOffset(edit.span.start),
- end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)),
+ start: compilerService.host.positionToLineOffset(file, edit.span.start),
+ end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)),
newText: edit.newText ? edit.newText : ""
};
});
};
- Session.prototype.getCompletions = function (args, simplifiedResult) {
- var prefix = args.prefix || "";
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var completions = project.getLanguageService().getCompletionsAtPosition(file, position);
+ Session.prototype.getCompletions = function (line, offset, prefix, fileName) {
+ if (!prefix) {
+ prefix = "";
+ }
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var completions = compilerService.languageService.getCompletionsAtPosition(file, position);
if (!completions) {
return undefined;
}
- if (simplifiedResult) {
- return completions.entries.reduce(function (result, entry) {
- if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) {
- var name_53 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan;
- var convertedSpan = undefined;
- if (replacementSpan) {
- convertedSpan = {
- start: scriptInfo.positionToLineOffset(replacementSpan.start),
- end: scriptInfo.positionToLineOffset(replacementSpan.start + replacementSpan.length)
- };
- }
- result.push({ name: name_53, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan });
+ return completions.entries.reduce(function (result, entry) {
+ if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) {
+ var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan;
+ var convertedSpan = undefined;
+ if (replacementSpan) {
+ convertedSpan = {
+ start: compilerService.host.positionToLineOffset(fileName, replacementSpan.start),
+ end: compilerService.host.positionToLineOffset(fileName, replacementSpan.start + replacementSpan.length)
+ };
}
- return result;
- }, []).sort(function (a, b) { return a.name.localeCompare(b.name); });
- }
- else {
- return completions;
- }
+ result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan });
+ }
+ return result;
+ }, []).sort(function (a, b) { return a.name.localeCompare(b.name); });
};
- Session.prototype.getCompletionEntryDetails = function (args) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- return args.entryNames.reduce(function (accum, entryName) {
- var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName);
+ Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ return entryNames.reduce(function (accum, entryName) {
+ var details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName);
if (details) {
accum.push(details);
}
return accum;
}, []);
};
- Session.prototype.getCompileOnSaveAffectedFileList = function (args) {
- var info = this.projectService.getScriptInfo(args.file);
- var result = [];
- if (!info) {
- return [];
+ Session.prototype.getSignatureHelpItems = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
}
- var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects;
- for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) {
- var project = projectsToSearch_1[_i];
- if (project.compileOnSaveEnabled && project.languageServiceEnabled) {
- result.push({
- projectFileName: project.getProjectName(),
- fileNames: project.getCompileOnSaveAffectedFileList(info)
- });
- }
- }
- return result;
- };
- Session.prototype.emitFile = function (args) {
- var _this = this;
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- if (!project) {
- server.Errors.ThrowNoProject();
- }
- var scriptInfo = project.getScriptInfo(file);
- return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); });
- };
- Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var helpItems = project.getLanguageService().getSignatureHelpItems(file, position);
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var helpItems = compilerService.languageService.getSignatureHelpItems(file, position);
if (!helpItems) {
return undefined;
}
- if (simplifiedResult) {
- var span_16 = helpItems.applicableSpan;
- return {
- items: helpItems.items,
- applicableSpan: {
- start: scriptInfo.positionToLineOffset(span_16.start),
- end: scriptInfo.positionToLineOffset(span_16.start + span_16.length)
- },
- selectedItemIndex: helpItems.selectedItemIndex,
- argumentIndex: helpItems.argumentIndex,
- argumentCount: helpItems.argumentCount
- };
- }
- else {
- return helpItems;
- }
+ var span = helpItems.applicableSpan;
+ var result = {
+ items: helpItems.items,
+ applicableSpan: {
+ start: compilerService.host.positionToLineOffset(file, span.start),
+ end: compilerService.host.positionToLineOffset(file, span.start + span.length)
+ },
+ selectedItemIndex: helpItems.selectedItemIndex,
+ argumentIndex: helpItems.argumentIndex,
+ argumentCount: helpItems.argumentCount
+ };
+ return result;
};
Session.prototype.getDiagnostics = function (delay, fileNames) {
var _this = this;
- var checkList = fileNames.reduce(function (accum, uncheckedFileName) {
- var fileName = server.toNormalizedPath(uncheckedFileName);
- var project = _this.projectService.getDefaultProjectForFile(fileName, true);
- if (project) {
+ var checkList = fileNames.reduce(function (accum, fileName) {
+ fileName = ts.normalizePath(fileName);
+ var project = _this.projectService.getProjectForFile(fileName);
+ if (project && !project.languageServiceDiabled) {
accum.push({ fileName: fileName, project: project });
}
return accum;
@@ -63937,34 +61112,40 @@ var ts;
this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay);
}
};
- Session.prototype.change = function (args) {
+ Session.prototype.change = function (line, offset, endLine, endOffset, insertString, fileName) {
var _this = this;
- var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project;
- if (project) {
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var start = scriptInfo.lineOffsetToPosition(args.line, args.offset);
- var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (project && !project.languageServiceDiabled) {
+ var compilerService = project.compilerService;
+ var start = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset);
if (start >= 0) {
- scriptInfo.editContent(start, end, args.insertString);
+ compilerService.host.editScript(file, start, end, insertString);
this.changeSeq++;
}
this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; });
}
};
- Session.prototype.reload = function (args, reqSeq) {
- var file = server.toNormalizedPath(args.file);
- var project = this.projectService.getDefaultProjectForFile(file, true);
- if (project) {
+ Session.prototype.reload = function (fileName, tempFileName, reqSeq) {
+ var _this = this;
+ if (reqSeq === void 0) { reqSeq = 0; }
+ var file = ts.normalizePath(fileName);
+ var tmpfile = ts.normalizePath(tempFileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (project && !project.languageServiceDiabled) {
this.changeSeq++;
- if (project.reloadScript(file)) {
- this.output(undefined, CommandNames.Reload, reqSeq);
- }
+ project.compilerService.host.reloadScript(file, tmpfile, function () {
+ _this.output(undefined, CommandNames.Reload, reqSeq);
+ });
}
};
Session.prototype.saveToTmp = function (fileName, tempFileName) {
- var scriptInfo = this.projectService.getScriptInfo(fileName);
- if (scriptInfo) {
- scriptInfo.saveTo(tempFileName);
+ var file = ts.normalizePath(fileName);
+ var tmpfile = ts.normalizePath(tempFileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (project && !project.languageServiceDiabled) {
+ project.compilerService.host.saveTo(file, tmpfile);
}
};
Session.prototype.closeClientFile = function (fileName) {
@@ -63974,91 +61155,77 @@ var ts;
var file = ts.normalizePath(fileName);
this.projectService.closeClientFile(file);
};
- Session.prototype.decorateNavigationBarItem = function (project, fileName, items) {
+ Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) {
var _this = this;
if (!items) {
return undefined;
}
- var scriptInfo = project.getScriptInfoForNormalizedPath(fileName);
+ var compilerService = project.compilerService;
return items.map(function (item) { return ({
text: item.text,
kind: item.kind,
kindModifiers: item.kindModifiers,
spans: item.spans.map(function (span) { return ({
- start: scriptInfo.positionToLineOffset(span.start),
- end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span))
+ start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex),
+ end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex)
}); }),
- childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems),
+ childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex),
indent: item.indent
}); });
};
- Session.prototype.getNavigationBarItems = function (args, simplifiedResult) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var items = project.getLanguageService().getNavigationBarItems(file);
+ Session.prototype.getNavigationBarItems = function (fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var items = compilerService.languageService.getNavigationBarItems(file);
if (!items) {
return undefined;
}
- return simplifiedResult
- ? this.decorateNavigationBarItem(project, file, items)
- : items;
+ return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName));
};
- Session.prototype.getNavigateToItems = function (args, simplifiedResult) {
- var projects = this.getProjects(args);
- var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined;
- if (simplifiedResult) {
- return server.combineProjectOutput(projects, function (project) {
- var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isJsOnlyProject());
- if (!navItems) {
- return [];
+ Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount, currentFileOnly) {
+ var file = ts.normalizePath(fileName);
+ var info = this.projectService.getScriptInfo(file);
+ var projects = this.projectService.findReferencingProjects(info);
+ var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; });
+ if (projectsWithLanguageServiceEnabeld.length === 0) {
+ throw Errors.NoProject;
+ }
+ var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) {
+ var compilerService = project.compilerService;
+ var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount, currentFileOnly ? fileName : undefined);
+ if (!navItems) {
+ return [];
+ }
+ return navItems.map(function (navItem) {
+ var start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start);
+ var end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan));
+ var bakedItem = {
+ name: navItem.name,
+ kind: navItem.kind,
+ file: navItem.fileName,
+ start: start,
+ end: end
+ };
+ if (navItem.kindModifiers && (navItem.kindModifiers !== "")) {
+ bakedItem.kindModifiers = navItem.kindModifiers;
}
- return navItems.map(function (navItem) {
- var scriptInfo = project.getScriptInfo(navItem.fileName);
- var start = scriptInfo.positionToLineOffset(navItem.textSpan.start);
- var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan));
- var bakedItem = {
- name: navItem.name,
- kind: navItem.kind,
- file: navItem.fileName,
- start: start,
- end: end
- };
- if (navItem.kindModifiers && (navItem.kindModifiers !== "")) {
- bakedItem.kindModifiers = navItem.kindModifiers;
- }
- if (navItem.matchKind !== "none") {
- bakedItem.matchKind = navItem.matchKind;
- }
- if (navItem.containerName && (navItem.containerName.length > 0)) {
- bakedItem.containerName = navItem.containerName;
- }
- if (navItem.containerKind && (navItem.containerKind.length > 0)) {
- bakedItem.containerKind = navItem.containerKind;
- }
- return bakedItem;
- });
- }, undefined, areNavToItemsForTheSameLocation);
- }
- else {
- return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isJsOnlyProject()); }, undefined, navigateToItemIsEqualTo);
- }
- function navigateToItemIsEqualTo(a, b) {
- if (a === b) {
- return true;
- }
- if (!a || !b) {
- return false;
- }
- return a.containerKind === b.containerKind &&
- a.containerName === b.containerName &&
- a.fileName === b.fileName &&
- a.isCaseSensitive === b.isCaseSensitive &&
- a.kind === b.kind &&
- a.kindModifiers === b.containerName &&
- a.matchKind === b.matchKind &&
- a.name === b.name &&
- a.textSpan.start === b.textSpan.start &&
- a.textSpan.length === b.textSpan.length;
- }
+ if (navItem.matchKind !== "none") {
+ bakedItem.matchKind = navItem.matchKind;
+ }
+ if (navItem.containerName && (navItem.containerName.length > 0)) {
+ bakedItem.containerName = navItem.containerName;
+ }
+ if (navItem.containerKind && (navItem.containerKind.length > 0)) {
+ bakedItem.containerKind = navItem.containerKind;
+ }
+ return bakedItem;
+ });
+ }, undefined, areNavToItemsForTheSameLocation);
+ return allNavToItems;
function areNavToItemsForTheSameLocation(a, b) {
if (a && b) {
return a.file === b.file &&
@@ -64068,27 +61235,26 @@ var ts;
return false;
}
};
- Session.prototype.getBraceMatching = function (args, simplifiedResult) {
- var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project;
- var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var position = this.getPosition(args, scriptInfo);
- var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position);
+ Session.prototype.getBraceMatching = function (line, offset, fileName) {
+ var file = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(file);
+ if (!project || project.languageServiceDiabled) {
+ throw Errors.NoProject;
+ }
+ var compilerService = project.compilerService;
+ var position = compilerService.host.lineOffsetToPosition(file, line, offset);
+ var spans = compilerService.languageService.getBraceMatchingAtPosition(file, position);
if (!spans) {
return undefined;
}
- if (simplifiedResult) {
- return spans.map(function (span) { return ({
- start: scriptInfo.positionToLineOffset(span.start),
- end: scriptInfo.positionToLineOffset(span.start + span.length)
- }); });
- }
- else {
- return spans;
- }
+ return spans.map(function (span) { return ({
+ start: compilerService.host.positionToLineOffset(file, span.start),
+ end: compilerService.host.positionToLineOffset(file, span.start + span.length)
+ }); });
};
Session.prototype.getDiagnosticsForProject = function (delay, fileName) {
var _this = this;
- var _a = this.getProjectInfoWorker(fileName, undefined, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled;
+ var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled;
if (languageServiceDisabled) {
return;
}
@@ -64097,8 +61263,8 @@ var ts;
var mediumPriorityFiles = [];
var lowPriorityFiles = [];
var veryLowPriorityFiles = [];
- var normalizedFileName = server.toNormalizedPath(fileName);
- var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true);
+ var normalizedFileName = ts.normalizePath(fileName);
+ var project = this.projectService.getProjectForFile(normalizedFileName);
for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) {
var fileNameInProject = fileNamesInProject_1[_i];
if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName))
@@ -64117,7 +61283,10 @@ var ts;
}
fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles);
if (fileNamesInProject.length > 0) {
- var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); });
+ var checkList = fileNamesInProject.map(function (fileName) {
+ var normalizedFileName = ts.normalizePath(fileName);
+ return { fileName: normalizedFileName, project: project };
+ });
this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n == _this.changeSeq; }, delay, 200, false);
}
};
@@ -64127,9 +61296,6 @@ var ts;
};
Session.prototype.exit = function () {
};
- Session.prototype.notRequired = function () {
- return { responseRequired: false };
- };
Session.prototype.requiredResponse = function (response) {
return { response: response, responseRequired: true };
};
@@ -64145,32 +61311,31 @@ var ts;
return handler(request);
}
else {
- this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err);
+ this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request));
this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command);
return { responseRequired: false };
}
};
Session.prototype.onMessage = function (message) {
- this.gcTimer.scheduleCollect();
var start;
- if (this.logger.hasLevel(server.LogLevel.requestTime)) {
+ if (this.logger.isVerbose()) {
+ this.logger.info("request: " + message);
start = this.hrtime();
- if (this.logger.hasLevel(server.LogLevel.verbose)) {
- this.logger.info("request: " + message);
- }
}
var request;
try {
request = JSON.parse(message);
var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired;
- if (this.logger.hasLevel(server.LogLevel.requestTime)) {
- var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4);
- if (responseRequired) {
- this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime);
- }
- else {
- this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime);
+ if (this.logger.isVerbose()) {
+ var elapsed = this.hrtime(start);
+ var seconds = elapsed[0];
+ var nanoseconds = elapsed[1];
+ var elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0;
+ var leader = "Elapsed time (in milliseconds)";
+ if (!responseRequired) {
+ leader = "Async elapsed time (in milliseconds)";
}
+ this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf");
}
if (response) {
this.output(response, request.command, request.seq);
@@ -64181,8 +61346,6 @@ var ts;
}
catch (err) {
if (err instanceof ts.OperationCanceledException) {
- this.output({ canceled: true }, request.command, request.seq);
- return;
}
this.logError(err, message);
this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack);
@@ -64198,6 +61361,1229 @@ var ts;
var server;
(function (server) {
var lineCollectionCapacity = 4;
+ function mergeFormatOptions(formatCodeOptions, formatOptions) {
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
+ Object.keys(formatOptions).forEach(function (key) {
+ var codeKey = key.charAt(0).toUpperCase() + key.substring(1);
+ if (hasOwnProperty.call(formatCodeOptions, codeKey)) {
+ formatCodeOptions[codeKey] = formatOptions[key];
+ }
+ });
+ }
+ server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
+ var ScriptInfo = (function () {
+ function ScriptInfo(host, fileName, content, isOpen) {
+ if (isOpen === void 0) { isOpen = false; }
+ this.host = host;
+ this.fileName = fileName;
+ this.isOpen = isOpen;
+ this.children = [];
+ this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host));
+ this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
+ this.svc = ScriptVersionCache.fromString(host, content);
+ }
+ ScriptInfo.prototype.setFormatOptions = function (formatOptions) {
+ if (formatOptions) {
+ mergeFormatOptions(this.formatCodeOptions, formatOptions);
+ }
+ };
+ ScriptInfo.prototype.close = function () {
+ this.isOpen = false;
+ };
+ ScriptInfo.prototype.addChild = function (childInfo) {
+ this.children.push(childInfo);
+ };
+ ScriptInfo.prototype.snap = function () {
+ return this.svc.getSnapshot();
+ };
+ ScriptInfo.prototype.getText = function () {
+ var snap = this.snap();
+ return snap.getText(0, snap.getLength());
+ };
+ ScriptInfo.prototype.getLineInfo = function (line) {
+ var snap = this.snap();
+ return snap.index.lineNumberToInfo(line);
+ };
+ ScriptInfo.prototype.editContent = function (start, end, newText) {
+ this.svc.edit(start, end - start, newText);
+ };
+ ScriptInfo.prototype.getTextChangeRangeBetweenVersions = function (startVersion, endVersion) {
+ return this.svc.getTextChangesBetweenVersions(startVersion, endVersion);
+ };
+ ScriptInfo.prototype.getChangeRange = function (oldSnapshot) {
+ return this.snap().getChangeRange(oldSnapshot);
+ };
+ return ScriptInfo;
+ }());
+ server.ScriptInfo = ScriptInfo;
+ var LSHost = (function () {
+ function LSHost(host, project) {
+ var _this = this;
+ this.host = host;
+ this.project = project;
+ this.roots = [];
+ this.getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
+ this.resolvedModuleNames = ts.createFileMap();
+ this.resolvedTypeReferenceDirectives = ts.createFileMap();
+ this.filenameToScript = ts.createFileMap();
+ this.moduleResolutionHost = {
+ fileExists: function (fileName) { return _this.fileExists(fileName); },
+ readFile: function (fileName) { return _this.host.readFile(fileName); },
+ directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); }
+ };
+ if (this.host.realpath) {
+ this.moduleResolutionHost.realpath = function (path) { return _this.host.realpath(path); };
+ }
+ }
+ LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) {
+ var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName);
+ var currentResolutionsInFile = cache.get(path);
+ var newResolutions = ts.createMap();
+ var resolvedModules = [];
+ var compilerOptions = this.getCompilationSettings();
+ for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
+ var name_53 = names_3[_i];
+ var resolution = newResolutions[name_53];
+ if (!resolution) {
+ var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_53];
+ if (moduleResolutionIsValid(existingResolution)) {
+ resolution = existingResolution;
+ }
+ else {
+ resolution = loader(name_53, containingFile, compilerOptions, this.moduleResolutionHost);
+ resolution.lastCheckTime = Date.now();
+ newResolutions[name_53] = resolution;
+ }
+ }
+ ts.Debug.assert(resolution !== undefined);
+ resolvedModules.push(getResult(resolution));
+ }
+ cache.set(path, newResolutions);
+ return resolvedModules;
+ function moduleResolutionIsValid(resolution) {
+ if (!resolution) {
+ return false;
+ }
+ if (getResult(resolution)) {
+ return true;
+ }
+ return resolution.failedLookupLocations.length === 0;
+ }
+ };
+ LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
+ return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; });
+ };
+ LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) {
+ return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, ts.resolveModuleName, function (m) { return m.resolvedModule; });
+ };
+ LSHost.prototype.getDefaultLibFileName = function () {
+ var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath()));
+ return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings));
+ };
+ LSHost.prototype.getScriptSnapshot = function (filename) {
+ var scriptInfo = this.getScriptInfo(filename);
+ if (scriptInfo) {
+ return scriptInfo.snap();
+ }
+ };
+ LSHost.prototype.setCompilationSettings = function (opt) {
+ this.compilationSettings = opt;
+ this.resolvedModuleNames.clear();
+ this.resolvedTypeReferenceDirectives.clear();
+ };
+ LSHost.prototype.lineAffectsRefs = function (filename, line) {
+ var info = this.getScriptInfo(filename);
+ var lineInfo = info.getLineInfo(line);
+ if (lineInfo && lineInfo.text) {
+ var regex = /reference|import|\/\*|\*\//;
+ return regex.test(lineInfo.text);
+ }
+ };
+ LSHost.prototype.getCompilationSettings = function () {
+ return this.compilationSettings;
+ };
+ LSHost.prototype.getScriptFileNames = function () {
+ return this.roots.map(function (root) { return root.fileName; });
+ };
+ LSHost.prototype.getScriptKind = function (fileName) {
+ var info = this.getScriptInfo(fileName);
+ if (!info) {
+ return undefined;
+ }
+ if (!info.scriptKind) {
+ info.scriptKind = ts.getScriptKindFromFileName(fileName);
+ }
+ return info.scriptKind;
+ };
+ LSHost.prototype.getScriptVersion = function (filename) {
+ return this.getScriptInfo(filename).svc.latestVersion().toString();
+ };
+ LSHost.prototype.getCurrentDirectory = function () {
+ return "";
+ };
+ LSHost.prototype.getScriptIsOpen = function (filename) {
+ return this.getScriptInfo(filename).isOpen;
+ };
+ LSHost.prototype.removeReferencedFile = function (info) {
+ if (!info.isOpen) {
+ this.filenameToScript.remove(info.path);
+ this.resolvedModuleNames.remove(info.path);
+ this.resolvedTypeReferenceDirectives.remove(info.path);
+ }
+ };
+ LSHost.prototype.getScriptInfo = function (filename) {
+ var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
+ var scriptInfo = this.filenameToScript.get(path);
+ if (!scriptInfo) {
+ scriptInfo = this.project.openReferencedFile(filename);
+ if (scriptInfo) {
+ this.filenameToScript.set(path, scriptInfo);
+ }
+ }
+ return scriptInfo;
+ };
+ LSHost.prototype.addRoot = function (info) {
+ if (!this.filenameToScript.contains(info.path)) {
+ this.filenameToScript.set(info.path, info);
+ this.roots.push(info);
+ }
+ };
+ LSHost.prototype.removeRoot = function (info) {
+ if (this.filenameToScript.contains(info.path)) {
+ this.filenameToScript.remove(info.path);
+ ts.unorderedRemoveItem(this.roots, info);
+ this.resolvedModuleNames.remove(info.path);
+ this.resolvedTypeReferenceDirectives.remove(info.path);
+ }
+ };
+ LSHost.prototype.saveTo = function (filename, tmpfilename) {
+ var script = this.getScriptInfo(filename);
+ if (script) {
+ var snap = script.snap();
+ this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength()));
+ }
+ };
+ LSHost.prototype.reloadScript = function (filename, tmpfilename, cb) {
+ var script = this.getScriptInfo(filename);
+ if (script) {
+ script.svc.reloadFromFile(tmpfilename, cb);
+ }
+ };
+ LSHost.prototype.editScript = function (filename, start, end, newText) {
+ var script = this.getScriptInfo(filename);
+ if (script) {
+ script.editContent(start, end, newText);
+ return;
+ }
+ throw new Error("No script with name '" + filename + "'");
+ };
+ LSHost.prototype.fileExists = function (path) {
+ var result = this.host.fileExists(path);
+ return result;
+ };
+ LSHost.prototype.directoryExists = function (path) {
+ return this.host.directoryExists(path);
+ };
+ LSHost.prototype.getDirectories = function (path) {
+ return this.host.getDirectories(path);
+ };
+ LSHost.prototype.readDirectory = function (path, extensions, exclude, include) {
+ return this.host.readDirectory(path, extensions, exclude, include);
+ };
+ LSHost.prototype.readFile = function (path, encoding) {
+ return this.host.readFile(path, encoding);
+ };
+ LSHost.prototype.lineToTextSpan = function (filename, line) {
+ var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
+ var script = this.filenameToScript.get(path);
+ var index = script.snap().index;
+ var lineInfo = index.lineNumberToInfo(line + 1);
+ var len;
+ if (lineInfo.leaf) {
+ len = lineInfo.leaf.text.length;
+ }
+ else {
+ var nextLineInfo = index.lineNumberToInfo(line + 2);
+ len = nextLineInfo.offset - lineInfo.offset;
+ }
+ return ts.createTextSpan(lineInfo.offset, len);
+ };
+ LSHost.prototype.lineOffsetToPosition = function (filename, line, offset) {
+ var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
+ var script = this.filenameToScript.get(path);
+ var index = script.snap().index;
+ var lineInfo = index.lineNumberToInfo(line);
+ return (lineInfo.offset + offset - 1);
+ };
+ LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) {
+ lineIndex = lineIndex || this.getLineIndex(filename);
+ var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position);
+ return { line: lineOffset.line, offset: lineOffset.offset + 1 };
+ };
+ LSHost.prototype.getLineIndex = function (filename) {
+ var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
+ var script = this.filenameToScript.get(path);
+ return script.snap().index;
+ };
+ return LSHost;
+ }());
+ server.LSHost = LSHost;
+ var Project = (function () {
+ function Project(projectService, projectOptions, languageServiceDiabled) {
+ if (languageServiceDiabled === void 0) { languageServiceDiabled = false; }
+ this.projectService = projectService;
+ this.projectOptions = projectOptions;
+ this.languageServiceDiabled = languageServiceDiabled;
+ this.directoriesWatchedForTsconfig = [];
+ this.filenameToSourceFile = ts.createMap();
+ this.updateGraphSeq = 0;
+ this.openRefCount = 0;
+ if (projectOptions && projectOptions.files) {
+ projectOptions.compilerOptions.allowNonTsExtensions = true;
+ }
+ if (!languageServiceDiabled) {
+ this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions);
+ }
+ }
+ Project.prototype.enableLanguageService = function () {
+ if (this.languageServiceDiabled) {
+ this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions);
+ }
+ this.languageServiceDiabled = false;
+ };
+ Project.prototype.disableLanguageService = function () {
+ this.languageServiceDiabled = true;
+ };
+ Project.prototype.addOpenRef = function () {
+ this.openRefCount++;
+ };
+ Project.prototype.deleteOpenRef = function () {
+ this.openRefCount--;
+ return this.openRefCount;
+ };
+ Project.prototype.openReferencedFile = function (filename) {
+ return this.projectService.openFile(filename, false);
+ };
+ Project.prototype.getRootFiles = function () {
+ if (this.languageServiceDiabled) {
+ return this.projectOptions ? this.projectOptions.files : undefined;
+ }
+ return this.compilerService.host.roots.map(function (info) { return info.fileName; });
+ };
+ Project.prototype.getFileNames = function () {
+ if (this.languageServiceDiabled) {
+ if (!this.projectOptions) {
+ return undefined;
+ }
+ var fileNames = [];
+ if (this.projectOptions && this.projectOptions.compilerOptions) {
+ fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions));
+ }
+ ts.addRange(fileNames, this.projectOptions.files);
+ return fileNames;
+ }
+ var sourceFiles = this.program.getSourceFiles();
+ return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; });
+ };
+ Project.prototype.getSourceFile = function (info) {
+ if (this.languageServiceDiabled) {
+ return undefined;
+ }
+ return this.filenameToSourceFile[info.fileName];
+ };
+ Project.prototype.getSourceFileFromName = function (filename, requireOpen) {
+ if (this.languageServiceDiabled) {
+ return undefined;
+ }
+ var info = this.projectService.getScriptInfo(filename);
+ if (info) {
+ if ((!requireOpen) || info.isOpen) {
+ return this.getSourceFile(info);
+ }
+ }
+ };
+ Project.prototype.isRoot = function (info) {
+ if (this.languageServiceDiabled) {
+ return undefined;
+ }
+ return this.compilerService.host.roots.some(function (root) { return root === info; });
+ };
+ Project.prototype.removeReferencedFile = function (info) {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.compilerService.host.removeReferencedFile(info);
+ this.updateGraph();
+ };
+ Project.prototype.updateFileMap = function () {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.filenameToSourceFile = ts.createMap();
+ var sourceFiles = this.program.getSourceFiles();
+ for (var i = 0, len = sourceFiles.length; i < len; i++) {
+ var normFilename = ts.normalizePath(sourceFiles[i].fileName);
+ this.filenameToSourceFile[normFilename] = sourceFiles[i];
+ }
+ };
+ Project.prototype.finishGraph = function () {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.updateGraph();
+ this.compilerService.languageService.getNavigateToItems(".*");
+ };
+ Project.prototype.updateGraph = function () {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.program = this.compilerService.languageService.getProgram();
+ this.updateFileMap();
+ };
+ Project.prototype.isConfiguredProject = function () {
+ return this.projectFilename;
+ };
+ Project.prototype.addRoot = function (info) {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.compilerService.host.addRoot(info);
+ };
+ Project.prototype.removeRoot = function (info) {
+ if (this.languageServiceDiabled) {
+ return;
+ }
+ this.compilerService.host.removeRoot(info);
+ };
+ Project.prototype.filesToString = function () {
+ if (this.languageServiceDiabled) {
+ if (this.projectOptions) {
+ var strBuilder_1 = "";
+ ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; });
+ return strBuilder_1;
+ }
+ }
+ var strBuilder = "";
+ ts.forEachProperty(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; });
+ return strBuilder;
+ };
+ Project.prototype.setProjectOptions = function (projectOptions) {
+ this.projectOptions = projectOptions;
+ if (projectOptions.compilerOptions) {
+ projectOptions.compilerOptions.allowNonTsExtensions = true;
+ if (!this.languageServiceDiabled) {
+ this.compilerService.setCompilerOptions(projectOptions.compilerOptions);
+ }
+ }
+ };
+ return Project;
+ }());
+ server.Project = Project;
+ function combineProjectOutput(projects, action, comparer, areEqual) {
+ var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer);
+ return projects.length > 1 ? ts.deduplicate(result, areEqual) : result;
+ }
+ server.combineProjectOutput = combineProjectOutput;
+ var ProjectService = (function () {
+ function ProjectService(host, psLogger, eventHandler) {
+ this.host = host;
+ this.psLogger = psLogger;
+ this.eventHandler = eventHandler;
+ this.filenameToScriptInfo = ts.createMap();
+ this.openFileRoots = [];
+ this.inferredProjects = [];
+ this.configuredProjects = [];
+ this.openFilesReferenced = [];
+ this.openFileRootsConfigured = [];
+ this.directoryWatchersForTsconfig = ts.createMap();
+ this.directoryWatchersRefCount = ts.createMap();
+ this.timerForDetectingProjectFileListChanges = ts.createMap();
+ this.addDefaultHostConfiguration();
+ }
+ ProjectService.prototype.addDefaultHostConfiguration = function () {
+ this.hostConfiguration = {
+ formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)),
+ hostInfo: "Unknown host"
+ };
+ };
+ ProjectService.prototype.getFormatCodeOptions = function (file) {
+ if (file) {
+ var info = this.filenameToScriptInfo[file];
+ if (info) {
+ return info.formatCodeOptions;
+ }
+ }
+ return this.hostConfiguration.formatCodeOptions;
+ };
+ ProjectService.prototype.watchedFileChanged = function (fileName) {
+ var info = this.filenameToScriptInfo[fileName];
+ if (!info) {
+ this.psLogger.info("Error: got watch notification for unknown file: " + fileName);
+ }
+ if (!this.host.fileExists(fileName)) {
+ this.fileDeletedInFilesystem(info);
+ }
+ else {
+ if (info && (!info.isOpen)) {
+ info.svc.reloadFromFile(info.fileName);
+ }
+ }
+ };
+ ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) {
+ if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) {
+ return;
+ }
+ this.log("Detected source file changes: " + fileName);
+ this.startTimerForDetectingProjectFileListChanges(project);
+ };
+ ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) {
+ var _this = this;
+ if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) {
+ this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]);
+ }
+ this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250);
+ };
+ ProjectService.prototype.handleProjectFileListChanges = function (project) {
+ var _this = this;
+ var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors;
+ this.reportConfigFileDiagnostics(project.projectFilename, errors);
+ var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); }));
+ var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); }));
+ if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) {
+ this.updateConfiguredProject(project);
+ this.updateProjectStructure();
+ }
+ };
+ ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) {
+ if (diagnostics && diagnostics.length > 0) {
+ this.eventHandler({
+ eventName: "configFileDiag",
+ data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile }
+ });
+ }
+ };
+ ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) {
+ var _this = this;
+ if (ts.getBaseFileName(fileName) !== "tsconfig.json") {
+ this.log(fileName + " is not tsconfig.json");
+ return;
+ }
+ this.log("Detected newly added tsconfig file: " + fileName);
+ var _a = this.configFileToProjectOptions(fileName), projectOptions = _a.projectOptions, errors = _a.errors;
+ this.reportConfigFileDiagnostics(fileName, errors);
+ if (!projectOptions) {
+ return;
+ }
+ var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); });
+ var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); });
+ for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) {
+ var openFileRoot = openFileRoots_1[_i];
+ if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) {
+ this.reloadProjects();
+ return;
+ }
+ }
+ };
+ ProjectService.prototype.getCanonicalFileName = function (fileName) {
+ var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
+ return ts.normalizePath(name);
+ };
+ ProjectService.prototype.watchedProjectConfigFileChanged = function (project) {
+ this.log("Config file changed: " + project.projectFilename);
+ var configFileErrors = this.updateConfiguredProject(project);
+ this.updateProjectStructure();
+ if (configFileErrors && configFileErrors.length > 0) {
+ this.eventHandler({ eventName: "configFileDiag", data: { triggerFile: project.projectFilename, configFileName: project.projectFilename, diagnostics: configFileErrors } });
+ }
+ };
+ ProjectService.prototype.log = function (msg, type) {
+ if (type === void 0) { type = "Err"; }
+ this.psLogger.msg(msg, type);
+ };
+ ProjectService.prototype.setHostConfiguration = function (args) {
+ if (args.file) {
+ var info = this.filenameToScriptInfo[args.file];
+ if (info) {
+ info.setFormatOptions(args.formatOptions);
+ this.log("Host configuration update for file " + args.file, "Info");
+ }
+ }
+ else {
+ if (args.hostInfo !== undefined) {
+ this.hostConfiguration.hostInfo = args.hostInfo;
+ this.log("Host information " + args.hostInfo, "Info");
+ }
+ if (args.formatOptions) {
+ mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions);
+ this.log("Format host information updated", "Info");
+ }
+ }
+ };
+ ProjectService.prototype.closeLog = function () {
+ this.psLogger.close();
+ };
+ ProjectService.prototype.createInferredProject = function (root) {
+ var _this = this;
+ var project = new Project(this);
+ project.addRoot(root);
+ var currentPath = ts.getDirectoryPath(root.fileName);
+ var parentPath = ts.getDirectoryPath(currentPath);
+ while (currentPath != parentPath) {
+ if (!project.projectService.directoryWatchersForTsconfig[currentPath]) {
+ this.log("Add watcher for: " + currentPath);
+ project.projectService.directoryWatchersForTsconfig[currentPath] =
+ this.host.watchDirectory(currentPath, function (fileName) { return _this.directoryWatchedForTsconfigChanged(fileName); });
+ project.projectService.directoryWatchersRefCount[currentPath] = 1;
+ }
+ else {
+ project.projectService.directoryWatchersRefCount[currentPath] += 1;
+ }
+ project.directoriesWatchedForTsconfig.push(currentPath);
+ currentPath = parentPath;
+ parentPath = ts.getDirectoryPath(parentPath);
+ }
+ project.finishGraph();
+ this.inferredProjects.push(project);
+ return project;
+ };
+ ProjectService.prototype.fileDeletedInFilesystem = function (info) {
+ this.psLogger.info(info.fileName + " deleted");
+ if (info.fileWatcher) {
+ info.fileWatcher.close();
+ info.fileWatcher = undefined;
+ }
+ if (!info.isOpen) {
+ this.filenameToScriptInfo[info.fileName] = undefined;
+ var referencingProjects = this.findReferencingProjects(info);
+ if (info.defaultProject) {
+ info.defaultProject.removeRoot(info);
+ }
+ for (var i = 0, len = referencingProjects.length; i < len; i++) {
+ referencingProjects[i].removeReferencedFile(info);
+ }
+ for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) {
+ var openFile = this.openFileRoots[j];
+ if (this.eventHandler) {
+ this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } });
+ }
+ }
+ for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) {
+ var openFile = this.openFilesReferenced[j];
+ if (this.eventHandler) {
+ this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } });
+ }
+ }
+ }
+ this.printProjects();
+ };
+ ProjectService.prototype.updateConfiguredProjectList = function () {
+ var configuredProjects = [];
+ for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
+ if (this.configuredProjects[i].openRefCount > 0) {
+ configuredProjects.push(this.configuredProjects[i]);
+ }
+ }
+ this.configuredProjects = configuredProjects;
+ };
+ ProjectService.prototype.removeProject = function (project) {
+ this.log("remove project: " + project.getRootFiles().toString());
+ if (project.isConfiguredProject()) {
+ project.projectFileWatcher.close();
+ project.directoryWatcher.close();
+ ts.forEachProperty(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); });
+ delete project.directoriesWatchedForWildcards;
+ ts.unorderedRemoveItem(this.configuredProjects, project);
+ }
+ else {
+ for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) {
+ var directory = _a[_i];
+ project.projectService.directoryWatchersRefCount[directory]--;
+ if (!project.projectService.directoryWatchersRefCount[directory]) {
+ this.log("Close directory watcher for: " + directory);
+ project.projectService.directoryWatchersForTsconfig[directory].close();
+ delete project.projectService.directoryWatchersForTsconfig[directory];
+ }
+ }
+ ts.unorderedRemoveItem(this.inferredProjects, project);
+ }
+ var fileNames = project.getFileNames();
+ for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) {
+ var fileName = fileNames_3[_b];
+ var info = this.getScriptInfo(fileName);
+ if (info.defaultProject == project) {
+ info.defaultProject = undefined;
+ }
+ }
+ };
+ ProjectService.prototype.setConfiguredProjectRoot = function (info) {
+ for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
+ var configuredProject = this.configuredProjects[i];
+ if (configuredProject.isRoot(info)) {
+ info.defaultProject = configuredProject;
+ configuredProject.addOpenRef();
+ return true;
+ }
+ }
+ return false;
+ };
+ ProjectService.prototype.addOpenFile = function (info) {
+ if (this.setConfiguredProjectRoot(info)) {
+ this.openFileRootsConfigured.push(info);
+ }
+ else {
+ this.findReferencingProjects(info);
+ if (info.defaultProject) {
+ info.defaultProject.addOpenRef();
+ this.openFilesReferenced.push(info);
+ }
+ else {
+ info.defaultProject = this.createInferredProject(info);
+ var openFileRoots = [];
+ for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
+ var r = this.openFileRoots[i];
+ if (info.defaultProject.getSourceFile(r)) {
+ this.removeProject(r.defaultProject);
+ this.openFilesReferenced.push(r);
+ r.defaultProject = info.defaultProject;
+ }
+ else {
+ openFileRoots.push(r);
+ }
+ }
+ this.openFileRoots = openFileRoots;
+ this.openFileRoots.push(info);
+ }
+ }
+ this.updateConfiguredProjectList();
+ };
+ ProjectService.prototype.closeOpenFile = function (info) {
+ info.svc.reloadFromFile(info.fileName);
+ var openFileRoots = [];
+ var removedProject;
+ for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
+ if (info === this.openFileRoots[i]) {
+ removedProject = info.defaultProject;
+ }
+ else {
+ openFileRoots.push(this.openFileRoots[i]);
+ }
+ }
+ this.openFileRoots = openFileRoots;
+ if (!removedProject) {
+ var openFileRootsConfigured = [];
+ for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) {
+ if (info === this.openFileRootsConfigured[i]) {
+ if (info.defaultProject.deleteOpenRef() === 0) {
+ removedProject = info.defaultProject;
+ }
+ }
+ else {
+ openFileRootsConfigured.push(this.openFileRootsConfigured[i]);
+ }
+ }
+ this.openFileRootsConfigured = openFileRootsConfigured;
+ }
+ if (removedProject) {
+ this.removeProject(removedProject);
+ var openFilesReferenced = [];
+ var orphanFiles = [];
+ for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) {
+ var f = this.openFilesReferenced[i];
+ if (f.defaultProject === removedProject || !f.defaultProject) {
+ f.defaultProject = undefined;
+ orphanFiles.push(f);
+ }
+ else {
+ openFilesReferenced.push(f);
+ }
+ }
+ this.openFilesReferenced = openFilesReferenced;
+ for (var i = 0, len = orphanFiles.length; i < len; i++) {
+ this.addOpenFile(orphanFiles[i]);
+ }
+ }
+ else {
+ ts.unorderedRemoveItem(this.openFilesReferenced, info);
+ }
+ info.close();
+ };
+ ProjectService.prototype.findReferencingProjects = function (info, excludedProject) {
+ var referencingProjects = [];
+ info.defaultProject = undefined;
+ for (var i = 0, len = this.inferredProjects.length; i < len; i++) {
+ var inferredProject = this.inferredProjects[i];
+ inferredProject.updateGraph();
+ if (inferredProject !== excludedProject) {
+ if (inferredProject.getSourceFile(info)) {
+ info.defaultProject = inferredProject;
+ referencingProjects.push(inferredProject);
+ }
+ }
+ }
+ for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
+ var configuredProject = this.configuredProjects[i];
+ configuredProject.updateGraph();
+ if (configuredProject.getSourceFile(info)) {
+ info.defaultProject = configuredProject;
+ referencingProjects.push(configuredProject);
+ }
+ }
+ return referencingProjects;
+ };
+ ProjectService.prototype.reloadProjects = function () {
+ this.log("reload projects.");
+ for (var _i = 0, _a = this.openFileRoots; _i < _a.length; _i++) {
+ var info = _a[_i];
+ this.openOrUpdateConfiguredProjectForFile(info.fileName);
+ }
+ this.updateProjectStructure();
+ };
+ ProjectService.prototype.updateProjectStructure = function () {
+ this.log("updating project structure from ...", "Info");
+ this.printProjects();
+ var unattachedOpenFiles = [];
+ var openFileRootsConfigured = [];
+ for (var _i = 0, _a = this.openFileRootsConfigured; _i < _a.length; _i++) {
+ var info = _a[_i];
+ var project = info.defaultProject;
+ if (!project || !(project.getSourceFile(info))) {
+ info.defaultProject = undefined;
+ unattachedOpenFiles.push(info);
+ }
+ else {
+ openFileRootsConfigured.push(info);
+ }
+ }
+ this.openFileRootsConfigured = openFileRootsConfigured;
+ var openFilesReferenced = [];
+ for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) {
+ var referencedFile = this.openFilesReferenced[i];
+ referencedFile.defaultProject.updateGraph();
+ var sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile);
+ if (sourceFile) {
+ openFilesReferenced.push(referencedFile);
+ }
+ else {
+ unattachedOpenFiles.push(referencedFile);
+ }
+ }
+ this.openFilesReferenced = openFilesReferenced;
+ var openFileRoots = [];
+ for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
+ var rootFile = this.openFileRoots[i];
+ var rootedProject = rootFile.defaultProject;
+ var referencingProjects = this.findReferencingProjects(rootFile, rootedProject);
+ if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) {
+ if (!rootedProject.isConfiguredProject()) {
+ this.removeProject(rootedProject);
+ }
+ this.openFileRootsConfigured.push(rootFile);
+ }
+ else {
+ if (referencingProjects.length === 0) {
+ rootFile.defaultProject = rootedProject;
+ openFileRoots.push(rootFile);
+ }
+ else {
+ this.removeProject(rootedProject);
+ this.openFilesReferenced.push(rootFile);
+ }
+ }
+ }
+ this.openFileRoots = openFileRoots;
+ for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) {
+ this.addOpenFile(unattachedOpenFiles[i]);
+ }
+ this.printProjects();
+ };
+ ProjectService.prototype.getScriptInfo = function (filename) {
+ filename = ts.normalizePath(filename);
+ return this.filenameToScriptInfo[filename];
+ };
+ ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) {
+ var _this = this;
+ fileName = ts.normalizePath(fileName);
+ var info = this.filenameToScriptInfo[fileName];
+ if (!info) {
+ var content = void 0;
+ if (this.host.fileExists(fileName)) {
+ content = fileContent || this.host.readFile(fileName);
+ }
+ if (!content) {
+ if (openedByClient) {
+ content = "";
+ }
+ }
+ if (content !== undefined) {
+ info = new ScriptInfo(this.host, fileName, content, openedByClient);
+ info.scriptKind = scriptKind;
+ info.setFormatOptions(this.getFormatCodeOptions());
+ this.filenameToScriptInfo[fileName] = info;
+ if (!info.isOpen) {
+ info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); });
+ }
+ }
+ }
+ if (info) {
+ if (fileContent) {
+ info.svc.reload(fileContent);
+ }
+ if (openedByClient) {
+ info.isOpen = true;
+ }
+ }
+ return info;
+ };
+ ProjectService.prototype.findConfigFile = function (searchPath) {
+ while (true) {
+ var tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json");
+ if (this.host.fileExists(tsconfigFileName)) {
+ return tsconfigFileName;
+ }
+ var jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json");
+ if (this.host.fileExists(jsconfigFileName)) {
+ return jsconfigFileName;
+ }
+ var parentPath = ts.getDirectoryPath(searchPath);
+ if (parentPath === searchPath) {
+ break;
+ }
+ searchPath = parentPath;
+ }
+ return undefined;
+ };
+ ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) {
+ var _a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors;
+ var info = this.openFile(fileName, true, fileContent, scriptKind);
+ this.addOpenFile(info);
+ this.printProjects();
+ return { configFileName: configFileName, configFileErrors: configFileErrors };
+ };
+ ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) {
+ var searchPath = ts.normalizePath(ts.getDirectoryPath(fileName));
+ this.log("Search path: " + searchPath, "Info");
+ var configFileName = this.findConfigFile(searchPath);
+ if (configFileName) {
+ this.log("Config file name: " + configFileName, "Info");
+ var project = this.findConfiguredProjectByConfigFile(configFileName);
+ if (!project) {
+ var configResult = this.openConfigFile(configFileName, fileName);
+ if (!configResult.project) {
+ return { configFileName: configFileName, configFileErrors: configResult.errors };
+ }
+ else {
+ this.log("Opened configuration file " + configFileName, "Info");
+ this.configuredProjects.push(configResult.project);
+ if (configResult.errors && configResult.errors.length > 0) {
+ return { configFileName: configFileName, configFileErrors: configResult.errors };
+ }
+ }
+ }
+ else {
+ this.updateConfiguredProject(project);
+ }
+ return { configFileName: configFileName };
+ }
+ else {
+ this.log("No config files found.");
+ }
+ return {};
+ };
+ ProjectService.prototype.closeClientFile = function (filename) {
+ var info = this.filenameToScriptInfo[filename];
+ if (info) {
+ this.closeOpenFile(info);
+ info.isOpen = false;
+ }
+ this.printProjects();
+ };
+ ProjectService.prototype.getProjectForFile = function (filename) {
+ var scriptInfo = this.filenameToScriptInfo[filename];
+ if (scriptInfo) {
+ return scriptInfo.defaultProject;
+ }
+ };
+ ProjectService.prototype.printProjectsForFile = function (filename) {
+ var scriptInfo = this.filenameToScriptInfo[filename];
+ if (scriptInfo) {
+ this.psLogger.startGroup();
+ this.psLogger.info("Projects for " + filename);
+ var projects = this.findReferencingProjects(scriptInfo);
+ for (var i = 0, len = projects.length; i < len; i++) {
+ this.psLogger.info("Project " + i.toString());
+ }
+ this.psLogger.endGroup();
+ }
+ else {
+ this.psLogger.info(filename + " not in any project");
+ }
+ };
+ ProjectService.prototype.printProjects = function () {
+ if (!this.psLogger.isVerbose()) {
+ return;
+ }
+ this.psLogger.startGroup();
+ for (var i = 0, len = this.inferredProjects.length; i < len; i++) {
+ var project = this.inferredProjects[i];
+ project.updateGraph();
+ this.psLogger.info("Project " + i.toString());
+ this.psLogger.info(project.filesToString());
+ this.psLogger.info("-----------------------------------------------");
+ }
+ for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
+ var project = this.configuredProjects[i];
+ project.updateGraph();
+ this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString());
+ this.psLogger.info(project.filesToString());
+ this.psLogger.info("-----------------------------------------------");
+ }
+ this.psLogger.info("Open file roots of inferred projects: ");
+ for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
+ this.psLogger.info(this.openFileRoots[i].fileName);
+ }
+ this.psLogger.info("Open files referenced by inferred or configured projects: ");
+ for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) {
+ var fileInfo = this.openFilesReferenced[i].fileName;
+ if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) {
+ fileInfo += " (configured)";
+ }
+ this.psLogger.info(fileInfo);
+ }
+ this.psLogger.info("Open file roots of configured projects: ");
+ for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) {
+ this.psLogger.info(this.openFileRootsConfigured[i].fileName);
+ }
+ this.psLogger.endGroup();
+ };
+ ProjectService.prototype.configProjectIsActive = function (fileName) {
+ return this.findConfiguredProjectByConfigFile(fileName) === undefined;
+ };
+ ProjectService.prototype.findConfiguredProjectByConfigFile = function (configFileName) {
+ for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
+ if (this.configuredProjects[i].projectFilename == configFileName) {
+ return this.configuredProjects[i];
+ }
+ }
+ return undefined;
+ };
+ ProjectService.prototype.configFileToProjectOptions = function (configFilename) {
+ configFilename = ts.normalizePath(configFilename);
+ var errors = [];
+ var dirPath = ts.getDirectoryPath(configFilename);
+ var contents = this.host.readFile(configFilename);
+ var _a = ts.parseAndReEmitConfigJSONFile(contents), configJsonObject = _a.configJsonObject, diagnostics = _a.diagnostics;
+ errors = ts.concatenate(errors, diagnostics);
+ var parsedCommandLine = ts.parseJsonConfigFileContent(configJsonObject, this.host, dirPath, {}, configFilename);
+ errors = ts.concatenate(errors, parsedCommandLine.errors);
+ ts.Debug.assert(!!parsedCommandLine.fileNames);
+ if (parsedCommandLine.fileNames.length === 0) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename));
+ return { errors: errors };
+ }
+ else {
+ var projectOptions = {
+ files: parsedCommandLine.fileNames,
+ wildcardDirectories: parsedCommandLine.wildcardDirectories,
+ compilerOptions: parsedCommandLine.options
+ };
+ return { projectOptions: projectOptions, errors: errors };
+ }
+ };
+ ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) {
+ var totalNonTsFileSize = 0;
+ if (!this.host.getFileSize) {
+ return false;
+ }
+ for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) {
+ var fileName = fileNames_4[_i];
+ if (ts.hasTypeScriptFileExtension(fileName)) {
+ continue;
+ }
+ totalNonTsFileSize += this.host.getFileSize(fileName);
+ if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) {
+ return true;
+ }
+ }
+ return false;
+ };
+ ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) {
+ var _this = this;
+ var parseConfigFileResult = this.configFileToProjectOptions(configFilename);
+ var errors = parseConfigFileResult.errors;
+ if (!parseConfigFileResult.projectOptions) {
+ return { errors: errors };
+ }
+ var projectOptions = parseConfigFileResult.projectOptions;
+ if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) {
+ if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) {
+ var project_1 = this.createProject(configFilename, projectOptions, true);
+ project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); });
+ return { project: project_1, errors: errors };
+ }
+ }
+ var project = this.createProject(configFilename, projectOptions);
+ for (var _i = 0, _a = projectOptions.files; _i < _a.length; _i++) {
+ var rootFilename = _a[_i];
+ if (this.host.fileExists(rootFilename)) {
+ var info = this.openFile(rootFilename, clientFileName == rootFilename);
+ project.addRoot(info);
+ }
+ else {
+ (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename));
+ }
+ }
+ project.finishGraph();
+ project.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project); });
+ var configDirectoryPath = ts.getDirectoryPath(configFilename);
+ this.log("Add recursive watcher for: " + configDirectoryPath);
+ project.directoryWatcher = this.host.watchDirectory(configDirectoryPath, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true);
+ project.directoriesWatchedForWildcards = ts.reduceProperties(ts.createMap(projectOptions.wildcardDirectories), function (watchers, flag, directory) {
+ if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) {
+ var recursive = (flag & 1) !== 0;
+ _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory);
+ watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, recursive);
+ }
+ return watchers;
+ }, {});
+ return { project: project, errors: errors };
+ };
+ ProjectService.prototype.updateConfiguredProject = function (project) {
+ var _this = this;
+ if (!this.host.fileExists(project.projectFilename)) {
+ this.log("Config file deleted");
+ this.removeProject(project);
+ }
+ else {
+ var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors;
+ if (!projectOptions) {
+ return errors;
+ }
+ else {
+ if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) {
+ project.setProjectOptions(projectOptions);
+ if (project.languageServiceDiabled) {
+ return errors;
+ }
+ project.disableLanguageService();
+ if (project.directoryWatcher) {
+ project.directoryWatcher.close();
+ project.directoryWatcher = undefined;
+ }
+ return errors;
+ }
+ if (project.languageServiceDiabled) {
+ project.setProjectOptions(projectOptions);
+ project.enableLanguageService();
+ project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true);
+ for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) {
+ var rootFilename = _b[_i];
+ if (this.host.fileExists(rootFilename)) {
+ var info = this.openFile(rootFilename, false);
+ project.addRoot(info);
+ }
+ }
+ project.finishGraph();
+ return errors;
+ }
+ var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; });
+ var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); });
+ var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; });
+ var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; });
+ for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) {
+ var fileName = fileNamesToRemove_1[_c];
+ var info = this.getScriptInfo(fileName);
+ if (info) {
+ project.removeRoot(info);
+ }
+ }
+ for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) {
+ var fileName = fileNamesToAdd_1[_d];
+ var info = this.getScriptInfo(fileName);
+ if (!info) {
+ info = this.openFile(fileName, false);
+ }
+ else {
+ if (info.isOpen) {
+ if (this.openFileRoots.indexOf(info) >= 0) {
+ ts.unorderedRemoveItem(this.openFileRoots, info);
+ if (info.defaultProject && !info.defaultProject.isConfiguredProject()) {
+ this.removeProject(info.defaultProject);
+ }
+ }
+ if (this.openFilesReferenced.indexOf(info) >= 0) {
+ ts.unorderedRemoveItem(this.openFilesReferenced, info);
+ }
+ this.openFileRootsConfigured.push(info);
+ info.defaultProject = project;
+ }
+ }
+ project.addRoot(info);
+ }
+ project.setProjectOptions(projectOptions);
+ project.finishGraph();
+ }
+ return errors;
+ }
+ };
+ ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) {
+ var project = new Project(this, projectOptions, languageServiceDisabled);
+ project.projectFilename = projectFilename;
+ return project;
+ };
+ return ProjectService;
+ }());
+ server.ProjectService = ProjectService;
+ var CompilerService = (function () {
+ function CompilerService(project, opt) {
+ this.project = project;
+ this.documentRegistry = ts.createDocumentRegistry();
+ this.host = new LSHost(project.projectService.host, project);
+ if (opt) {
+ this.setCompilerOptions(opt);
+ }
+ else {
+ var defaultOpts = ts.getDefaultCompilerOptions();
+ defaultOpts.allowNonTsExtensions = true;
+ defaultOpts.allowJs = true;
+ this.setCompilerOptions(defaultOpts);
+ }
+ this.languageService = ts.createLanguageService(this.host, this.documentRegistry);
+ this.classifier = ts.createClassifier();
+ }
+ CompilerService.prototype.setCompilerOptions = function (opt) {
+ this.settings = opt;
+ this.host.setCompilationSettings(opt);
+ };
+ CompilerService.prototype.isExternalModule = function (filename) {
+ var sourceFile = this.languageService.getNonBoundSourceFile(filename);
+ return ts.isExternalModule(sourceFile);
+ };
+ CompilerService.getDefaultFormatCodeOptions = function (host) {
+ return ts.clone({
+ BaseIndentSize: 0,
+ IndentSize: 4,
+ TabSize: 4,
+ NewLineCharacter: host.newLine || "\n",
+ ConvertTabsToSpaces: true,
+ IndentStyle: ts.IndentStyle.Smart,
+ InsertSpaceAfterCommaDelimiter: true,
+ InsertSpaceAfterSemicolonInForStatements: true,
+ InsertSpaceBeforeAndAfterBinaryOperators: true,
+ InsertSpaceAfterKeywordsInControlFlowStatements: true,
+ InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
+ InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
+ InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
+ InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
+ InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
+ InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
+ InsertSpaceAfterTypeAssertion: false,
+ PlaceOpenBraceOnNewLineForFunctions: false,
+ PlaceOpenBraceOnNewLineForControlBlocks: false
+ });
+ };
+ return CompilerService;
+ }());
+ server.CompilerService = CompilerService;
(function (CharRangeSection) {
CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart";
CharRangeSection[CharRangeSection["Start"] = 1] = "Start";
@@ -64415,19 +62801,10 @@ var ts;
var ScriptVersionCache = (function () {
function ScriptVersionCache() {
this.changes = [];
- this.versions = new Array(ScriptVersionCache.maxVersions);
+ this.versions = [];
this.minVersion = 0;
this.currentVersion = 0;
}
- ScriptVersionCache.prototype.versionToIndex = function (version) {
- if (version < this.minVersion || version > this.currentVersion) {
- return undefined;
- }
- return version % ScriptVersionCache.maxVersions;
- };
- ScriptVersionCache.prototype.currentVersionToIndex = function () {
- return this.currentVersion % ScriptVersionCache.maxVersions;
- };
ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) {
this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText);
if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) ||
@@ -64437,7 +62814,7 @@ var ts;
}
};
ScriptVersionCache.prototype.latest = function () {
- return this.versions[this.currentVersionToIndex()];
+ return this.versions[this.currentVersion];
};
ScriptVersionCache.prototype.latestVersion = function () {
if (this.changes.length > 0) {
@@ -64445,30 +62822,32 @@ var ts;
}
return this.currentVersion;
};
- ScriptVersionCache.prototype.reloadFromFile = function (filename) {
+ ScriptVersionCache.prototype.reloadFromFile = function (filename, cb) {
var content = this.host.readFile(filename);
if (!content) {
content = "";
}
this.reload(content);
+ if (cb)
+ cb();
};
ScriptVersionCache.prototype.reload = function (script) {
this.currentVersion++;
this.changes = [];
var snap = new LineIndexSnapshot(this.currentVersion, this);
- for (var i = 0; i < this.versions.length; i++) {
- this.versions[i] = undefined;
- }
- this.versions[this.currentVersionToIndex()] = snap;
+ this.versions[this.currentVersion] = snap;
snap.index = new LineIndex();
var lm = LineIndex.linesFromText(script);
snap.index.load(lm.lines);
+ for (var i = this.minVersion; i < this.currentVersion; i++) {
+ this.versions[i] = undefined;
+ }
this.minVersion = this.currentVersion;
};
ScriptVersionCache.prototype.getSnapshot = function () {
- var snap = this.versions[this.currentVersionToIndex()];
+ var snap = this.versions[this.currentVersion];
if (this.changes.length > 0) {
- var snapIndex = snap.index;
+ var snapIndex = this.latest().index;
for (var i = 0, len = this.changes.length; i < len; i++) {
var change = this.changes[i];
snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText);
@@ -64477,10 +62856,14 @@ var ts;
snap.index = snapIndex;
snap.changesSincePreviousVersion = this.changes;
this.currentVersion = snap.version;
- this.versions[this.currentVersionToIndex()] = snap;
+ this.versions[snap.version] = snap;
this.changes = [];
if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) {
+ var oldMin = this.minVersion;
this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1;
+ for (var j = oldMin; j < this.minVersion; j++) {
+ this.versions[j] = undefined;
+ }
}
}
return snap;
@@ -64490,7 +62873,7 @@ var ts;
if (oldVersion >= this.minVersion) {
var textChangeRanges = [];
for (var i = oldVersion + 1; i <= newVersion; i++) {
- var snap = this.versions[this.versionToIndex(i)];
+ var snap = this.versions[i];
for (var j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) {
var textChange = snap.changesSincePreviousVersion[j];
textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange();
@@ -64628,7 +63011,7 @@ var ts;
done: false,
leaf: function (relativeStart, relativeLength, ll) {
if (!f(ll, relativeStart, relativeLength)) {
- this.done = true;
+ walkFns.done = true;
}
}
};
@@ -64641,7 +63024,7 @@ var ts;
return source.substring(0, s) + nt + source.substring(s + dl, source.length);
}
if (this.root.charCount() === 0) {
- if (newText !== undefined) {
+ if (newText) {
this.load(LineIndex.linesFromText(newText).lines);
return this;
}
@@ -65021,6 +63404,12 @@ var ts;
function LineLeaf(text) {
this.text = text;
}
+ LineLeaf.prototype.setUdata = function (data) {
+ this.udata = data;
+ };
+ LineLeaf.prototype.getUdata = function () {
+ return this.udata;
+ };
LineLeaf.prototype.isLeaf = function () {
return true;
};
@@ -65116,12 +63505,6 @@ var ts;
}
return this.shimHost.getProjectVersion();
};
- LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () {
- if (!this.shimHost.getTypeRootsVersion) {
- return 0;
- }
- return this.shimHost.getTypeRootsVersion();
- };
LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () {
return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
};
@@ -65721,4 +64104,4 @@ var TypeScript;
Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
})(Services = TypeScript.Services || (TypeScript.Services = {}));
})(TypeScript || (TypeScript = {}));
-var toolsVersion = "2.0";
+var toolsVersion = "2.1";
diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts
index 590b3bb2ac9..9116a629d6d 100644
--- a/lib/typescript.d.ts
+++ b/lib/typescript.d.ts
@@ -29,7 +29,6 @@ declare namespace ts {
contains(fileName: Path): boolean;
remove(fileName: Path): void;
forEachValue(f: (key: Path, v: T) => void): void;
- getKeys(): Path[];
clear(): void;
}
interface TextRange {
@@ -1246,7 +1245,7 @@ declare namespace ts {
* used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter
* will be invoked when writing the JavaScript and declaration files.
*/
- emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult;
+ emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult;
getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
@@ -1373,7 +1372,6 @@ declare namespace ts {
UseFullyQualifiedType = 128,
InFirstTypeArgument = 256,
InTypeAlias = 512,
- UseTypeAliasValue = 1024,
}
enum SymbolFormatFlags {
None = 0,
@@ -1744,7 +1742,6 @@ declare namespace ts {
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: MapLike;
- compileOnSave?: boolean;
}
enum WatchDirectoryFlags {
None = 0,
@@ -1947,6 +1944,10 @@ declare namespace ts {
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
+ /** The version of the TypeScript compiler release */
+ const version = "2.1.0";
+ function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string;
+ function resolveTripleslashReference(moduleName: string, containingFile: string): string;
function getEffectiveTypeRoots(options: CompilerOptions, host: {
directoryExists?: (directoryName: string) => boolean;
getCurrentDirectory?: () => string;
@@ -1957,24 +1958,9 @@ declare namespace ts {
* is assumed to be the same as root directory of the project.
*/
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
- /**
- * Given a set of options, returns the set of type directive names
- * that should be included for this program automatically.
- * This list could either come from the config file,
- * or from enumerating the types root + initial secondary types lookup location.
- * More type directives might appear in the program later as a result of loading actual source files;
- * this list is only the set of defaults that are implicitly included.
- */
- function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[];
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
-}
-declare namespace ts {
- /** The version of the TypeScript compiler release */
- const version = "2.0.5";
- function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string;
- function resolveTripleslashReference(moduleName: string, containingFile: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
interface FormatDiagnosticsHost {
@@ -1984,6 +1970,15 @@ declare namespace ts {
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
+ /**
+ * Given a set of options, returns the set of type directive names
+ * that should be included for this program automatically.
+ * This list could either come from the config file,
+ * or from enumerating the types root + initial secondary types lookup location.
+ * More type directives might appear in the program later as a result of loading actual source files;
+ * this list is only the set of defaults that are implicitly included.
+ */
+ function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[];
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
declare namespace ts {
@@ -2000,7 +1995,7 @@ declare namespace ts {
* @param fileName The path to the config file
* @param jsonText The text of the config file
*/
- function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): {
+ function parseConfigFileTextToJson(fileName: string, jsonText: string): {
config?: any;
error?: Diagnostic;
};
@@ -2012,13 +2007,12 @@ declare namespace ts {
* file to. e.g. outDir
*/
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine;
- function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
};
function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
- options: TypingOptions;
+ options: CompilerOptions;
errors: Diagnostic[];
};
}
@@ -2161,18 +2155,18 @@ declare namespace ts {
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[];
/** @deprecated */
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[];
- getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[];
+ getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[];
getNavigationBarItems(fileName: string): NavigationBarItem[];
getOutliningSpans(fileName: string): OutliningSpan[];
getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[];
getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[];
- getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number;
- getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[];
- getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[];
- getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[];
+ getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number;
+ getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[];
+ getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[];
+ getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[];
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
- getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput;
+ getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
dispose(): void;
}
@@ -2252,11 +2246,6 @@ declare namespace ts {
containerName: string;
containerKind: string;
}
- enum IndentStyle {
- None = 0,
- Block = 1,
- Smart = 2,
- }
interface EditorOptions {
BaseIndentSize?: number;
IndentSize: number;
@@ -2265,13 +2254,10 @@ declare namespace ts {
ConvertTabsToSpaces: boolean;
IndentStyle: IndentStyle;
}
- interface EditorSettings {
- baseIndentSize?: number;
- indentSize: number;
- tabSize: number;
- newLineCharacter: string;
- convertTabsToSpaces: boolean;
- indentStyle: IndentStyle;
+ enum IndentStyle {
+ None = 0,
+ Block = 1,
+ Smart = 2,
}
interface FormatCodeOptions extends EditorOptions {
InsertSpaceAfterCommaDelimiter: boolean;
@@ -2287,21 +2273,7 @@ declare namespace ts {
InsertSpaceAfterTypeAssertion?: boolean;
PlaceOpenBraceOnNewLineForFunctions: boolean;
PlaceOpenBraceOnNewLineForControlBlocks: boolean;
- }
- interface FormatCodeSettings extends EditorSettings {
- insertSpaceAfterCommaDelimiter: boolean;
- insertSpaceAfterSemicolonInForStatements: boolean;
- insertSpaceBeforeAndAfterBinaryOperators: boolean;
- insertSpaceAfterKeywordsInControlFlowStatements: boolean;
- insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean;
- insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean;
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean;
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean;
- insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean;
- insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: boolean;
- insertSpaceAfterTypeAssertion?: boolean;
- placeOpenBraceOnNewLineForFunctions: boolean;
- placeOpenBraceOnNewLineForControlBlocks: boolean;
+ [s: string]: boolean | number | string | undefined;
}
interface DefinitionInfo {
fileName: string;
@@ -2715,7 +2687,6 @@ declare namespace ts {
interface DisplayPartsSymbolWriter extends SymbolWriter {
displayParts(): SymbolDisplayPart[];
}
- function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings;
function displayPartsToString(displayParts: SymbolDisplayPart[]): string;
function getDefaultCompilerOptions(): CompilerOptions;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile;
diff --git a/lib/typescript.js b/lib/typescript.js
index 0985c69c169..14fbdce59a8 100644
--- a/lib/typescript.js
+++ b/lib/typescript.js
@@ -502,7 +502,6 @@ var ts;
TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType";
TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument";
TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias";
- TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue";
})(ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
var TypeFormatFlags = ts.TypeFormatFlags;
(function (SymbolFormatFlags) {
@@ -1165,7 +1164,6 @@ var ts;
contains: contains,
remove: remove,
forEachValue: forEachValueInMap,
- getKeys: getKeys,
clear: clear
};
function forEachValueInMap(f) {
@@ -1173,13 +1171,6 @@ var ts;
f(key, files[key]);
}
}
- function getKeys() {
- var keys = [];
- for (var key in files) {
- keys.push(key);
- }
- return keys;
- }
// path should already be well-formed so it does not need to be normalized
function get(path) {
return files[toKey(path)];
@@ -1510,7 +1501,6 @@ var ts;
return array1.concat(array2);
}
ts.concatenate = concatenate;
- // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication.
function deduplicate(array, areEqual) {
var result;
if (array) {
@@ -1614,22 +1604,16 @@ var ts;
* @param array A sorted array whose first element must be no larger than number
* @param number The value to be searched for in the array.
*/
- function binarySearch(array, value, comparer) {
- if (!array || array.length === 0) {
- return -1;
- }
+ function binarySearch(array, value) {
var low = 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) {
+ if (midValue === value) {
return middle;
}
- else if (comparer(midValue, value) > 0) {
+ else if (midValue > value) {
high = middle - 1;
}
else {
@@ -2194,49 +2178,10 @@ var ts;
return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1;
}
ts.isUrl = isUrl;
- 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);
- }
- ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
- function getEmitScriptTarget(compilerOptions) {
- return compilerOptions.target || 0 /* ES3 */;
- }
- ts.getEmitScriptTarget = getEmitScriptTarget;
- function getEmitModuleKind(compilerOptions) {
- return typeof compilerOptions.module === "number" ?
- compilerOptions.module :
- getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS;
- }
- ts.getEmitModuleKind = getEmitModuleKind;
- /* @internal */
- 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;
- }
- ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
function isRootedDiskPath(path) {
return getRootLength(path) !== 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
- function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
- return !isRootedDiskPath(absoluteOrRelativePath)
- ? absoluteOrRelativePath
- : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false);
- }
- ts.convertToRelativePath = convertToRelativePath;
function normalizedPathComponents(path, rootLength) {
var normalizedParts = getNormalizedParts(path, rootLength);
return [path.substr(0, rootLength)].concat(normalizedParts);
@@ -2680,14 +2625,6 @@ var ts;
return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
ts.getSupportedExtensions = getSupportedExtensions;
- function hasJavaScriptFileExtension(fileName) {
- return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
- }
- ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
- function hasTypeScriptFileExtension(fileName) {
- return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
- }
- ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension;
function isSupportedSourceFileName(fileName, compilerOptions) {
if (!fileName) {
return false;
@@ -2899,12 +2836,6 @@ var ts;
: (function (fileName) { return fileName.toLowerCase(); });
}
ts.createGetCanonicalFileName = createGetCanonicalFileName;
- function positionIsSynthesized(pos) {
- // This is a fast way of testing the following conditions:
- // pos === undefined || pos === null || isNaN(pos) || pos < 0;
- return !(pos >= 0);
- }
- ts.positionIsSynthesized = positionIsSynthesized;
})(ts || (ts = {}));
///
var ts;
@@ -3368,40 +3299,20 @@ var ts;
realpath: realpath
};
}
- function recursiveCreateDirectory(directoryPath, sys) {
- var basePath = ts.getDirectoryPath(directoryPath);
- var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath);
- if (shouldCreateParent) {
- recursiveCreateDirectory(basePath, sys);
- }
- if (shouldCreateParent || !sys.directoryExists(directoryPath)) {
- sys.createDirectory(directoryPath);
- }
- }
- var sys;
if (typeof ChakraHost !== "undefined") {
- sys = getChakraSystem();
+ return getChakraSystem();
}
else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
- sys = getWScriptSystem();
+ return getWScriptSystem();
}
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
// process and process.nextTick checks if current environment is node-like
// process.browser check excludes webpack and browserify
- sys = getNodeSystem();
+ return getNodeSystem();
}
- if (sys) {
- // patch writefile to create folder before writing the file
- var originalWriteFile_1 = sys.writeFile;
- sys.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);
- };
+ else {
+ return undefined; // Unsupported host
}
- return sys;
})();
})(ts || (ts = {}));
//
@@ -4124,7 +4035,6 @@ var ts;
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." },
Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." },
- Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -7078,6 +6988,12 @@ var ts;
return false;
}
ts.isPartOfExpression = isPartOfExpression;
+ 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);
+ }
+ ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
var moduleState = ts.getModuleInstanceState(node);
return moduleState === 1 /* Instantiated */ ||
@@ -7739,10 +7655,16 @@ var ts;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(node) {
- return ts.positionIsSynthesized(node.pos)
- || ts.positionIsSynthesized(node.end);
+ return positionIsSynthesized(node.pos)
+ || positionIsSynthesized(node.end);
}
ts.nodeIsSynthesized = nodeIsSynthesized;
+ function positionIsSynthesized(pos) {
+ // This is a fast way of testing the following conditions:
+ // pos === undefined || pos === null || isNaN(pos) || pos < 0;
+ return !(pos >= 0);
+ }
+ ts.positionIsSynthesized = positionIsSynthesized;
function getOriginalNode(node) {
if (node) {
while (node.original !== undefined) {
@@ -8203,12 +8125,24 @@ var ts;
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";
+ if (options.declaration) {
+ var path = outputDir
+ ? getSourceFilePathInNewDir(sourceFile, host, outputDir)
+ : sourceFile.fileName;
+ return ts.removeFileExtension(path) + ".d.ts";
+ }
}
ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
+ function getEmitScriptTarget(compilerOptions) {
+ return compilerOptions.target || 0 /* ES3 */;
+ }
+ ts.getEmitScriptTarget = getEmitScriptTarget;
+ function getEmitModuleKind(compilerOptions) {
+ return typeof compilerOptions.module === "number" ?
+ compilerOptions.module :
+ getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS;
+ }
+ ts.getEmitModuleKind = getEmitModuleKind;
/**
* Gets the source files that are expected to have an emit output.
*
@@ -8221,7 +8155,7 @@ var ts;
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- var moduleKind = ts.getEmitModuleKind(options);
+ var moduleKind = getEmitModuleKind(options);
var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
var sourceFiles = host.getSourceFiles();
// Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
@@ -8250,7 +8184,7 @@ var ts;
* @param sourceFiles The transformed source files to emit.
* @param action The action to execute.
*/
- function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) {
+ function forEachTransformedEmitFile(host, sourceFiles, action) {
var options = host.getCompilerOptions();
// Emit on each source file
if (options.outFile || options.out) {
@@ -8283,7 +8217,7 @@ var ts;
}
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && emitOnlyDtsFiles ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
+ var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false);
}
function onBundledEmit(host, sourceFiles) {
@@ -8308,7 +8242,7 @@ var ts;
* @param action The action to execute.
* @param targetSourceFile An optional target source file to emit.
*/
- function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) {
+ function forEachExpectedEmitFile(host, action, targetSourceFile) {
var options = host.getCompilerOptions();
// Emit on each source file
if (options.outFile || options.out) {
@@ -8341,13 +8275,12 @@ var ts;
}
}
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
var emitFileNames = {
jsFilePath: jsFilePath,
sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
- declarationFilePath: declarationFilePath
+ declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined
};
- action(emitFileNames, [sourceFile], /*isBundledEmit*/ false, emitOnlyDtsFiles);
+ action(emitFileNames, [sourceFile], /*isBundledEmit*/ false);
}
function onBundledEmit(host) {
// Can emit only sources that are not declaration file and are either non module code or module with
@@ -8355,7 +8288,7 @@ var ts;
var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) &&
!host.isSourceFileFromExternalLibrary(sourceFile) &&
(!ts.isExternalModule(sourceFile) ||
- !!ts.getEmitModuleKind(options)); });
+ !!getEmitModuleKind(options)); });
if (bundledSources.length) {
var jsFilePath = options.outFile || options.out;
var emitFileNames = {
@@ -8363,7 +8296,7 @@ var ts;
sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined
};
- action(emitFileNames, bundledSources, /*isBundledEmit*/ true, emitOnlyDtsFiles);
+ action(emitFileNames, bundledSources, /*isBundledEmit*/ true);
}
}
}
@@ -8767,6 +8700,14 @@ var ts;
return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined;
}
ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
+ function hasJavaScriptFileExtension(fileName) {
+ return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
+ function hasTypeScriptFileExtension(fileName) {
+ return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension;
/** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
function tryExtractTypeScriptExtension(fileName) {
return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
@@ -8879,6 +8820,12 @@ var ts;
return result;
}
ts.convertToBase64 = convertToBase64;
+ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
+ return !ts.isRootedDiskPath(absoluteOrRelativePath)
+ ? absoluteOrRelativePath
+ : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false);
+ }
+ ts.convertToRelativePath = convertToRelativePath;
var carriageReturnLineFeed = "\r\n";
var lineFeed = "\n";
function getNewLineCharacter(options) {
@@ -8991,7 +8938,7 @@ var ts;
* @param value The delta.
*/
function movePos(pos, value) {
- return ts.positionIsSynthesized(pos) ? -1 : pos + value;
+ return positionIsSynthesized(pos) ? -1 : pos + value;
}
ts.movePos = movePos;
/**
@@ -9107,7 +9054,7 @@ var ts;
}
ts.positionsAreOnSameLine = positionsAreOnSameLine;
function getStartPositionOfRange(range, sourceFile) {
- return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
+ return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
}
ts.getStartPositionOfRange = getStartPositionOfRange;
function collectExternalModuleInfo(sourceFile, resolver) {
@@ -18875,731 +18822,7 @@ var ts;
})(InvalidPosition || (InvalidPosition = {}));
})(IncrementalParser || (IncrementalParser = {}));
})(ts || (ts = {}));
-///
-///
-var ts;
-(function (ts) {
- function trace(host, message) {
- host.trace(ts.formatMessage.apply(undefined, arguments));
- }
- ts.trace = trace;
- /* @internal */
- function isTraceEnabled(compilerOptions, host) {
- return compilerOptions.traceResolution && host.trace !== undefined;
- }
- ts.isTraceEnabled = isTraceEnabled;
- /* @internal */
- function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) {
- return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
- }
- ts.createResolvedModule = createResolvedModule;
- function moduleHasNonRelativeName(moduleName) {
- return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
- }
- function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
- var jsonContent = readJson(packageJsonPath, state.host);
- function tryReadFromField(fieldName) {
- if (ts.hasProperty(jsonContent, fieldName)) {
- var typesFile = jsonContent[fieldName];
- if (typeof typesFile === "string") {
- var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1);
- }
- return typesFilePath_1;
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
- }
- }
- }
- }
- var typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
- if (typesFilePath) {
- return typesFilePath;
- }
- // Use the main module for inferring types if no types package specified and the allowJs is set
- if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main);
- }
- var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main));
- return mainFilePath;
- }
- return undefined;
- }
- function readJson(path, host) {
- try {
- var jsonText = host.readFile(path);
- return jsonText ? JSON.parse(jsonText) : {};
- }
- catch (e) {
- // gracefully handle if readFile fails or returns not JSON
- return {};
- }
- }
- var typeReferenceExtensions = [".d.ts"];
- 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();
- }
- return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
- }
- ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
- /**
- * Returns the path to every node_modules/@types directory from some ancestor directory.
- * Returns undefined if there are none.
- */
- function getDefaultTypeRoots(currentDirectory, host) {
- if (!host.directoryExists) {
- return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
- }
- var typeRoots;
- while (true) {
- var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes);
- if (host.directoryExists(atTypes)) {
- (typeRoots || (typeRoots = [])).push(atTypes);
- }
- var parent_6 = ts.getDirectoryPath(currentDirectory);
- if (parent_6 === currentDirectory) {
- break;
- }
- currentDirectory = parent_6;
- }
- return typeRoots;
- }
- var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
- /**
- * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
- * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
- * is assumed to be the same as root directory of the project.
- */
- function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
- var traceEnabled = isTraceEnabled(options, host);
- var moduleResolutionState = {
- compilerOptions: options,
- host: host,
- skipTsx: true,
- 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 = [];
- // Check primary library paths
- if (typeRoots && typeRoots.length) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
- }
- var primarySearchPaths = typeRoots;
- for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) {
- var typeRoot = primarySearchPaths_1[_i];
- var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
- var candidateDirectory = ts.getDirectoryPath(candidate);
- var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState);
- if (resolvedFile_1) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true);
- }
- return {
- resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 },
- failedLookupLocations: failedLookupLocations
- };
- }
- }
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
- }
- }
- var resolvedFile;
- var initialLocationForSecondaryLookup;
- if (containingFile) {
- initialLocationForSecondaryLookup = 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);
- }
- resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*checkOneLevel*/ false);
- if (traceEnabled) {
- if (resolvedFile) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
- }
- else {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
- }
- }
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
- }
- }
- return {
- resolvedTypeReferenceDirective: resolvedFile
- ? { primary: false, resolvedFileName: resolvedFile }
- : undefined,
- failedLookupLocations: failedLookupLocations
- };
- }
- ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
- /**
- * Given a set of options, returns the set of type directive names
- * that should be included for this program automatically.
- * This list could either come from the config file,
- * or from enumerating the types root + initial secondary types lookup location.
- * More type directives might appear in the program later as a result of loading actual source files;
- * this list is only the set of defaults that are implicitly included.
- */
- 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;
- }
- ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
- function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
- }
- 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]);
- }
- }
- var result;
- switch (moduleResolution) {
- case ts.ModuleResolutionKind.NodeJs:
- result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
- case ts.ModuleResolutionKind.Classic:
- result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
- }
- 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;
- }
- ts.resolveModuleName = resolveModuleName;
- /**
- * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
- * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
- * can be resolved successfully by TypeScript compiler and runtime module loader.
- * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
- * fallback to standard resolution routine.
- *
- * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
- * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
- * be '/a/b/c/d'
- * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
- * will be resolved based on the content of the module name.
- * Structure of 'paths' compiler options
- * 'paths': {
- * pattern-1: [...substitutions],
- * pattern-2: [...substitutions],
- * ...
- * pattern-n: [...substitutions]
- * }
- * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
- * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
- * If pattern contains '*' then to match pattern "*" module name must start with the and end with .
- * denotes part of the module name between and .
- * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
- * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
- * from the candidate location.
- * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
- * substitution in the list and replace '*' with string. If candidate location is not rooted it
- * will be converted to absolute using baseUrl.
- * For example:
- * baseUrl: /a/b/c
- * "paths": {
- * // match all module names
- * "*": [
- * "*", // use matched name as is,
- * // will be looked as /a/b/c/
- *
- * "folder1/*" // substitution will convert matched name to 'folder1/',
- * // since it is not rooted then final candidate location will be /a/b/c/folder1/
- * ],
- * // match module names that start with 'components/'
- * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/',
- * // it is rooted so it will be final candidate location
- * }
- *
- * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
- * they were in the same location. For example lets say there are two files
- * '/local/src/content/file1.ts'
- * '/shared/components/contracts/src/content/protocols/file2.ts'
- * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
- * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
- * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
- * root dirs were merged together.
- * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
- * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
- * '/local/src/content/protocols/file2' and try to load it - failure.
- * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
- * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
- * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
- */
- function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
- if (moduleHasNonRelativeName(moduleName)) {
- return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
- }
- else {
- return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
- }
- }
- function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
- if (!state.compilerOptions.rootDirs) {
- return undefined;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
- }
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- var matchedRootDir;
- var matchedNormalizedPrefix;
- for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
- var rootDir = _a[_i];
- // rootDirs are expected to be absolute
- // in case of tsconfig.json this will happen automatically - compiler will expand relative names
- // using location of tsconfig.json as base location
- var normalizedRoot = ts.normalizePath(rootDir);
- if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
- normalizedRoot += ts.directorySeparator;
- }
- var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
- (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
- }
- if (isLongestMatchingPrefix) {
- matchedNormalizedPrefix = normalizedRoot;
- matchedRootDir = rootDir;
- }
- }
- if (matchedNormalizedPrefix) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
- }
- var suffix = candidate.substr(matchedNormalizedPrefix.length);
- // first - try to load from a initial location
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
- }
- var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
- if (resolvedFileName) {
- return resolvedFileName;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
- }
- // then try to resolve using remaining entries in rootDirs
- for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
- var rootDir = _c[_b];
- if (rootDir === matchedRootDir) {
- // skip the initially matched entry
- continue;
- }
- var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
- }
- var baseDirectory = ts.getDirectoryPath(candidate_1);
- var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
- if (resolvedFileName_1) {
- return resolvedFileName_1;
- }
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
- }
- }
- return undefined;
- }
- function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) {
- if (!state.compilerOptions.baseUrl) {
- return undefined;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
- }
- // string is for exact match
- var matchedPattern = undefined;
- if (state.compilerOptions.paths) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
- }
- matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
- }
- if (matchedPattern) {
- var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
- var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
- }
- for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) {
- var subst = _a[_i];
- var path = matchedStar ? subst.replace("*", matchedStar) : subst;
- var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
- }
- var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- if (resolvedFileName) {
- return resolvedFileName;
- }
- }
- return undefined;
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
- }
- return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- }
- }
- /**
- * patternStrings contains both pattern strings (containing "*") and regular strings.
- * Return an exact match if possible, or a pattern match, or undefined.
- * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
- */
- 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);
- }
- function patternText(_a) {
- var prefix = _a.prefix, suffix = _a.suffix;
- return prefix + "*" + suffix;
- }
- /**
- * Given that candidate matches pattern, returns the text matching the '*'.
- * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
- */
- function matchedText(pattern, candidate) {
- ts.Debug.assert(isPatternMatch(pattern, candidate));
- return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
- }
- /** Return the object corresponding to the best pattern to match `candidate`. */
- /* @internal */
- 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;
- }
- ts.findBestPatternMatch = findBestPatternMatch;
- function isPatternMatch(_a, candidate) {
- var prefix = _a.prefix, suffix = _a.suffix;
- return candidate.length >= prefix.length + suffix.length &&
- ts.startsWith(candidate, prefix) &&
- ts.endsWith(candidate, suffix);
- }
- /* @internal */
- function tryParsePattern(pattern) {
- // This should be verified outside of here and a proper error thrown.
- ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern));
- var indexOfStar = pattern.indexOf("*");
- return indexOfStar === -1 ? undefined : {
- prefix: pattern.substr(0, indexOfStar),
- suffix: pattern.substr(indexOfStar + 1)
- };
- }
- ts.tryParsePattern = tryParsePattern;
- function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var failedLookupLocations = [];
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false };
- var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state);
- var isExternalLibraryImport = false;
- if (!resolvedFileName) {
- if (moduleHasNonRelativeName(moduleName)) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
- }
- resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, /*checkOneLevel*/ false);
- isExternalLibraryImport = resolvedFileName !== undefined;
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
- }
- }
- if (resolvedFileName && host.realpath) {
- var originalFileName = resolvedFileName;
- resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName));
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName);
- }
- }
- return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
- }
- ts.nodeModuleNameResolver = nodeModuleNameResolver;
- function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
- }
- var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
- return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
- }
- /* @internal */
- function directoryProbablyExists(directoryName, host) {
- // if host does not support 'directoryExists' assume that directory will exist
- return !host.directoryExists || host.directoryExists(directoryName);
- }
- ts.directoryProbablyExists = directoryProbablyExists;
- /**
- * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
- * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
- */
- function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
- // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
- var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
- if (resolvedByAddingExtension) {
- return resolvedByAddingExtension;
- }
- // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
- // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
- if (ts.hasJavaScriptFileExtension(candidate)) {
- var extensionless = ts.removeFileExtension(candidate);
- if (state.traceEnabled) {
- var extension = candidate.substring(extensionless.length);
- trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
- }
- return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
- }
- }
- /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
- function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
- if (!onlyRecordFailures) {
- // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
- var directory = ts.getDirectoryPath(candidate);
- if (directory) {
- onlyRecordFailures = !directoryProbablyExists(directory, state.host);
- }
- }
- return ts.forEach(extensions, function (ext) {
- return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state);
- });
- }
- /** Return the file if it exists. */
- function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) {
- if (!onlyRecordFailures && state.host.fileExists(fileName)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
- }
- return fileName;
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
- }
- failedLookupLocation.push(fileName);
- return undefined;
- }
- }
- function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) {
- var packageJsonPath = pathToPackageJson(candidate);
- var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
- if (directoryExists && state.host.fileExists(packageJsonPath)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
- }
- var typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
- if (typesFile) {
- var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host);
- // A package.json "typings" may specify an exact filename, or may choose to omit an extension.
- var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) ||
- tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state);
- if (result) {
- return result;
- }
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field);
- }
- }
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
- }
- // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
- failedLookupLocation.push(packageJsonPath);
- }
- return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
- }
- function pathToPackageJson(directory) {
- return ts.combinePaths(directory, "package.json");
- }
- function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) {
- var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
- var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
- var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
- var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions);
- var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
- if (result) {
- return result;
- }
- result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
- if (result) {
- return result;
- }
- }
- /* @internal */
- function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) {
- directory = ts.normalizeSlashes(directory);
- while (true) {
- var baseName = ts.getBaseFileName(directory);
- if (baseName !== "node_modules") {
- // Try to load source from the package
- var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
- if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
- // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package
- return packageResult;
- }
- else {
- // Else prefer a types package over non-TypeScript results (e.g. JavaScript files)
- var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
- if (typesResult || packageResult) {
- return typesResult || packageResult;
- }
- }
- }
- var parentPath = ts.getDirectoryPath(directory);
- if (parentPath === directory || checkOneLevel) {
- break;
- }
- directory = parentPath;
- }
- return undefined;
- }
- ts.loadModuleFromNodeModules = loadModuleFromNodeModules;
- function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
- var failedLookupLocations = [];
- var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
- if (resolvedFileName) {
- return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations);
- }
- var referencedSourceFile;
- if (moduleHasNonRelativeName(moduleName)) {
- while (true) {
- var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
- if (referencedSourceFile) {
- break;
- }
- var parentPath = ts.getDirectoryPath(containingDirectory);
- if (parentPath === containingDirectory) {
- break;
- }
- containingDirectory = parentPath;
- }
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
- }
- return referencedSourceFile
- ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations }
- : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
- }
- ts.classicNameResolver = classicNameResolver;
-})(ts || (ts = {}));
///
-///
///
/* @internal */
var ts;
@@ -21380,12 +20603,12 @@ var ts;
return;
}
else {
- var parent_7 = node.parent;
- if (!ts.isExternalModule(parent_7)) {
+ var parent_6 = node.parent;
+ if (!ts.isExternalModule(parent_6)) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files));
return;
}
- if (!parent_7.isDeclarationFile) {
+ if (!parent_6.isDeclarationFile) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files));
return;
}
@@ -24184,9 +23407,9 @@ var ts;
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
// Go up and add our parent.
- var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
- if (parent_8) {
- walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
+ var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
+ if (parent_7) {
+ walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
}
}
if (accessibleSymbolChain) {
@@ -24326,14 +23549,14 @@ var ts;
while (i < length_1) {
// Find group of type arguments for type parameters with the same declaring container.
var start = i;
- var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
+ var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
do {
i++;
- } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9);
+ } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8);
// When type parameters are their own type arguments for the whole group (i.e. we have
// the default outer type arguments), we don't show the group.
if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
- writeSymbolTypeReference(parent_9, typeArguments, start, i, flags);
+ writeSymbolTypeReference(parent_8, typeArguments, start, i, flags);
writePunctuation(writer, 21 /* DotToken */);
}
}
@@ -24737,14 +23960,14 @@ var ts;
if (ts.isExternalModuleAugmentation(node)) {
return true;
}
- var parent_10 = getDeclarationContainer(node);
+ var parent_9 = getDeclarationContainer(node);
// If the node is not exported or it is not ambient module element (except import declaration)
if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
- !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_10.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_10))) {
- return isGlobalSourceFile(parent_10);
+ !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_9.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_9))) {
+ return isGlobalSourceFile(parent_9);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
- return isDeclarationVisible(parent_10);
+ return isDeclarationVisible(parent_9);
case 145 /* PropertyDeclaration */:
case 144 /* PropertySignature */:
case 149 /* GetAccessor */:
@@ -32625,13 +31848,13 @@ var ts;
for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
var signature = signatures_2[_i];
var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
- var parent_11 = signature.declaration && signature.declaration.parent;
+ var parent_10 = signature.declaration && signature.declaration.parent;
if (!lastSymbol || symbol === lastSymbol) {
- if (lastParent && parent_11 === lastParent) {
+ if (lastParent && parent_10 === lastParent) {
index++;
}
else {
- lastParent = parent_11;
+ lastParent = parent_10;
index = cutoffIndex;
}
}
@@ -32639,7 +31862,7 @@ var ts;
// current declaration belongs to a different symbol
// set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
index = cutoffIndex = result.length;
- lastParent = parent_11;
+ lastParent = parent_10;
}
lastSymbol = symbol;
// specialized signatures always need to be placed before non-specialized signatures regardless
@@ -35165,9 +34388,9 @@ var ts;
case 156 /* FunctionType */:
case 147 /* MethodDeclaration */:
case 146 /* MethodSignature */:
- var parent_12 = node.parent;
- if (node === parent_12.type) {
- return parent_12;
+ var parent_11 = node.parent;
+ if (node === parent_11.type) {
+ return parent_11;
}
}
}
@@ -36723,12 +35946,12 @@ var ts;
checkComputedPropertyName(node.propertyName);
}
// check private/protected variable access
- var parent_13 = node.parent.parent;
- var parentType = getTypeForBindingElementParent(parent_13);
+ var parent_12 = node.parent.parent;
+ var parentType = getTypeForBindingElementParent(parent_12);
var name_21 = node.propertyName || node.name;
var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21));
- if (parent_13.initializer && property && getParentOfSymbol(property)) {
- checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property);
+ if (parent_12.initializer && property && getParentOfSymbol(property)) {
+ checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property);
}
}
// For a binding pattern, check contained binding elements
@@ -39503,9 +38726,9 @@ var ts;
if (startInDeclarationContainer) {
// When resolving the name of a declaration as a value, we need to start resolution
// at a point outside of the declaration.
- var parent_14 = reference.parent;
- if (ts.isDeclaration(parent_14) && reference === parent_14.name) {
- location = getDeclarationContainer(parent_14);
+ var parent_13 = reference.parent;
+ if (ts.isDeclaration(parent_13) && reference === parent_13.name) {
+ location = getDeclarationContainer(parent_13);
}
}
return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined);
@@ -39629,9 +38852,9 @@ var ts;
// external modules cannot define or contribute to type declaration files
var current = symbol;
while (true) {
- var parent_15 = getParentOfSymbol(current);
- if (parent_15) {
- current = parent_15;
+ var parent_14 = getParentOfSymbol(current);
+ if (parent_14) {
+ current = parent_14;
}
else {
break;
@@ -53512,11 +52735,11 @@ var ts;
return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);
function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) {
var declarationFilePath = _a.declarationFilePath;
- emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, /*emitOnlyDtsFiles*/ false);
+ emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);
}
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
- function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) {
+ function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) {
var newLine = host.getNewLine();
var compilerOptions = host.getCompilerOptions();
var write;
@@ -53563,7 +52786,7 @@ var ts;
// global file reference is added only
// - if it is not bundled emit (because otherwise it would be self reference)
// - and it is not already added
- if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) {
+ if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) {
addedGlobalFileReference = true;
}
emittedReferencedFiles.push(referencedFile);
@@ -53764,7 +52987,7 @@ var ts;
}
else {
errorNameNode = declaration.name;
- resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer);
+ resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer);
errorNameNode = undefined;
}
}
@@ -53777,7 +53000,7 @@ var ts;
}
else {
errorNameNode = signature.name;
- resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer);
+ resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer);
errorNameNode = undefined;
}
}
@@ -53979,7 +53202,7 @@ var ts;
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic;
- resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer);
+ resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer);
write(";");
writeLine();
write(node.isExportEquals ? "export = " : "export default ");
@@ -54401,7 +53624,7 @@ var ts;
}
else {
writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError;
- resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer);
+ resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer);
}
function getHeritageClauseVisibilityError(symbolAccessibilityResult) {
var diagnosticMessage;
@@ -55042,7 +54265,7 @@ var ts;
* @param referencedFile
* @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not
*/
- function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) {
+ function writeReferencePath(referencedFile, addBundledFileReference) {
var declFileName;
var addedBundledEmitReference = false;
if (ts.isDeclarationFile(referencedFile)) {
@@ -55051,7 +54274,7 @@ var ts;
}
else {
// Get the declaration file path
- ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles);
+ ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile);
}
if (declFileName) {
declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName,
@@ -55071,8 +54294,8 @@ var ts;
}
}
/* @internal */
- function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) {
- var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles);
+ function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) {
+ var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit);
var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit;
if (!emitSkipped) {
var declarationOutput = emitDeclarationResult.referencesOutput
@@ -55113,7 +54336,7 @@ var ts;
TempFlags[TempFlags["_i"] = 268435456] = "_i";
})(TempFlags || (TempFlags = {}));
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) {
+ function emitFiles(resolver, host, targetSourceFile) {
var delimiters = createDelimiterMap();
var brackets = createBracketsMap();
// emit output for the __extends helper function
@@ -55232,7 +54455,7 @@ var ts;
var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode;
ts.performance.mark("beforePrint");
// Emit each output file
- ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile, emitOnlyDtsFiles);
+ ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile);
// Clean up after transformation
transformed.dispose();
ts.performance.measure("printTime", "beforePrint");
@@ -55251,7 +54474,7 @@ var ts;
emitSkipped = true;
}
if (declarationFilePath) {
- emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped;
+ emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped;
}
if (!emitSkipped && emittedFilesList) {
emittedFilesList.push(jsFilePath);
@@ -57593,7 +56816,7 @@ var ts;
var ts;
(function (ts) {
/** The version of the TypeScript compiler release */
- ts.version = "2.0.5";
+ ts.version = "2.1.0";
var emptyArray = [];
function findConfigFile(searchPath, fileExists, configName) {
if (configName === void 0) { configName = "tsconfig.json"; }
@@ -57655,6 +56878,695 @@ var ts;
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}
ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
+ function trace(host, message) {
+ host.trace(ts.formatMessage.apply(undefined, arguments));
+ }
+ function isTraceEnabled(compilerOptions, host) {
+ return compilerOptions.traceResolution && host.trace !== undefined;
+ }
+ /* @internal */
+ 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;
+ }
+ ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) {
+ return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
+ }
+ function moduleHasNonRelativeName(moduleName) {
+ return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
+ }
+ function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
+ var jsonContent = readJson(packageJsonPath, state.host);
+ function tryReadFromField(fieldName) {
+ if (ts.hasProperty(jsonContent, fieldName)) {
+ var typesFile = jsonContent[fieldName];
+ if (typeof typesFile === "string") {
+ var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1);
+ }
+ return typesFilePath_1;
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
+ }
+ }
+ }
+ }
+ var typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
+ if (typesFilePath) {
+ return typesFilePath;
+ }
+ // Use the main module for inferring types if no types package specified and the allowJs is set
+ if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main);
+ }
+ var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main));
+ return mainFilePath;
+ }
+ return undefined;
+ }
+ function readJson(path, host) {
+ try {
+ var jsonText = host.readFile(path);
+ return jsonText ? JSON.parse(jsonText) : {};
+ }
+ catch (e) {
+ // gracefully handle if readFile fails or returns not JSON
+ return {};
+ }
+ }
+ var typeReferenceExtensions = [".d.ts"];
+ 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();
+ }
+ return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
+ }
+ ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
+ /**
+ * Returns the path to every node_modules/@types directory from some ancestor directory.
+ * Returns undefined if there are none.
+ */
+ function getDefaultTypeRoots(currentDirectory, host) {
+ if (!host.directoryExists) {
+ return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
+ }
+ var typeRoots;
+ while (true) {
+ var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes);
+ if (host.directoryExists(atTypes)) {
+ (typeRoots || (typeRoots = [])).push(atTypes);
+ }
+ var parent_15 = ts.getDirectoryPath(currentDirectory);
+ if (parent_15 === currentDirectory) {
+ break;
+ }
+ currentDirectory = parent_15;
+ }
+ return typeRoots;
+ }
+ var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
+ /**
+ * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
+ * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
+ * is assumed to be the same as root directory of the project.
+ */
+ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
+ var traceEnabled = isTraceEnabled(options, host);
+ var moduleResolutionState = {
+ compilerOptions: options,
+ host: host,
+ skipTsx: true,
+ 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 = [];
+ // Check primary library paths
+ if (typeRoots && typeRoots.length) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
+ }
+ var primarySearchPaths = typeRoots;
+ for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) {
+ var typeRoot = primarySearchPaths_1[_i];
+ var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
+ var candidateDirectory = ts.getDirectoryPath(candidate);
+ var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState);
+ if (resolvedFile_1) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true);
+ }
+ return {
+ resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 },
+ failedLookupLocations: failedLookupLocations
+ };
+ }
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
+ }
+ }
+ var resolvedFile;
+ var initialLocationForSecondaryLookup;
+ if (containingFile) {
+ initialLocationForSecondaryLookup = 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);
+ }
+ resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState);
+ if (traceEnabled) {
+ if (resolvedFile) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
+ }
+ else {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
+ }
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
+ }
+ }
+ return {
+ resolvedTypeReferenceDirective: resolvedFile
+ ? { primary: false, resolvedFileName: resolvedFile }
+ : undefined,
+ failedLookupLocations: failedLookupLocations
+ };
+ }
+ ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
+ function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
+ }
+ 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]);
+ }
+ }
+ var result;
+ switch (moduleResolution) {
+ case ts.ModuleResolutionKind.NodeJs:
+ result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
+ break;
+ case ts.ModuleResolutionKind.Classic:
+ result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
+ break;
+ }
+ 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;
+ }
+ ts.resolveModuleName = resolveModuleName;
+ /**
+ * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
+ * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
+ * can be resolved successfully by TypeScript compiler and runtime module loader.
+ * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
+ * fallback to standard resolution routine.
+ *
+ * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
+ * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
+ * be '/a/b/c/d'
+ * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
+ * will be resolved based on the content of the module name.
+ * Structure of 'paths' compiler options
+ * 'paths': {
+ * pattern-1: [...substitutions],
+ * pattern-2: [...substitutions],
+ * ...
+ * pattern-n: [...substitutions]
+ * }
+ * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
+ * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
+ * If pattern contains '*' then to match pattern "*" module name must start with the and end with .
+ * denotes part of the module name between and .
+ * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
+ * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
+ * from the candidate location.
+ * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
+ * substitution in the list and replace '*' with string. If candidate location is not rooted it
+ * will be converted to absolute using baseUrl.
+ * For example:
+ * baseUrl: /a/b/c
+ * "paths": {
+ * // match all module names
+ * "*": [
+ * "*", // use matched name as is,
+ * // will be looked as /a/b/c/
+ *
+ * "folder1/*" // substitution will convert matched name to 'folder1/',
+ * // since it is not rooted then final candidate location will be /a/b/c/folder1/
+ * ],
+ * // match module names that start with 'components/'
+ * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/',
+ * // it is rooted so it will be final candidate location
+ * }
+ *
+ * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
+ * they were in the same location. For example lets say there are two files
+ * '/local/src/content/file1.ts'
+ * '/shared/components/contracts/src/content/protocols/file2.ts'
+ * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
+ * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
+ * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
+ * root dirs were merged together.
+ * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
+ * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
+ * '/local/src/content/protocols/file2' and try to load it - failure.
+ * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
+ * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
+ * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
+ */
+ function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
+ if (moduleHasNonRelativeName(moduleName)) {
+ return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
+ }
+ else {
+ return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
+ }
+ }
+ function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
+ if (!state.compilerOptions.rootDirs) {
+ return undefined;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
+ }
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ var matchedRootDir;
+ var matchedNormalizedPrefix;
+ for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
+ var rootDir = _a[_i];
+ // rootDirs are expected to be absolute
+ // in case of tsconfig.json this will happen automatically - compiler will expand relative names
+ // using location of tsconfig.json as base location
+ var normalizedRoot = ts.normalizePath(rootDir);
+ if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
+ normalizedRoot += ts.directorySeparator;
+ }
+ var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
+ (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
+ }
+ if (isLongestMatchingPrefix) {
+ matchedNormalizedPrefix = normalizedRoot;
+ matchedRootDir = rootDir;
+ }
+ }
+ if (matchedNormalizedPrefix) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
+ }
+ var suffix = candidate.substr(matchedNormalizedPrefix.length);
+ // first - try to load from a initial location
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
+ }
+ var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
+ if (resolvedFileName) {
+ return resolvedFileName;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
+ }
+ // then try to resolve using remaining entries in rootDirs
+ for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
+ var rootDir = _c[_b];
+ if (rootDir === matchedRootDir) {
+ // skip the initially matched entry
+ continue;
+ }
+ var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
+ }
+ var baseDirectory = ts.getDirectoryPath(candidate_1);
+ var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
+ if (resolvedFileName_1) {
+ return resolvedFileName_1;
+ }
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
+ }
+ }
+ return undefined;
+ }
+ function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) {
+ if (!state.compilerOptions.baseUrl) {
+ return undefined;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
+ }
+ // string is for exact match
+ var matchedPattern = undefined;
+ if (state.compilerOptions.paths) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
+ }
+ matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
+ }
+ if (matchedPattern) {
+ var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
+ var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
+ }
+ for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) {
+ var subst = _a[_i];
+ var path = matchedStar ? subst.replace("*", matchedStar) : subst;
+ var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
+ }
+ var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ if (resolvedFileName) {
+ return resolvedFileName;
+ }
+ }
+ return undefined;
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
+ }
+ return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ }
+ }
+ /**
+ * patternStrings contains both pattern strings (containing "*") and regular strings.
+ * Return an exact match if possible, or a pattern match, or undefined.
+ * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
+ */
+ 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);
+ }
+ function patternText(_a) {
+ var prefix = _a.prefix, suffix = _a.suffix;
+ return prefix + "*" + suffix;
+ }
+ /**
+ * Given that candidate matches pattern, returns the text matching the '*'.
+ * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
+ */
+ function matchedText(pattern, candidate) {
+ ts.Debug.assert(isPatternMatch(pattern, candidate));
+ return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
+ }
+ /** Return the object corresponding to the best pattern to match `candidate`. */
+ /* @internal */
+ 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;
+ }
+ ts.findBestPatternMatch = findBestPatternMatch;
+ function isPatternMatch(_a, candidate) {
+ var prefix = _a.prefix, suffix = _a.suffix;
+ return candidate.length >= prefix.length + suffix.length &&
+ ts.startsWith(candidate, prefix) &&
+ ts.endsWith(candidate, suffix);
+ }
+ /* @internal */
+ function tryParsePattern(pattern) {
+ // This should be verified outside of here and a proper error thrown.
+ ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
+ var indexOfStar = pattern.indexOf("*");
+ return indexOfStar === -1 ? undefined : {
+ prefix: pattern.substr(0, indexOfStar),
+ suffix: pattern.substr(indexOfStar + 1)
+ };
+ }
+ ts.tryParsePattern = tryParsePattern;
+ function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var failedLookupLocations = [];
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false };
+ var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state);
+ var isExternalLibraryImport = false;
+ if (!resolvedFileName) {
+ if (moduleHasNonRelativeName(moduleName)) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
+ }
+ resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state);
+ isExternalLibraryImport = resolvedFileName !== undefined;
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
+ }
+ }
+ if (resolvedFileName && host.realpath) {
+ var originalFileName = resolvedFileName;
+ resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName));
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName);
+ }
+ }
+ return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
+ }
+ ts.nodeModuleNameResolver = nodeModuleNameResolver;
+ function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
+ }
+ var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
+ return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
+ }
+ /* @internal */
+ function directoryProbablyExists(directoryName, host) {
+ // if host does not support 'directoryExists' assume that directory will exist
+ return !host.directoryExists || host.directoryExists(directoryName);
+ }
+ ts.directoryProbablyExists = directoryProbablyExists;
+ /**
+ * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
+ * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
+ */
+ function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
+ // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
+ var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
+ if (resolvedByAddingExtension) {
+ return resolvedByAddingExtension;
+ }
+ // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
+ // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
+ if (ts.hasJavaScriptFileExtension(candidate)) {
+ var extensionless = ts.removeFileExtension(candidate);
+ if (state.traceEnabled) {
+ var extension = candidate.substring(extensionless.length);
+ trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
+ }
+ return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
+ }
+ }
+ /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
+ function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
+ if (!onlyRecordFailures) {
+ // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
+ var directory = ts.getDirectoryPath(candidate);
+ if (directory) {
+ onlyRecordFailures = !directoryProbablyExists(directory, state.host);
+ }
+ }
+ return ts.forEach(extensions, function (ext) {
+ return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state);
+ });
+ }
+ /** Return the file if it exists. */
+ function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) {
+ if (!onlyRecordFailures && state.host.fileExists(fileName)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
+ }
+ return fileName;
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
+ }
+ failedLookupLocation.push(fileName);
+ return undefined;
+ }
+ }
+ function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) {
+ var packageJsonPath = pathToPackageJson(candidate);
+ var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
+ if (directoryExists && state.host.fileExists(packageJsonPath)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
+ }
+ var typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
+ if (typesFile) {
+ var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host);
+ // A package.json "typings" may specify an exact filename, or may choose to omit an extension.
+ var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) ||
+ tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state);
+ if (result) {
+ return result;
+ }
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field);
+ }
+ }
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
+ }
+ // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
+ failedLookupLocation.push(packageJsonPath);
+ }
+ return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
+ }
+ function pathToPackageJson(directory) {
+ return ts.combinePaths(directory, "package.json");
+ }
+ function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) {
+ var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
+ var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
+ var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
+ var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions);
+ var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
+ if (result) {
+ return result;
+ }
+ result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
+ if (result) {
+ return result;
+ }
+ }
+ function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) {
+ directory = ts.normalizeSlashes(directory);
+ while (true) {
+ var baseName = ts.getBaseFileName(directory);
+ if (baseName !== "node_modules") {
+ // Try to load source from the package
+ var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
+ if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
+ // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package
+ return packageResult;
+ }
+ else {
+ // Else prefer a types package over non-TypeScript results (e.g. JavaScript files)
+ var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
+ if (typesResult || packageResult) {
+ return typesResult || packageResult;
+ }
+ }
+ }
+ var parentPath = ts.getDirectoryPath(directory);
+ if (parentPath === directory) {
+ break;
+ }
+ directory = parentPath;
+ }
+ return undefined;
+ }
+ function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
+ var failedLookupLocations = [];
+ var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
+ if (resolvedFileName) {
+ return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations);
+ }
+ var referencedSourceFile;
+ if (moduleHasNonRelativeName(moduleName)) {
+ while (true) {
+ var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
+ if (referencedSourceFile) {
+ break;
+ }
+ var parentPath = ts.getDirectoryPath(containingDirectory);
+ if (parentPath === containingDirectory) {
+ break;
+ }
+ containingDirectory = parentPath;
+ }
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
+ }
+ return referencedSourceFile
+ ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations }
+ : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
+ }
+ ts.classicNameResolver = classicNameResolver;
function createCompilerHost(options, setParentNodes) {
var existingDirectories = ts.createMap();
function getCanonicalFileName(fileName) {
@@ -57828,6 +57740,45 @@ var ts;
}
return resolutions;
}
+ /**
+ * Given a set of options, returns the set of type directive names
+ * that should be included for this program automatically.
+ * This list could either come from the config file,
+ * or from enumerating the types root + initial secondary types lookup location.
+ * More type directives might appear in the program later as a result of loading actual source files;
+ * this list is only the set of defaults that are implicitly included.
+ */
+ 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;
+ }
+ ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
function createProgram(rootNames, options, host, oldProgram) {
var program;
var files = [];
@@ -57864,7 +57815,7 @@ var ts;
resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); };
}
else {
- var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; };
+ var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; };
resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); };
}
var resolveTypeReferenceDirectiveNamesWorker;
@@ -57872,7 +57823,7 @@ var ts;
resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); };
}
else {
- var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; };
+ var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; };
resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); };
}
var filesByName = ts.createFileMap();
@@ -57882,7 +57833,7 @@ var ts;
if (!tryReuseStructureFromOldProgram()) {
ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); });
// load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
- var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host);
+ var typeReferences = getAutomaticTypeDirectiveNames(options, host);
if (typeReferences) {
// This containingFilename needs to match with the one used in managed-side
var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts");
@@ -57933,8 +57884,7 @@ var ts;
getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
- getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
- dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker
+ getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -58104,19 +58054,16 @@ var ts;
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
}
- function dropDiagnosticsProducingTypeChecker() {
- diagnosticsProducingTypeChecker = undefined;
- }
function getTypeChecker() {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
- function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
- return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); });
+ function emit(sourceFile, writeFileCallback, cancellationToken) {
+ return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
}
- function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
+ function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) {
var declarationDiagnostics = [];
if (options.noEmit) {
return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
@@ -58148,7 +58095,7 @@ var ts;
// checked is to not pass the file to getEmitResolver.
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
ts.performance.mark("beforeEmit");
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -58801,7 +58748,7 @@ var ts;
if (!ts.hasProperty(options.paths, key)) {
continue;
}
- if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
+ if (!hasZeroOrOneAsteriskCharacter(key)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key));
}
if (ts.isArray(options.paths[key])) {
@@ -58812,7 +58759,7 @@ var ts;
var subst = _a[_i];
var typeOfSubst = typeof subst;
if (typeOfSubst === "string") {
- if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
+ if (!hasZeroOrOneAsteriskCharacter(subst)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key));
}
}
@@ -58944,15 +58891,12 @@ var ts;
///
var ts;
(function (ts) {
- /* @internal */
- ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
/* @internal */
ts.optionDeclarations = [
{
name: "charset",
type: "string"
},
- ts.compileOnSaveCommandLineOption,
{
name: "declaration",
shortName: "d",
@@ -59603,11 +59547,10 @@ var ts;
* @param fileName The path to the config file
* @param jsonText The text of the config file
*/
- function parseConfigFileTextToJson(fileName, jsonText, stripComments) {
- if (stripComments === void 0) { stripComments = true; }
+ function parseConfigFileTextToJson(fileName, jsonText) {
try {
- var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText;
- return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} };
+ var jsonTextWithoutComments = removeComments(jsonText);
+ return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} };
}
catch (e) {
return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) };
@@ -59769,15 +59712,13 @@ var ts;
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,
typingOptions: typingOptions,
raw: json,
errors: errors,
- wildcardDirectories: wildcardDirectories,
- compileOnSave: compileOnSave
+ wildcardDirectories: wildcardDirectories
};
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)
@@ -59858,17 +59799,6 @@ var ts;
var _b;
}
ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
- 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;
- }
- ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson;
function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
var errors = [];
var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
@@ -59882,9 +59812,7 @@ var ts;
}
ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
- var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
- ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true }
- : {};
+ var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {};
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
return options;
}
@@ -61729,7 +61657,7 @@ var ts;
return ts.ensureScriptKind(fileName, scriptKind);
}
ts.getScriptKind = getScriptKind;
- function sanitizeConfigFile(configFileName, content) {
+ function parseAndReEmitConfigJSONFile(content) {
var options = {
fileName: "config.js",
compilerOptions: {
@@ -61743,17 +61671,14 @@ var ts;
// also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these
// as well
var trimmedOutput = outputText.trim();
+ var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2));
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
- };
+ return { configJsonObject: configJsonObject, diagnostics: diagnostics };
}
- ts.sanitizeConfigFile = sanitizeConfigFile;
+ ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -66506,9 +66431,7 @@ var ts;
})(ts || (ts = {}));
// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.
-///
-///
-///
+///
/* @internal */
var ts;
(function (ts) {
@@ -66519,7 +66442,6 @@ var ts;
// A map of loose file names to library names
// that we are confident require typings
var safeList;
- var EmptySafeList = ts.createMap();
/**
* @param host is the object providing I/O related operations.
* @param fileNames are the file names that belong to the same project
@@ -66536,13 +66458,10 @@ var ts;
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 */;
- });
+ fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); });
if (!safeList) {
var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
- safeList = result.config ? ts.createMap(result.config) : EmptySafeList;
+ safeList = ts.createMap(result.config);
}
var filesToWatch = [];
// Directories to search for package.json, bower.json and other typing information
@@ -66633,10 +66552,13 @@ var ts;
var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension);
var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); });
var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); });
- if (safeList !== EmptySafeList) {
+ if (safeList === undefined) {
+ mergeTypings(cleanedTypingNames);
+ }
+ else {
mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; }));
}
- var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; });
+ var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); });
if (hasJsxFile) {
mergeTypings(["react"]);
}
@@ -66651,7 +66573,7 @@ var ts;
return;
}
var typingNames = [];
- var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
+ var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
var fileName = fileNames_2[_i];
var normalizedFileName = ts.normalizePath(fileName);
@@ -66694,7 +66616,7 @@ var ts;
(function (ts) {
var NavigateTo;
(function (NavigateTo) {
- function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) {
+ function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) {
var patternMatcher = ts.createPatternMatcher(searchValue);
var rawItems = [];
// This means "compare in a case insensitive manner."
@@ -66702,9 +66624,6 @@ var ts;
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
ts.forEach(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) {
- return;
- }
var nameToDeclarations = sourceFile.getNamedDeclarations();
for (var name_49 in nameToDeclarations) {
var declarations = nameToDeclarations[name_49];
@@ -71086,25 +71005,25 @@ var ts;
};
RulesProvider.prototype.createActiveRules = function (options) {
var rules = this.globalRules.HighPriorityCommonRules.slice(0);
- if (options.insertSpaceAfterCommaDelimiter) {
+ if (options.InsertSpaceAfterCommaDelimiter) {
rules.push(this.globalRules.SpaceAfterComma);
}
else {
rules.push(this.globalRules.NoSpaceAfterComma);
}
- if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) {
+ if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) {
rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword);
}
else {
rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword);
}
- if (options.insertSpaceAfterKeywordsInControlFlowStatements) {
+ if (options.InsertSpaceAfterKeywordsInControlFlowStatements) {
rules.push(this.globalRules.SpaceAfterKeywordInControl);
}
else {
rules.push(this.globalRules.NoSpaceAfterKeywordInControl);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) {
rules.push(this.globalRules.SpaceAfterOpenParen);
rules.push(this.globalRules.SpaceBeforeCloseParen);
rules.push(this.globalRules.NoSpaceBetweenParens);
@@ -71114,7 +71033,7 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeCloseParen);
rules.push(this.globalRules.NoSpaceBetweenParens);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) {
rules.push(this.globalRules.SpaceAfterOpenBracket);
rules.push(this.globalRules.SpaceBeforeCloseBracket);
rules.push(this.globalRules.NoSpaceBetweenBrackets);
@@ -71126,7 +71045,7 @@ var ts;
}
// 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) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) {
rules.push(this.globalRules.SpaceAfterOpenBrace);
rules.push(this.globalRules.SpaceBeforeCloseBrace);
rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets);
@@ -71136,7 +71055,7 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeCloseBrace);
rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) {
rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail);
}
@@ -71144,7 +71063,7 @@ var ts;
rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) {
rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression);
rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression);
}
@@ -71152,13 +71071,13 @@ var ts;
rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression);
rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression);
}
- if (options.insertSpaceAfterSemicolonInForStatements) {
+ if (options.InsertSpaceAfterSemicolonInForStatements) {
rules.push(this.globalRules.SpaceAfterSemicolonInFor);
}
else {
rules.push(this.globalRules.NoSpaceAfterSemicolonInFor);
}
- if (options.insertSpaceBeforeAndAfterBinaryOperators) {
+ if (options.InsertSpaceBeforeAndAfterBinaryOperators) {
rules.push(this.globalRules.SpaceBeforeBinaryOperator);
rules.push(this.globalRules.SpaceAfterBinaryOperator);
}
@@ -71166,14 +71085,14 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeBinaryOperator);
rules.push(this.globalRules.NoSpaceAfterBinaryOperator);
}
- if (options.placeOpenBraceOnNewLineForControlBlocks) {
+ if (options.PlaceOpenBraceOnNewLineForControlBlocks) {
rules.push(this.globalRules.NewLineBeforeOpenBraceInControl);
}
- if (options.placeOpenBraceOnNewLineForFunctions) {
+ if (options.PlaceOpenBraceOnNewLineForFunctions) {
rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction);
rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock);
}
- if (options.insertSpaceAfterTypeAssertion) {
+ if (options.InsertSpaceAfterTypeAssertion) {
rules.push(this.globalRules.SpaceAfterTypeAssertion);
}
else {
@@ -71413,7 +71332,7 @@ var ts;
break;
}
if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) {
- return options.indentSize;
+ return options.IndentSize;
}
previousLine = line;
child = n;
@@ -71485,7 +71404,7 @@ var ts;
}
function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) {
var indentation = inheritedIndentation;
- var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0;
+ var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0;
if (effectiveParentStartLine === startLine) {
// if node is located on the same line with the parent
// - inherit indentation from the parent
@@ -71493,7 +71412,7 @@ var ts;
indentation = startLine === lastIndentedLine
? indentationOnLastIndentedLine
: parentDynamicIndentation.getIndentation();
- delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta);
+ delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta);
}
else if (indentation === -1 /* Unknown */) {
if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
@@ -71574,13 +71493,13 @@ var ts;
recomputeIndentation: function (lineAdded) {
if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) {
if (lineAdded) {
- indentation += options.indentSize;
+ indentation += options.IndentSize;
}
else {
- indentation -= options.indentSize;
+ indentation -= options.IndentSize;
}
if (formatting.SmartIndenter.shouldIndentChildNode(node)) {
- delta = options.indentSize;
+ delta = options.IndentSize;
}
else {
delta = 0;
@@ -72000,7 +71919,7 @@ var ts;
// edit should not be applied only if we have one line feed between elements
var lineDelta = currentStartLine - previousStartLine;
if (lineDelta !== 1) {
- recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter);
+ recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter);
}
break;
case 2 /* Space */:
@@ -72061,14 +71980,14 @@ var ts;
var internedSpacesIndentation;
function getIndentationString(indentation, options) {
// reset interned strings if FormatCodeOptions were changed
- var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize);
+ var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize);
if (resetInternedStrings) {
- internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize };
+ 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;
+ if (!options.ConvertTabsToSpaces) {
+ var tabs = Math.floor(indentation / options.TabSize);
+ var spaces = indentation - tabs * options.TabSize;
var tabString = void 0;
if (!internedTabsIndentation) {
internedTabsIndentation = [];
@@ -72083,13 +72002,13 @@ var ts;
}
else {
var spacesString = void 0;
- var quotient = Math.floor(indentation / options.indentSize);
- var remainder = indentation % options.indentSize;
+ var quotient = Math.floor(indentation / options.IndentSize);
+ var remainder = indentation % options.IndentSize;
if (!internedSpacesIndentation) {
internedSpacesIndentation = [];
}
if (internedSpacesIndentation[quotient] === undefined) {
- spacesString = repeat(" ", options.indentSize * quotient);
+ spacesString = repeat(" ", options.IndentSize * quotient);
internedSpacesIndentation[quotient] = spacesString;
}
else {
@@ -72126,7 +72045,7 @@ var ts;
}
// no indentation when the indent style is set to none,
// so we can return fast
- if (options.indentStyle === ts.IndentStyle.None) {
+ if (options.IndentStyle === ts.IndentStyle.None) {
return 0;
}
var precedingToken = ts.findPrecedingToken(position, sourceFile);
@@ -72142,7 +72061,7 @@ var ts;
// 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) {
+ 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;
@@ -72176,7 +72095,7 @@ var ts;
indentationDelta = 0;
}
else {
- indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0;
+ indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0;
}
break;
}
@@ -72187,7 +72106,7 @@ var ts;
}
actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options);
if (actualIndentation !== -1 /* Unknown */) {
- return actualIndentation + options.indentSize;
+ return actualIndentation + options.IndentSize;
}
previous = current;
current = current.parent;
@@ -72199,15 +72118,15 @@ var ts;
return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options);
}
SmartIndenter.getIndentation = getIndentation;
+ function getBaseIndentation(options) {
+ return options.BaseIndentSize || 0;
+ }
+ SmartIndenter.getBaseIndentation = getBaseIndentation;
function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) {
var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options);
}
SmartIndenter.getIndentationForNode = getIndentationForNode;
- function getBaseIndentation(options) {
- return options.baseIndentSize || 0;
- }
- SmartIndenter.getBaseIndentation = getBaseIndentation;
function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) {
var parent = current.parent;
var parentStart;
@@ -72242,7 +72161,7 @@ var ts;
}
// increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line
if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) {
- indentationDelta += options.indentSize;
+ indentationDelta += options.IndentSize;
}
current = parent;
currentStart = parentStart;
@@ -72452,7 +72371,7 @@ var ts;
break;
}
if (ch === 9 /* tab */) {
- column += options.tabSize + (column % options.tabSize);
+ column += options.TabSize + (column % options.TabSize);
}
else {
column++;
@@ -73066,30 +72985,6 @@ var ts;
getSignatureConstructor: function () { return SignatureObject; }
};
}
- 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;
- }
- ts.toEditorSettings = toEditorSettings;
- function isCamelCase(s) {
- return !s.length || s.charAt(0) === s.charAt(0).toLowerCase();
- }
function displayPartsToString(displayParts) {
if (displayParts) {
return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join("");
@@ -73658,12 +73553,12 @@ var ts;
return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments);
}
/// NavigateTo
- function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) {
+ function getNavigateToItems(searchValue, maxResultCount, fileName) {
synchronizeHostData();
var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles();
- return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles);
+ return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount);
}
- function getEmitOutput(fileName, emitOnlyDtsFiles) {
+ function getEmitOutput(fileName) {
synchronizeHostData();
var sourceFile = getValidSourceFile(fileName);
var outputFiles = [];
@@ -73674,7 +73569,7 @@ var ts;
text: data
});
}
- var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles);
+ var emitOutput = program.emit(sourceFile, writeFile, cancellationToken);
return {
outputFiles: outputFiles,
emitSkipped: emitOutput.emitSkipped
@@ -73820,35 +73715,31 @@ var ts;
}
function getIndentationAtPosition(fileName, position, editorOptions) {
var start = ts.timestamp();
- var settings = toEditorSettings(editorOptions);
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start));
start = ts.timestamp();
- var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings);
+ var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions);
log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start));
return result;
}
function getFormattingEditsForRange(fileName, start, end, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
- return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options);
}
function getFormattingEditsForDocument(fileName, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
- return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options);
}
function getFormattingEditsAfterKeystroke(fileName, position, key, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
if (key === "}") {
- return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options);
}
else if (key === ";") {
- return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options);
}
else if (key === "\n") {
- return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options);
}
return [];
}
@@ -74821,12 +74712,6 @@ var ts;
}
return this.shimHost.getProjectVersion();
};
- LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () {
- if (!this.shimHost.getTypeRootsVersion) {
- return 0;
- }
- return this.shimHost.getTypeRootsVersion();
- };
LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () {
return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
};
@@ -75510,5 +75395,5 @@ var TypeScript;
// 'toolsVersion' gets consumed by the managed side, so it's not unused.
// TODO: it should be moved into a namespace though.
/* @internal */
-var toolsVersion = "2.0";
+var toolsVersion = "2.1";
/* tslint:enable:no-unused-variable */
diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts
index 9757e538f3b..e9c209674b5 100644
--- a/lib/typescriptServices.d.ts
+++ b/lib/typescriptServices.d.ts
@@ -29,7 +29,6 @@ declare namespace ts {
contains(fileName: Path): boolean;
remove(fileName: Path): void;
forEachValue(f: (key: Path, v: T) => void): void;
- getKeys(): Path[];
clear(): void;
}
interface TextRange {
@@ -1246,7 +1245,7 @@ declare namespace ts {
* used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter
* will be invoked when writing the JavaScript and declaration files.
*/
- emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult;
+ emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult;
getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
@@ -1373,7 +1372,6 @@ declare namespace ts {
UseFullyQualifiedType = 128,
InFirstTypeArgument = 256,
InTypeAlias = 512,
- UseTypeAliasValue = 1024,
}
enum SymbolFormatFlags {
None = 0,
@@ -1744,7 +1742,6 @@ declare namespace ts {
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: MapLike;
- compileOnSave?: boolean;
}
enum WatchDirectoryFlags {
None = 0,
@@ -1947,6 +1944,10 @@ declare namespace ts {
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
+ /** The version of the TypeScript compiler release */
+ const version = "2.1.0";
+ function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string;
+ function resolveTripleslashReference(moduleName: string, containingFile: string): string;
function getEffectiveTypeRoots(options: CompilerOptions, host: {
directoryExists?: (directoryName: string) => boolean;
getCurrentDirectory?: () => string;
@@ -1957,24 +1958,9 @@ declare namespace ts {
* is assumed to be the same as root directory of the project.
*/
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
- /**
- * Given a set of options, returns the set of type directive names
- * that should be included for this program automatically.
- * This list could either come from the config file,
- * or from enumerating the types root + initial secondary types lookup location.
- * More type directives might appear in the program later as a result of loading actual source files;
- * this list is only the set of defaults that are implicitly included.
- */
- function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[];
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
-}
-declare namespace ts {
- /** The version of the TypeScript compiler release */
- const version = "2.0.5";
- function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string;
- function resolveTripleslashReference(moduleName: string, containingFile: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
interface FormatDiagnosticsHost {
@@ -1984,6 +1970,15 @@ declare namespace ts {
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
+ /**
+ * Given a set of options, returns the set of type directive names
+ * that should be included for this program automatically.
+ * This list could either come from the config file,
+ * or from enumerating the types root + initial secondary types lookup location.
+ * More type directives might appear in the program later as a result of loading actual source files;
+ * this list is only the set of defaults that are implicitly included.
+ */
+ function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[];
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
declare namespace ts {
@@ -2000,7 +1995,7 @@ declare namespace ts {
* @param fileName The path to the config file
* @param jsonText The text of the config file
*/
- function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): {
+ function parseConfigFileTextToJson(fileName: string, jsonText: string): {
config?: any;
error?: Diagnostic;
};
@@ -2012,13 +2007,12 @@ declare namespace ts {
* file to. e.g. outDir
*/
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine;
- function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
};
function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
- options: TypingOptions;
+ options: CompilerOptions;
errors: Diagnostic[];
};
}
@@ -2161,18 +2155,18 @@ declare namespace ts {
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[];
/** @deprecated */
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[];
- getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[];
+ getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[];
getNavigationBarItems(fileName: string): NavigationBarItem[];
getOutliningSpans(fileName: string): OutliningSpan[];
getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[];
getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[];
- getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number;
- getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[];
- getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[];
- getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[];
+ getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number;
+ getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[];
+ getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[];
+ getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[];
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
- getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput;
+ getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
dispose(): void;
}
@@ -2252,11 +2246,6 @@ declare namespace ts {
containerName: string;
containerKind: string;
}
- enum IndentStyle {
- None = 0,
- Block = 1,
- Smart = 2,
- }
interface EditorOptions {
BaseIndentSize?: number;
IndentSize: number;
@@ -2265,13 +2254,10 @@ declare namespace ts {
ConvertTabsToSpaces: boolean;
IndentStyle: IndentStyle;
}
- interface EditorSettings {
- baseIndentSize?: number;
- indentSize: number;
- tabSize: number;
- newLineCharacter: string;
- convertTabsToSpaces: boolean;
- indentStyle: IndentStyle;
+ enum IndentStyle {
+ None = 0,
+ Block = 1,
+ Smart = 2,
}
interface FormatCodeOptions extends EditorOptions {
InsertSpaceAfterCommaDelimiter: boolean;
@@ -2287,21 +2273,7 @@ declare namespace ts {
InsertSpaceAfterTypeAssertion?: boolean;
PlaceOpenBraceOnNewLineForFunctions: boolean;
PlaceOpenBraceOnNewLineForControlBlocks: boolean;
- }
- interface FormatCodeSettings extends EditorSettings {
- insertSpaceAfterCommaDelimiter: boolean;
- insertSpaceAfterSemicolonInForStatements: boolean;
- insertSpaceBeforeAndAfterBinaryOperators: boolean;
- insertSpaceAfterKeywordsInControlFlowStatements: boolean;
- insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean;
- insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean;
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean;
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean;
- insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean;
- insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: boolean;
- insertSpaceAfterTypeAssertion?: boolean;
- placeOpenBraceOnNewLineForFunctions: boolean;
- placeOpenBraceOnNewLineForControlBlocks: boolean;
+ [s: string]: boolean | number | string | undefined;
}
interface DefinitionInfo {
fileName: string;
@@ -2715,7 +2687,6 @@ declare namespace ts {
interface DisplayPartsSymbolWriter extends SymbolWriter {
displayParts(): SymbolDisplayPart[];
}
- function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings;
function displayPartsToString(displayParts: SymbolDisplayPart[]): string;
function getDefaultCompilerOptions(): CompilerOptions;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile;
diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js
index 0985c69c169..14fbdce59a8 100644
--- a/lib/typescriptServices.js
+++ b/lib/typescriptServices.js
@@ -502,7 +502,6 @@ var ts;
TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType";
TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument";
TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias";
- TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue";
})(ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
var TypeFormatFlags = ts.TypeFormatFlags;
(function (SymbolFormatFlags) {
@@ -1165,7 +1164,6 @@ var ts;
contains: contains,
remove: remove,
forEachValue: forEachValueInMap,
- getKeys: getKeys,
clear: clear
};
function forEachValueInMap(f) {
@@ -1173,13 +1171,6 @@ var ts;
f(key, files[key]);
}
}
- function getKeys() {
- var keys = [];
- for (var key in files) {
- keys.push(key);
- }
- return keys;
- }
// path should already be well-formed so it does not need to be normalized
function get(path) {
return files[toKey(path)];
@@ -1510,7 +1501,6 @@ var ts;
return array1.concat(array2);
}
ts.concatenate = concatenate;
- // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication.
function deduplicate(array, areEqual) {
var result;
if (array) {
@@ -1614,22 +1604,16 @@ var ts;
* @param array A sorted array whose first element must be no larger than number
* @param number The value to be searched for in the array.
*/
- function binarySearch(array, value, comparer) {
- if (!array || array.length === 0) {
- return -1;
- }
+ function binarySearch(array, value) {
var low = 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) {
+ if (midValue === value) {
return middle;
}
- else if (comparer(midValue, value) > 0) {
+ else if (midValue > value) {
high = middle - 1;
}
else {
@@ -2194,49 +2178,10 @@ var ts;
return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1;
}
ts.isUrl = isUrl;
- 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);
- }
- ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
- function getEmitScriptTarget(compilerOptions) {
- return compilerOptions.target || 0 /* ES3 */;
- }
- ts.getEmitScriptTarget = getEmitScriptTarget;
- function getEmitModuleKind(compilerOptions) {
- return typeof compilerOptions.module === "number" ?
- compilerOptions.module :
- getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS;
- }
- ts.getEmitModuleKind = getEmitModuleKind;
- /* @internal */
- 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;
- }
- ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
function isRootedDiskPath(path) {
return getRootLength(path) !== 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
- function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
- return !isRootedDiskPath(absoluteOrRelativePath)
- ? absoluteOrRelativePath
- : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false);
- }
- ts.convertToRelativePath = convertToRelativePath;
function normalizedPathComponents(path, rootLength) {
var normalizedParts = getNormalizedParts(path, rootLength);
return [path.substr(0, rootLength)].concat(normalizedParts);
@@ -2680,14 +2625,6 @@ var ts;
return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
ts.getSupportedExtensions = getSupportedExtensions;
- function hasJavaScriptFileExtension(fileName) {
- return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
- }
- ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
- function hasTypeScriptFileExtension(fileName) {
- return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
- }
- ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension;
function isSupportedSourceFileName(fileName, compilerOptions) {
if (!fileName) {
return false;
@@ -2899,12 +2836,6 @@ var ts;
: (function (fileName) { return fileName.toLowerCase(); });
}
ts.createGetCanonicalFileName = createGetCanonicalFileName;
- function positionIsSynthesized(pos) {
- // This is a fast way of testing the following conditions:
- // pos === undefined || pos === null || isNaN(pos) || pos < 0;
- return !(pos >= 0);
- }
- ts.positionIsSynthesized = positionIsSynthesized;
})(ts || (ts = {}));
///
var ts;
@@ -3368,40 +3299,20 @@ var ts;
realpath: realpath
};
}
- function recursiveCreateDirectory(directoryPath, sys) {
- var basePath = ts.getDirectoryPath(directoryPath);
- var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath);
- if (shouldCreateParent) {
- recursiveCreateDirectory(basePath, sys);
- }
- if (shouldCreateParent || !sys.directoryExists(directoryPath)) {
- sys.createDirectory(directoryPath);
- }
- }
- var sys;
if (typeof ChakraHost !== "undefined") {
- sys = getChakraSystem();
+ return getChakraSystem();
}
else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
- sys = getWScriptSystem();
+ return getWScriptSystem();
}
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
// process and process.nextTick checks if current environment is node-like
// process.browser check excludes webpack and browserify
- sys = getNodeSystem();
+ return getNodeSystem();
}
- if (sys) {
- // patch writefile to create folder before writing the file
- var originalWriteFile_1 = sys.writeFile;
- sys.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);
- };
+ else {
+ return undefined; // Unsupported host
}
- return sys;
})();
})(ts || (ts = {}));
//
@@ -4124,7 +4035,6 @@ var ts;
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." },
Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." },
- Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -7078,6 +6988,12 @@ var ts;
return false;
}
ts.isPartOfExpression = isPartOfExpression;
+ 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);
+ }
+ ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
var moduleState = ts.getModuleInstanceState(node);
return moduleState === 1 /* Instantiated */ ||
@@ -7739,10 +7655,16 @@ var ts;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(node) {
- return ts.positionIsSynthesized(node.pos)
- || ts.positionIsSynthesized(node.end);
+ return positionIsSynthesized(node.pos)
+ || positionIsSynthesized(node.end);
}
ts.nodeIsSynthesized = nodeIsSynthesized;
+ function positionIsSynthesized(pos) {
+ // This is a fast way of testing the following conditions:
+ // pos === undefined || pos === null || isNaN(pos) || pos < 0;
+ return !(pos >= 0);
+ }
+ ts.positionIsSynthesized = positionIsSynthesized;
function getOriginalNode(node) {
if (node) {
while (node.original !== undefined) {
@@ -8203,12 +8125,24 @@ var ts;
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";
+ if (options.declaration) {
+ var path = outputDir
+ ? getSourceFilePathInNewDir(sourceFile, host, outputDir)
+ : sourceFile.fileName;
+ return ts.removeFileExtension(path) + ".d.ts";
+ }
}
ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
+ function getEmitScriptTarget(compilerOptions) {
+ return compilerOptions.target || 0 /* ES3 */;
+ }
+ ts.getEmitScriptTarget = getEmitScriptTarget;
+ function getEmitModuleKind(compilerOptions) {
+ return typeof compilerOptions.module === "number" ?
+ compilerOptions.module :
+ getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS;
+ }
+ ts.getEmitModuleKind = getEmitModuleKind;
/**
* Gets the source files that are expected to have an emit output.
*
@@ -8221,7 +8155,7 @@ var ts;
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- var moduleKind = ts.getEmitModuleKind(options);
+ var moduleKind = getEmitModuleKind(options);
var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
var sourceFiles = host.getSourceFiles();
// Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
@@ -8250,7 +8184,7 @@ var ts;
* @param sourceFiles The transformed source files to emit.
* @param action The action to execute.
*/
- function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) {
+ function forEachTransformedEmitFile(host, sourceFiles, action) {
var options = host.getCompilerOptions();
// Emit on each source file
if (options.outFile || options.out) {
@@ -8283,7 +8217,7 @@ var ts;
}
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && emitOnlyDtsFiles ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
+ var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false);
}
function onBundledEmit(host, sourceFiles) {
@@ -8308,7 +8242,7 @@ var ts;
* @param action The action to execute.
* @param targetSourceFile An optional target source file to emit.
*/
- function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) {
+ function forEachExpectedEmitFile(host, action, targetSourceFile) {
var options = host.getCompilerOptions();
// Emit on each source file
if (options.outFile || options.out) {
@@ -8341,13 +8275,12 @@ var ts;
}
}
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
var emitFileNames = {
jsFilePath: jsFilePath,
sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
- declarationFilePath: declarationFilePath
+ declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined
};
- action(emitFileNames, [sourceFile], /*isBundledEmit*/ false, emitOnlyDtsFiles);
+ action(emitFileNames, [sourceFile], /*isBundledEmit*/ false);
}
function onBundledEmit(host) {
// Can emit only sources that are not declaration file and are either non module code or module with
@@ -8355,7 +8288,7 @@ var ts;
var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) &&
!host.isSourceFileFromExternalLibrary(sourceFile) &&
(!ts.isExternalModule(sourceFile) ||
- !!ts.getEmitModuleKind(options)); });
+ !!getEmitModuleKind(options)); });
if (bundledSources.length) {
var jsFilePath = options.outFile || options.out;
var emitFileNames = {
@@ -8363,7 +8296,7 @@ var ts;
sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined
};
- action(emitFileNames, bundledSources, /*isBundledEmit*/ true, emitOnlyDtsFiles);
+ action(emitFileNames, bundledSources, /*isBundledEmit*/ true);
}
}
}
@@ -8767,6 +8700,14 @@ var ts;
return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined;
}
ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
+ function hasJavaScriptFileExtension(fileName) {
+ return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
+ function hasTypeScriptFileExtension(fileName) {
+ return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension;
/** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
function tryExtractTypeScriptExtension(fileName) {
return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
@@ -8879,6 +8820,12 @@ var ts;
return result;
}
ts.convertToBase64 = convertToBase64;
+ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
+ return !ts.isRootedDiskPath(absoluteOrRelativePath)
+ ? absoluteOrRelativePath
+ : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false);
+ }
+ ts.convertToRelativePath = convertToRelativePath;
var carriageReturnLineFeed = "\r\n";
var lineFeed = "\n";
function getNewLineCharacter(options) {
@@ -8991,7 +8938,7 @@ var ts;
* @param value The delta.
*/
function movePos(pos, value) {
- return ts.positionIsSynthesized(pos) ? -1 : pos + value;
+ return positionIsSynthesized(pos) ? -1 : pos + value;
}
ts.movePos = movePos;
/**
@@ -9107,7 +9054,7 @@ var ts;
}
ts.positionsAreOnSameLine = positionsAreOnSameLine;
function getStartPositionOfRange(range, sourceFile) {
- return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
+ return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
}
ts.getStartPositionOfRange = getStartPositionOfRange;
function collectExternalModuleInfo(sourceFile, resolver) {
@@ -18875,731 +18822,7 @@ var ts;
})(InvalidPosition || (InvalidPosition = {}));
})(IncrementalParser || (IncrementalParser = {}));
})(ts || (ts = {}));
-///
-///
-var ts;
-(function (ts) {
- function trace(host, message) {
- host.trace(ts.formatMessage.apply(undefined, arguments));
- }
- ts.trace = trace;
- /* @internal */
- function isTraceEnabled(compilerOptions, host) {
- return compilerOptions.traceResolution && host.trace !== undefined;
- }
- ts.isTraceEnabled = isTraceEnabled;
- /* @internal */
- function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) {
- return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
- }
- ts.createResolvedModule = createResolvedModule;
- function moduleHasNonRelativeName(moduleName) {
- return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
- }
- function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
- var jsonContent = readJson(packageJsonPath, state.host);
- function tryReadFromField(fieldName) {
- if (ts.hasProperty(jsonContent, fieldName)) {
- var typesFile = jsonContent[fieldName];
- if (typeof typesFile === "string") {
- var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1);
- }
- return typesFilePath_1;
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
- }
- }
- }
- }
- var typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
- if (typesFilePath) {
- return typesFilePath;
- }
- // Use the main module for inferring types if no types package specified and the allowJs is set
- if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main);
- }
- var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main));
- return mainFilePath;
- }
- return undefined;
- }
- function readJson(path, host) {
- try {
- var jsonText = host.readFile(path);
- return jsonText ? JSON.parse(jsonText) : {};
- }
- catch (e) {
- // gracefully handle if readFile fails or returns not JSON
- return {};
- }
- }
- var typeReferenceExtensions = [".d.ts"];
- 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();
- }
- return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
- }
- ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
- /**
- * Returns the path to every node_modules/@types directory from some ancestor directory.
- * Returns undefined if there are none.
- */
- function getDefaultTypeRoots(currentDirectory, host) {
- if (!host.directoryExists) {
- return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
- }
- var typeRoots;
- while (true) {
- var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes);
- if (host.directoryExists(atTypes)) {
- (typeRoots || (typeRoots = [])).push(atTypes);
- }
- var parent_6 = ts.getDirectoryPath(currentDirectory);
- if (parent_6 === currentDirectory) {
- break;
- }
- currentDirectory = parent_6;
- }
- return typeRoots;
- }
- var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
- /**
- * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
- * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
- * is assumed to be the same as root directory of the project.
- */
- function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
- var traceEnabled = isTraceEnabled(options, host);
- var moduleResolutionState = {
- compilerOptions: options,
- host: host,
- skipTsx: true,
- 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 = [];
- // Check primary library paths
- if (typeRoots && typeRoots.length) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
- }
- var primarySearchPaths = typeRoots;
- for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) {
- var typeRoot = primarySearchPaths_1[_i];
- var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
- var candidateDirectory = ts.getDirectoryPath(candidate);
- var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState);
- if (resolvedFile_1) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true);
- }
- return {
- resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 },
- failedLookupLocations: failedLookupLocations
- };
- }
- }
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
- }
- }
- var resolvedFile;
- var initialLocationForSecondaryLookup;
- if (containingFile) {
- initialLocationForSecondaryLookup = 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);
- }
- resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*checkOneLevel*/ false);
- if (traceEnabled) {
- if (resolvedFile) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
- }
- else {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
- }
- }
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
- }
- }
- return {
- resolvedTypeReferenceDirective: resolvedFile
- ? { primary: false, resolvedFileName: resolvedFile }
- : undefined,
- failedLookupLocations: failedLookupLocations
- };
- }
- ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
- /**
- * Given a set of options, returns the set of type directive names
- * that should be included for this program automatically.
- * This list could either come from the config file,
- * or from enumerating the types root + initial secondary types lookup location.
- * More type directives might appear in the program later as a result of loading actual source files;
- * this list is only the set of defaults that are implicitly included.
- */
- 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;
- }
- ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
- function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
- }
- 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]);
- }
- }
- var result;
- switch (moduleResolution) {
- case ts.ModuleResolutionKind.NodeJs:
- result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
- case ts.ModuleResolutionKind.Classic:
- result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
- }
- 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;
- }
- ts.resolveModuleName = resolveModuleName;
- /**
- * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
- * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
- * can be resolved successfully by TypeScript compiler and runtime module loader.
- * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
- * fallback to standard resolution routine.
- *
- * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
- * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
- * be '/a/b/c/d'
- * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
- * will be resolved based on the content of the module name.
- * Structure of 'paths' compiler options
- * 'paths': {
- * pattern-1: [...substitutions],
- * pattern-2: [...substitutions],
- * ...
- * pattern-n: [...substitutions]
- * }
- * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
- * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
- * If pattern contains '*' then to match pattern "*" module name must start with the and end with .
- * denotes part of the module name between and .
- * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
- * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
- * from the candidate location.
- * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
- * substitution in the list and replace '*' with string. If candidate location is not rooted it
- * will be converted to absolute using baseUrl.
- * For example:
- * baseUrl: /a/b/c
- * "paths": {
- * // match all module names
- * "*": [
- * "*", // use matched name as is,
- * // will be looked as /a/b/c/
- *
- * "folder1/*" // substitution will convert matched name to 'folder1/',
- * // since it is not rooted then final candidate location will be /a/b/c/folder1/
- * ],
- * // match module names that start with 'components/'
- * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/',
- * // it is rooted so it will be final candidate location
- * }
- *
- * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
- * they were in the same location. For example lets say there are two files
- * '/local/src/content/file1.ts'
- * '/shared/components/contracts/src/content/protocols/file2.ts'
- * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
- * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
- * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
- * root dirs were merged together.
- * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
- * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
- * '/local/src/content/protocols/file2' and try to load it - failure.
- * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
- * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
- * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
- */
- function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
- if (moduleHasNonRelativeName(moduleName)) {
- return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
- }
- else {
- return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
- }
- }
- function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
- if (!state.compilerOptions.rootDirs) {
- return undefined;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
- }
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- var matchedRootDir;
- var matchedNormalizedPrefix;
- for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
- var rootDir = _a[_i];
- // rootDirs are expected to be absolute
- // in case of tsconfig.json this will happen automatically - compiler will expand relative names
- // using location of tsconfig.json as base location
- var normalizedRoot = ts.normalizePath(rootDir);
- if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
- normalizedRoot += ts.directorySeparator;
- }
- var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
- (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
- }
- if (isLongestMatchingPrefix) {
- matchedNormalizedPrefix = normalizedRoot;
- matchedRootDir = rootDir;
- }
- }
- if (matchedNormalizedPrefix) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
- }
- var suffix = candidate.substr(matchedNormalizedPrefix.length);
- // first - try to load from a initial location
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
- }
- var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
- if (resolvedFileName) {
- return resolvedFileName;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
- }
- // then try to resolve using remaining entries in rootDirs
- for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
- var rootDir = _c[_b];
- if (rootDir === matchedRootDir) {
- // skip the initially matched entry
- continue;
- }
- var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
- }
- var baseDirectory = ts.getDirectoryPath(candidate_1);
- var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
- if (resolvedFileName_1) {
- return resolvedFileName_1;
- }
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
- }
- }
- return undefined;
- }
- function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) {
- if (!state.compilerOptions.baseUrl) {
- return undefined;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
- }
- // string is for exact match
- var matchedPattern = undefined;
- if (state.compilerOptions.paths) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
- }
- matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
- }
- if (matchedPattern) {
- var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
- var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
- }
- for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) {
- var subst = _a[_i];
- var path = matchedStar ? subst.replace("*", matchedStar) : subst;
- var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
- }
- var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- if (resolvedFileName) {
- return resolvedFileName;
- }
- }
- return undefined;
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
- }
- return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- }
- }
- /**
- * patternStrings contains both pattern strings (containing "*") and regular strings.
- * Return an exact match if possible, or a pattern match, or undefined.
- * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
- */
- 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);
- }
- function patternText(_a) {
- var prefix = _a.prefix, suffix = _a.suffix;
- return prefix + "*" + suffix;
- }
- /**
- * Given that candidate matches pattern, returns the text matching the '*'.
- * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
- */
- function matchedText(pattern, candidate) {
- ts.Debug.assert(isPatternMatch(pattern, candidate));
- return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
- }
- /** Return the object corresponding to the best pattern to match `candidate`. */
- /* @internal */
- 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;
- }
- ts.findBestPatternMatch = findBestPatternMatch;
- function isPatternMatch(_a, candidate) {
- var prefix = _a.prefix, suffix = _a.suffix;
- return candidate.length >= prefix.length + suffix.length &&
- ts.startsWith(candidate, prefix) &&
- ts.endsWith(candidate, suffix);
- }
- /* @internal */
- function tryParsePattern(pattern) {
- // This should be verified outside of here and a proper error thrown.
- ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern));
- var indexOfStar = pattern.indexOf("*");
- return indexOfStar === -1 ? undefined : {
- prefix: pattern.substr(0, indexOfStar),
- suffix: pattern.substr(indexOfStar + 1)
- };
- }
- ts.tryParsePattern = tryParsePattern;
- function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var failedLookupLocations = [];
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false };
- var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state);
- var isExternalLibraryImport = false;
- if (!resolvedFileName) {
- if (moduleHasNonRelativeName(moduleName)) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
- }
- resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, /*checkOneLevel*/ false);
- isExternalLibraryImport = resolvedFileName !== undefined;
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
- }
- }
- if (resolvedFileName && host.realpath) {
- var originalFileName = resolvedFileName;
- resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName));
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName);
- }
- }
- return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
- }
- ts.nodeModuleNameResolver = nodeModuleNameResolver;
- function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
- }
- var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
- return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
- }
- /* @internal */
- function directoryProbablyExists(directoryName, host) {
- // if host does not support 'directoryExists' assume that directory will exist
- return !host.directoryExists || host.directoryExists(directoryName);
- }
- ts.directoryProbablyExists = directoryProbablyExists;
- /**
- * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
- * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
- */
- function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
- // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
- var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
- if (resolvedByAddingExtension) {
- return resolvedByAddingExtension;
- }
- // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
- // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
- if (ts.hasJavaScriptFileExtension(candidate)) {
- var extensionless = ts.removeFileExtension(candidate);
- if (state.traceEnabled) {
- var extension = candidate.substring(extensionless.length);
- trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
- }
- return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
- }
- }
- /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
- function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
- if (!onlyRecordFailures) {
- // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
- var directory = ts.getDirectoryPath(candidate);
- if (directory) {
- onlyRecordFailures = !directoryProbablyExists(directory, state.host);
- }
- }
- return ts.forEach(extensions, function (ext) {
- return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state);
- });
- }
- /** Return the file if it exists. */
- function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) {
- if (!onlyRecordFailures && state.host.fileExists(fileName)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
- }
- return fileName;
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
- }
- failedLookupLocation.push(fileName);
- return undefined;
- }
- }
- function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) {
- var packageJsonPath = pathToPackageJson(candidate);
- var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
- if (directoryExists && state.host.fileExists(packageJsonPath)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
- }
- var typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
- if (typesFile) {
- var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host);
- // A package.json "typings" may specify an exact filename, or may choose to omit an extension.
- var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) ||
- tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state);
- if (result) {
- return result;
- }
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field);
- }
- }
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
- }
- // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
- failedLookupLocation.push(packageJsonPath);
- }
- return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
- }
- function pathToPackageJson(directory) {
- return ts.combinePaths(directory, "package.json");
- }
- function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) {
- var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
- var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
- var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
- var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions);
- var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
- if (result) {
- return result;
- }
- result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
- if (result) {
- return result;
- }
- }
- /* @internal */
- function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) {
- directory = ts.normalizeSlashes(directory);
- while (true) {
- var baseName = ts.getBaseFileName(directory);
- if (baseName !== "node_modules") {
- // Try to load source from the package
- var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
- if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
- // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package
- return packageResult;
- }
- else {
- // Else prefer a types package over non-TypeScript results (e.g. JavaScript files)
- var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
- if (typesResult || packageResult) {
- return typesResult || packageResult;
- }
- }
- }
- var parentPath = ts.getDirectoryPath(directory);
- if (parentPath === directory || checkOneLevel) {
- break;
- }
- directory = parentPath;
- }
- return undefined;
- }
- ts.loadModuleFromNodeModules = loadModuleFromNodeModules;
- function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
- var failedLookupLocations = [];
- var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
- if (resolvedFileName) {
- return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations);
- }
- var referencedSourceFile;
- if (moduleHasNonRelativeName(moduleName)) {
- while (true) {
- var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
- if (referencedSourceFile) {
- break;
- }
- var parentPath = ts.getDirectoryPath(containingDirectory);
- if (parentPath === containingDirectory) {
- break;
- }
- containingDirectory = parentPath;
- }
- }
- else {
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
- }
- return referencedSourceFile
- ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations }
- : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
- }
- ts.classicNameResolver = classicNameResolver;
-})(ts || (ts = {}));
///
-///
///
/* @internal */
var ts;
@@ -21380,12 +20603,12 @@ var ts;
return;
}
else {
- var parent_7 = node.parent;
- if (!ts.isExternalModule(parent_7)) {
+ var parent_6 = node.parent;
+ if (!ts.isExternalModule(parent_6)) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files));
return;
}
- if (!parent_7.isDeclarationFile) {
+ if (!parent_6.isDeclarationFile) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files));
return;
}
@@ -24184,9 +23407,9 @@ var ts;
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
// Go up and add our parent.
- var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
- if (parent_8) {
- walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
+ var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
+ if (parent_7) {
+ walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
}
}
if (accessibleSymbolChain) {
@@ -24326,14 +23549,14 @@ var ts;
while (i < length_1) {
// Find group of type arguments for type parameters with the same declaring container.
var start = i;
- var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
+ var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
do {
i++;
- } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9);
+ } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8);
// When type parameters are their own type arguments for the whole group (i.e. we have
// the default outer type arguments), we don't show the group.
if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
- writeSymbolTypeReference(parent_9, typeArguments, start, i, flags);
+ writeSymbolTypeReference(parent_8, typeArguments, start, i, flags);
writePunctuation(writer, 21 /* DotToken */);
}
}
@@ -24737,14 +23960,14 @@ var ts;
if (ts.isExternalModuleAugmentation(node)) {
return true;
}
- var parent_10 = getDeclarationContainer(node);
+ var parent_9 = getDeclarationContainer(node);
// If the node is not exported or it is not ambient module element (except import declaration)
if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
- !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_10.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_10))) {
- return isGlobalSourceFile(parent_10);
+ !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_9.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_9))) {
+ return isGlobalSourceFile(parent_9);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
- return isDeclarationVisible(parent_10);
+ return isDeclarationVisible(parent_9);
case 145 /* PropertyDeclaration */:
case 144 /* PropertySignature */:
case 149 /* GetAccessor */:
@@ -32625,13 +31848,13 @@ var ts;
for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
var signature = signatures_2[_i];
var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
- var parent_11 = signature.declaration && signature.declaration.parent;
+ var parent_10 = signature.declaration && signature.declaration.parent;
if (!lastSymbol || symbol === lastSymbol) {
- if (lastParent && parent_11 === lastParent) {
+ if (lastParent && parent_10 === lastParent) {
index++;
}
else {
- lastParent = parent_11;
+ lastParent = parent_10;
index = cutoffIndex;
}
}
@@ -32639,7 +31862,7 @@ var ts;
// current declaration belongs to a different symbol
// set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
index = cutoffIndex = result.length;
- lastParent = parent_11;
+ lastParent = parent_10;
}
lastSymbol = symbol;
// specialized signatures always need to be placed before non-specialized signatures regardless
@@ -35165,9 +34388,9 @@ var ts;
case 156 /* FunctionType */:
case 147 /* MethodDeclaration */:
case 146 /* MethodSignature */:
- var parent_12 = node.parent;
- if (node === parent_12.type) {
- return parent_12;
+ var parent_11 = node.parent;
+ if (node === parent_11.type) {
+ return parent_11;
}
}
}
@@ -36723,12 +35946,12 @@ var ts;
checkComputedPropertyName(node.propertyName);
}
// check private/protected variable access
- var parent_13 = node.parent.parent;
- var parentType = getTypeForBindingElementParent(parent_13);
+ var parent_12 = node.parent.parent;
+ var parentType = getTypeForBindingElementParent(parent_12);
var name_21 = node.propertyName || node.name;
var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21));
- if (parent_13.initializer && property && getParentOfSymbol(property)) {
- checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property);
+ if (parent_12.initializer && property && getParentOfSymbol(property)) {
+ checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property);
}
}
// For a binding pattern, check contained binding elements
@@ -39503,9 +38726,9 @@ var ts;
if (startInDeclarationContainer) {
// When resolving the name of a declaration as a value, we need to start resolution
// at a point outside of the declaration.
- var parent_14 = reference.parent;
- if (ts.isDeclaration(parent_14) && reference === parent_14.name) {
- location = getDeclarationContainer(parent_14);
+ var parent_13 = reference.parent;
+ if (ts.isDeclaration(parent_13) && reference === parent_13.name) {
+ location = getDeclarationContainer(parent_13);
}
}
return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined);
@@ -39629,9 +38852,9 @@ var ts;
// external modules cannot define or contribute to type declaration files
var current = symbol;
while (true) {
- var parent_15 = getParentOfSymbol(current);
- if (parent_15) {
- current = parent_15;
+ var parent_14 = getParentOfSymbol(current);
+ if (parent_14) {
+ current = parent_14;
}
else {
break;
@@ -53512,11 +52735,11 @@ var ts;
return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);
function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) {
var declarationFilePath = _a.declarationFilePath;
- emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, /*emitOnlyDtsFiles*/ false);
+ emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);
}
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
- function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) {
+ function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) {
var newLine = host.getNewLine();
var compilerOptions = host.getCompilerOptions();
var write;
@@ -53563,7 +52786,7 @@ var ts;
// global file reference is added only
// - if it is not bundled emit (because otherwise it would be self reference)
// - and it is not already added
- if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) {
+ if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) {
addedGlobalFileReference = true;
}
emittedReferencedFiles.push(referencedFile);
@@ -53764,7 +52987,7 @@ var ts;
}
else {
errorNameNode = declaration.name;
- resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer);
+ resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer);
errorNameNode = undefined;
}
}
@@ -53777,7 +53000,7 @@ var ts;
}
else {
errorNameNode = signature.name;
- resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer);
+ resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer);
errorNameNode = undefined;
}
}
@@ -53979,7 +53202,7 @@ var ts;
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic;
- resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer);
+ resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer);
write(";");
writeLine();
write(node.isExportEquals ? "export = " : "export default ");
@@ -54401,7 +53624,7 @@ var ts;
}
else {
writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError;
- resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer);
+ resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer);
}
function getHeritageClauseVisibilityError(symbolAccessibilityResult) {
var diagnosticMessage;
@@ -55042,7 +54265,7 @@ var ts;
* @param referencedFile
* @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not
*/
- function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) {
+ function writeReferencePath(referencedFile, addBundledFileReference) {
var declFileName;
var addedBundledEmitReference = false;
if (ts.isDeclarationFile(referencedFile)) {
@@ -55051,7 +54274,7 @@ var ts;
}
else {
// Get the declaration file path
- ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles);
+ ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile);
}
if (declFileName) {
declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName,
@@ -55071,8 +54294,8 @@ var ts;
}
}
/* @internal */
- function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) {
- var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles);
+ function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) {
+ var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit);
var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit;
if (!emitSkipped) {
var declarationOutput = emitDeclarationResult.referencesOutput
@@ -55113,7 +54336,7 @@ var ts;
TempFlags[TempFlags["_i"] = 268435456] = "_i";
})(TempFlags || (TempFlags = {}));
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) {
+ function emitFiles(resolver, host, targetSourceFile) {
var delimiters = createDelimiterMap();
var brackets = createBracketsMap();
// emit output for the __extends helper function
@@ -55232,7 +54455,7 @@ var ts;
var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode;
ts.performance.mark("beforePrint");
// Emit each output file
- ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile, emitOnlyDtsFiles);
+ ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile);
// Clean up after transformation
transformed.dispose();
ts.performance.measure("printTime", "beforePrint");
@@ -55251,7 +54474,7 @@ var ts;
emitSkipped = true;
}
if (declarationFilePath) {
- emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped;
+ emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped;
}
if (!emitSkipped && emittedFilesList) {
emittedFilesList.push(jsFilePath);
@@ -57593,7 +56816,7 @@ var ts;
var ts;
(function (ts) {
/** The version of the TypeScript compiler release */
- ts.version = "2.0.5";
+ ts.version = "2.1.0";
var emptyArray = [];
function findConfigFile(searchPath, fileExists, configName) {
if (configName === void 0) { configName = "tsconfig.json"; }
@@ -57655,6 +56878,695 @@ var ts;
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}
ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
+ function trace(host, message) {
+ host.trace(ts.formatMessage.apply(undefined, arguments));
+ }
+ function isTraceEnabled(compilerOptions, host) {
+ return compilerOptions.traceResolution && host.trace !== undefined;
+ }
+ /* @internal */
+ 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;
+ }
+ ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) {
+ return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
+ }
+ function moduleHasNonRelativeName(moduleName) {
+ return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
+ }
+ function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
+ var jsonContent = readJson(packageJsonPath, state.host);
+ function tryReadFromField(fieldName) {
+ if (ts.hasProperty(jsonContent, fieldName)) {
+ var typesFile = jsonContent[fieldName];
+ if (typeof typesFile === "string") {
+ var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1);
+ }
+ return typesFilePath_1;
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
+ }
+ }
+ }
+ }
+ var typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
+ if (typesFilePath) {
+ return typesFilePath;
+ }
+ // Use the main module for inferring types if no types package specified and the allowJs is set
+ if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main);
+ }
+ var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main));
+ return mainFilePath;
+ }
+ return undefined;
+ }
+ function readJson(path, host) {
+ try {
+ var jsonText = host.readFile(path);
+ return jsonText ? JSON.parse(jsonText) : {};
+ }
+ catch (e) {
+ // gracefully handle if readFile fails or returns not JSON
+ return {};
+ }
+ }
+ var typeReferenceExtensions = [".d.ts"];
+ 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();
+ }
+ return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
+ }
+ ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
+ /**
+ * Returns the path to every node_modules/@types directory from some ancestor directory.
+ * Returns undefined if there are none.
+ */
+ function getDefaultTypeRoots(currentDirectory, host) {
+ if (!host.directoryExists) {
+ return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
+ }
+ var typeRoots;
+ while (true) {
+ var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes);
+ if (host.directoryExists(atTypes)) {
+ (typeRoots || (typeRoots = [])).push(atTypes);
+ }
+ var parent_15 = ts.getDirectoryPath(currentDirectory);
+ if (parent_15 === currentDirectory) {
+ break;
+ }
+ currentDirectory = parent_15;
+ }
+ return typeRoots;
+ }
+ var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
+ /**
+ * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
+ * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
+ * is assumed to be the same as root directory of the project.
+ */
+ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
+ var traceEnabled = isTraceEnabled(options, host);
+ var moduleResolutionState = {
+ compilerOptions: options,
+ host: host,
+ skipTsx: true,
+ 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 = [];
+ // Check primary library paths
+ if (typeRoots && typeRoots.length) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
+ }
+ var primarySearchPaths = typeRoots;
+ for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) {
+ var typeRoot = primarySearchPaths_1[_i];
+ var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
+ var candidateDirectory = ts.getDirectoryPath(candidate);
+ var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState);
+ if (resolvedFile_1) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true);
+ }
+ return {
+ resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 },
+ failedLookupLocations: failedLookupLocations
+ };
+ }
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
+ }
+ }
+ var resolvedFile;
+ var initialLocationForSecondaryLookup;
+ if (containingFile) {
+ initialLocationForSecondaryLookup = 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);
+ }
+ resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState);
+ if (traceEnabled) {
+ if (resolvedFile) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
+ }
+ else {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
+ }
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
+ }
+ }
+ return {
+ resolvedTypeReferenceDirective: resolvedFile
+ ? { primary: false, resolvedFileName: resolvedFile }
+ : undefined,
+ failedLookupLocations: failedLookupLocations
+ };
+ }
+ ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
+ function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
+ }
+ 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]);
+ }
+ }
+ var result;
+ switch (moduleResolution) {
+ case ts.ModuleResolutionKind.NodeJs:
+ result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
+ break;
+ case ts.ModuleResolutionKind.Classic:
+ result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
+ break;
+ }
+ 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;
+ }
+ ts.resolveModuleName = resolveModuleName;
+ /**
+ * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
+ * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
+ * can be resolved successfully by TypeScript compiler and runtime module loader.
+ * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
+ * fallback to standard resolution routine.
+ *
+ * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
+ * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
+ * be '/a/b/c/d'
+ * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
+ * will be resolved based on the content of the module name.
+ * Structure of 'paths' compiler options
+ * 'paths': {
+ * pattern-1: [...substitutions],
+ * pattern-2: [...substitutions],
+ * ...
+ * pattern-n: [...substitutions]
+ * }
+ * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
+ * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
+ * If pattern contains '*' then to match pattern "*" module name must start with the and end with .
+ * denotes part of the module name between and .
+ * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
+ * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
+ * from the candidate location.
+ * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
+ * substitution in the list and replace '*' with string. If candidate location is not rooted it
+ * will be converted to absolute using baseUrl.
+ * For example:
+ * baseUrl: /a/b/c
+ * "paths": {
+ * // match all module names
+ * "*": [
+ * "*", // use matched name as is,
+ * // will be looked as /a/b/c/
+ *
+ * "folder1/*" // substitution will convert matched name to 'folder1/',
+ * // since it is not rooted then final candidate location will be /a/b/c/folder1/
+ * ],
+ * // match module names that start with 'components/'
+ * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/',
+ * // it is rooted so it will be final candidate location
+ * }
+ *
+ * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
+ * they were in the same location. For example lets say there are two files
+ * '/local/src/content/file1.ts'
+ * '/shared/components/contracts/src/content/protocols/file2.ts'
+ * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
+ * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
+ * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
+ * root dirs were merged together.
+ * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
+ * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
+ * '/local/src/content/protocols/file2' and try to load it - failure.
+ * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
+ * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
+ * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
+ */
+ function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
+ if (moduleHasNonRelativeName(moduleName)) {
+ return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
+ }
+ else {
+ return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
+ }
+ }
+ function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) {
+ if (!state.compilerOptions.rootDirs) {
+ return undefined;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
+ }
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ var matchedRootDir;
+ var matchedNormalizedPrefix;
+ for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
+ var rootDir = _a[_i];
+ // rootDirs are expected to be absolute
+ // in case of tsconfig.json this will happen automatically - compiler will expand relative names
+ // using location of tsconfig.json as base location
+ var normalizedRoot = ts.normalizePath(rootDir);
+ if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
+ normalizedRoot += ts.directorySeparator;
+ }
+ var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
+ (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
+ }
+ if (isLongestMatchingPrefix) {
+ matchedNormalizedPrefix = normalizedRoot;
+ matchedRootDir = rootDir;
+ }
+ }
+ if (matchedNormalizedPrefix) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
+ }
+ var suffix = candidate.substr(matchedNormalizedPrefix.length);
+ // first - try to load from a initial location
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
+ }
+ var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
+ if (resolvedFileName) {
+ return resolvedFileName;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
+ }
+ // then try to resolve using remaining entries in rootDirs
+ for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
+ var rootDir = _c[_b];
+ if (rootDir === matchedRootDir) {
+ // skip the initially matched entry
+ continue;
+ }
+ var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
+ }
+ var baseDirectory = ts.getDirectoryPath(candidate_1);
+ var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
+ if (resolvedFileName_1) {
+ return resolvedFileName_1;
+ }
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
+ }
+ }
+ return undefined;
+ }
+ function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) {
+ if (!state.compilerOptions.baseUrl) {
+ return undefined;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
+ }
+ // string is for exact match
+ var matchedPattern = undefined;
+ if (state.compilerOptions.paths) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
+ }
+ matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
+ }
+ if (matchedPattern) {
+ var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
+ var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
+ }
+ for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) {
+ var subst = _a[_i];
+ var path = matchedStar ? subst.replace("*", matchedStar) : subst;
+ var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
+ }
+ var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ if (resolvedFileName) {
+ return resolvedFileName;
+ }
+ }
+ return undefined;
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
+ }
+ return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ }
+ }
+ /**
+ * patternStrings contains both pattern strings (containing "*") and regular strings.
+ * Return an exact match if possible, or a pattern match, or undefined.
+ * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
+ */
+ 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);
+ }
+ function patternText(_a) {
+ var prefix = _a.prefix, suffix = _a.suffix;
+ return prefix + "*" + suffix;
+ }
+ /**
+ * Given that candidate matches pattern, returns the text matching the '*'.
+ * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
+ */
+ function matchedText(pattern, candidate) {
+ ts.Debug.assert(isPatternMatch(pattern, candidate));
+ return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
+ }
+ /** Return the object corresponding to the best pattern to match `candidate`. */
+ /* @internal */
+ 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;
+ }
+ ts.findBestPatternMatch = findBestPatternMatch;
+ function isPatternMatch(_a, candidate) {
+ var prefix = _a.prefix, suffix = _a.suffix;
+ return candidate.length >= prefix.length + suffix.length &&
+ ts.startsWith(candidate, prefix) &&
+ ts.endsWith(candidate, suffix);
+ }
+ /* @internal */
+ function tryParsePattern(pattern) {
+ // This should be verified outside of here and a proper error thrown.
+ ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
+ var indexOfStar = pattern.indexOf("*");
+ return indexOfStar === -1 ? undefined : {
+ prefix: pattern.substr(0, indexOfStar),
+ suffix: pattern.substr(indexOfStar + 1)
+ };
+ }
+ ts.tryParsePattern = tryParsePattern;
+ function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var failedLookupLocations = [];
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false };
+ var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state);
+ var isExternalLibraryImport = false;
+ if (!resolvedFileName) {
+ if (moduleHasNonRelativeName(moduleName)) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
+ }
+ resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state);
+ isExternalLibraryImport = resolvedFileName !== undefined;
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
+ }
+ }
+ if (resolvedFileName && host.realpath) {
+ var originalFileName = resolvedFileName;
+ resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName));
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName);
+ }
+ }
+ return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
+ }
+ ts.nodeModuleNameResolver = nodeModuleNameResolver;
+ function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
+ }
+ var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
+ return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
+ }
+ /* @internal */
+ function directoryProbablyExists(directoryName, host) {
+ // if host does not support 'directoryExists' assume that directory will exist
+ return !host.directoryExists || host.directoryExists(directoryName);
+ }
+ ts.directoryProbablyExists = directoryProbablyExists;
+ /**
+ * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
+ * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
+ */
+ function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
+ // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
+ var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
+ if (resolvedByAddingExtension) {
+ return resolvedByAddingExtension;
+ }
+ // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
+ // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
+ if (ts.hasJavaScriptFileExtension(candidate)) {
+ var extensionless = ts.removeFileExtension(candidate);
+ if (state.traceEnabled) {
+ var extension = candidate.substring(extensionless.length);
+ trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
+ }
+ return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
+ }
+ }
+ /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
+ function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
+ if (!onlyRecordFailures) {
+ // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
+ var directory = ts.getDirectoryPath(candidate);
+ if (directory) {
+ onlyRecordFailures = !directoryProbablyExists(directory, state.host);
+ }
+ }
+ return ts.forEach(extensions, function (ext) {
+ return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state);
+ });
+ }
+ /** Return the file if it exists. */
+ function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) {
+ if (!onlyRecordFailures && state.host.fileExists(fileName)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
+ }
+ return fileName;
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
+ }
+ failedLookupLocation.push(fileName);
+ return undefined;
+ }
+ }
+ function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) {
+ var packageJsonPath = pathToPackageJson(candidate);
+ var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
+ if (directoryExists && state.host.fileExists(packageJsonPath)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
+ }
+ var typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
+ if (typesFile) {
+ var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host);
+ // A package.json "typings" may specify an exact filename, or may choose to omit an extension.
+ var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) ||
+ tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state);
+ if (result) {
+ return result;
+ }
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field);
+ }
+ }
+ }
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
+ }
+ // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
+ failedLookupLocation.push(packageJsonPath);
+ }
+ return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
+ }
+ function pathToPackageJson(directory) {
+ return ts.combinePaths(directory, "package.json");
+ }
+ function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) {
+ var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
+ var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
+ var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
+ var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions);
+ var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
+ if (result) {
+ return result;
+ }
+ result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
+ if (result) {
+ return result;
+ }
+ }
+ function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) {
+ directory = ts.normalizeSlashes(directory);
+ while (true) {
+ var baseName = ts.getBaseFileName(directory);
+ if (baseName !== "node_modules") {
+ // Try to load source from the package
+ var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
+ if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
+ // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package
+ return packageResult;
+ }
+ else {
+ // Else prefer a types package over non-TypeScript results (e.g. JavaScript files)
+ var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
+ if (typesResult || packageResult) {
+ return typesResult || packageResult;
+ }
+ }
+ }
+ var parentPath = ts.getDirectoryPath(directory);
+ if (parentPath === directory) {
+ break;
+ }
+ directory = parentPath;
+ }
+ return undefined;
+ }
+ function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
+ var failedLookupLocations = [];
+ var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
+ if (resolvedFileName) {
+ return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations);
+ }
+ var referencedSourceFile;
+ if (moduleHasNonRelativeName(moduleName)) {
+ while (true) {
+ var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
+ if (referencedSourceFile) {
+ break;
+ }
+ var parentPath = ts.getDirectoryPath(containingDirectory);
+ if (parentPath === containingDirectory) {
+ break;
+ }
+ containingDirectory = parentPath;
+ }
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
+ }
+ return referencedSourceFile
+ ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations }
+ : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
+ }
+ ts.classicNameResolver = classicNameResolver;
function createCompilerHost(options, setParentNodes) {
var existingDirectories = ts.createMap();
function getCanonicalFileName(fileName) {
@@ -57828,6 +57740,45 @@ var ts;
}
return resolutions;
}
+ /**
+ * Given a set of options, returns the set of type directive names
+ * that should be included for this program automatically.
+ * This list could either come from the config file,
+ * or from enumerating the types root + initial secondary types lookup location.
+ * More type directives might appear in the program later as a result of loading actual source files;
+ * this list is only the set of defaults that are implicitly included.
+ */
+ 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;
+ }
+ ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
function createProgram(rootNames, options, host, oldProgram) {
var program;
var files = [];
@@ -57864,7 +57815,7 @@ var ts;
resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); };
}
else {
- var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; };
+ var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; };
resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); };
}
var resolveTypeReferenceDirectiveNamesWorker;
@@ -57872,7 +57823,7 @@ var ts;
resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); };
}
else {
- var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; };
+ var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; };
resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); };
}
var filesByName = ts.createFileMap();
@@ -57882,7 +57833,7 @@ var ts;
if (!tryReuseStructureFromOldProgram()) {
ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); });
// load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
- var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host);
+ var typeReferences = getAutomaticTypeDirectiveNames(options, host);
if (typeReferences) {
// This containingFilename needs to match with the one used in managed-side
var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts");
@@ -57933,8 +57884,7 @@ var ts;
getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
- getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
- dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker
+ getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -58104,19 +58054,16 @@ var ts;
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
}
- function dropDiagnosticsProducingTypeChecker() {
- diagnosticsProducingTypeChecker = undefined;
- }
function getTypeChecker() {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
- function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
- return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); });
+ function emit(sourceFile, writeFileCallback, cancellationToken) {
+ return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
}
- function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
+ function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) {
var declarationDiagnostics = [];
if (options.noEmit) {
return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
@@ -58148,7 +58095,7 @@ var ts;
// checked is to not pass the file to getEmitResolver.
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
ts.performance.mark("beforeEmit");
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -58801,7 +58748,7 @@ var ts;
if (!ts.hasProperty(options.paths, key)) {
continue;
}
- if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
+ if (!hasZeroOrOneAsteriskCharacter(key)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key));
}
if (ts.isArray(options.paths[key])) {
@@ -58812,7 +58759,7 @@ var ts;
var subst = _a[_i];
var typeOfSubst = typeof subst;
if (typeOfSubst === "string") {
- if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
+ if (!hasZeroOrOneAsteriskCharacter(subst)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key));
}
}
@@ -58944,15 +58891,12 @@ var ts;
///
var ts;
(function (ts) {
- /* @internal */
- ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
/* @internal */
ts.optionDeclarations = [
{
name: "charset",
type: "string"
},
- ts.compileOnSaveCommandLineOption,
{
name: "declaration",
shortName: "d",
@@ -59603,11 +59547,10 @@ var ts;
* @param fileName The path to the config file
* @param jsonText The text of the config file
*/
- function parseConfigFileTextToJson(fileName, jsonText, stripComments) {
- if (stripComments === void 0) { stripComments = true; }
+ function parseConfigFileTextToJson(fileName, jsonText) {
try {
- var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText;
- return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} };
+ var jsonTextWithoutComments = removeComments(jsonText);
+ return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} };
}
catch (e) {
return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) };
@@ -59769,15 +59712,13 @@ var ts;
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,
typingOptions: typingOptions,
raw: json,
errors: errors,
- wildcardDirectories: wildcardDirectories,
- compileOnSave: compileOnSave
+ wildcardDirectories: wildcardDirectories
};
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)
@@ -59858,17 +59799,6 @@ var ts;
var _b;
}
ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
- 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;
- }
- ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson;
function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
var errors = [];
var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
@@ -59882,9 +59812,7 @@ var ts;
}
ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
- var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
- ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true }
- : {};
+ var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {};
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
return options;
}
@@ -61729,7 +61657,7 @@ var ts;
return ts.ensureScriptKind(fileName, scriptKind);
}
ts.getScriptKind = getScriptKind;
- function sanitizeConfigFile(configFileName, content) {
+ function parseAndReEmitConfigJSONFile(content) {
var options = {
fileName: "config.js",
compilerOptions: {
@@ -61743,17 +61671,14 @@ var ts;
// also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these
// as well
var trimmedOutput = outputText.trim();
+ var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2));
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
- };
+ return { configJsonObject: configJsonObject, diagnostics: diagnostics };
}
- ts.sanitizeConfigFile = sanitizeConfigFile;
+ ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -66506,9 +66431,7 @@ var ts;
})(ts || (ts = {}));
// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.
-///
-///
-///
+///
/* @internal */
var ts;
(function (ts) {
@@ -66519,7 +66442,6 @@ var ts;
// A map of loose file names to library names
// that we are confident require typings
var safeList;
- var EmptySafeList = ts.createMap();
/**
* @param host is the object providing I/O related operations.
* @param fileNames are the file names that belong to the same project
@@ -66536,13 +66458,10 @@ var ts;
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 */;
- });
+ fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); });
if (!safeList) {
var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
- safeList = result.config ? ts.createMap(result.config) : EmptySafeList;
+ safeList = ts.createMap(result.config);
}
var filesToWatch = [];
// Directories to search for package.json, bower.json and other typing information
@@ -66633,10 +66552,13 @@ var ts;
var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension);
var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); });
var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); });
- if (safeList !== EmptySafeList) {
+ if (safeList === undefined) {
+ mergeTypings(cleanedTypingNames);
+ }
+ else {
mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; }));
}
- var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; });
+ var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); });
if (hasJsxFile) {
mergeTypings(["react"]);
}
@@ -66651,7 +66573,7 @@ var ts;
return;
}
var typingNames = [];
- var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
+ var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
var fileName = fileNames_2[_i];
var normalizedFileName = ts.normalizePath(fileName);
@@ -66694,7 +66616,7 @@ var ts;
(function (ts) {
var NavigateTo;
(function (NavigateTo) {
- function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) {
+ function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) {
var patternMatcher = ts.createPatternMatcher(searchValue);
var rawItems = [];
// This means "compare in a case insensitive manner."
@@ -66702,9 +66624,6 @@ var ts;
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
ts.forEach(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) {
- return;
- }
var nameToDeclarations = sourceFile.getNamedDeclarations();
for (var name_49 in nameToDeclarations) {
var declarations = nameToDeclarations[name_49];
@@ -71086,25 +71005,25 @@ var ts;
};
RulesProvider.prototype.createActiveRules = function (options) {
var rules = this.globalRules.HighPriorityCommonRules.slice(0);
- if (options.insertSpaceAfterCommaDelimiter) {
+ if (options.InsertSpaceAfterCommaDelimiter) {
rules.push(this.globalRules.SpaceAfterComma);
}
else {
rules.push(this.globalRules.NoSpaceAfterComma);
}
- if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) {
+ if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) {
rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword);
}
else {
rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword);
}
- if (options.insertSpaceAfterKeywordsInControlFlowStatements) {
+ if (options.InsertSpaceAfterKeywordsInControlFlowStatements) {
rules.push(this.globalRules.SpaceAfterKeywordInControl);
}
else {
rules.push(this.globalRules.NoSpaceAfterKeywordInControl);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) {
rules.push(this.globalRules.SpaceAfterOpenParen);
rules.push(this.globalRules.SpaceBeforeCloseParen);
rules.push(this.globalRules.NoSpaceBetweenParens);
@@ -71114,7 +71033,7 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeCloseParen);
rules.push(this.globalRules.NoSpaceBetweenParens);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) {
rules.push(this.globalRules.SpaceAfterOpenBracket);
rules.push(this.globalRules.SpaceBeforeCloseBracket);
rules.push(this.globalRules.NoSpaceBetweenBrackets);
@@ -71126,7 +71045,7 @@ var ts;
}
// 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) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) {
rules.push(this.globalRules.SpaceAfterOpenBrace);
rules.push(this.globalRules.SpaceBeforeCloseBrace);
rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets);
@@ -71136,7 +71055,7 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeCloseBrace);
rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) {
rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail);
}
@@ -71144,7 +71063,7 @@ var ts;
rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail);
}
- if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) {
+ if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) {
rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression);
rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression);
}
@@ -71152,13 +71071,13 @@ var ts;
rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression);
rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression);
}
- if (options.insertSpaceAfterSemicolonInForStatements) {
+ if (options.InsertSpaceAfterSemicolonInForStatements) {
rules.push(this.globalRules.SpaceAfterSemicolonInFor);
}
else {
rules.push(this.globalRules.NoSpaceAfterSemicolonInFor);
}
- if (options.insertSpaceBeforeAndAfterBinaryOperators) {
+ if (options.InsertSpaceBeforeAndAfterBinaryOperators) {
rules.push(this.globalRules.SpaceBeforeBinaryOperator);
rules.push(this.globalRules.SpaceAfterBinaryOperator);
}
@@ -71166,14 +71085,14 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeBinaryOperator);
rules.push(this.globalRules.NoSpaceAfterBinaryOperator);
}
- if (options.placeOpenBraceOnNewLineForControlBlocks) {
+ if (options.PlaceOpenBraceOnNewLineForControlBlocks) {
rules.push(this.globalRules.NewLineBeforeOpenBraceInControl);
}
- if (options.placeOpenBraceOnNewLineForFunctions) {
+ if (options.PlaceOpenBraceOnNewLineForFunctions) {
rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction);
rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock);
}
- if (options.insertSpaceAfterTypeAssertion) {
+ if (options.InsertSpaceAfterTypeAssertion) {
rules.push(this.globalRules.SpaceAfterTypeAssertion);
}
else {
@@ -71413,7 +71332,7 @@ var ts;
break;
}
if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) {
- return options.indentSize;
+ return options.IndentSize;
}
previousLine = line;
child = n;
@@ -71485,7 +71404,7 @@ var ts;
}
function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) {
var indentation = inheritedIndentation;
- var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0;
+ var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0;
if (effectiveParentStartLine === startLine) {
// if node is located on the same line with the parent
// - inherit indentation from the parent
@@ -71493,7 +71412,7 @@ var ts;
indentation = startLine === lastIndentedLine
? indentationOnLastIndentedLine
: parentDynamicIndentation.getIndentation();
- delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta);
+ delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta);
}
else if (indentation === -1 /* Unknown */) {
if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
@@ -71574,13 +71493,13 @@ var ts;
recomputeIndentation: function (lineAdded) {
if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) {
if (lineAdded) {
- indentation += options.indentSize;
+ indentation += options.IndentSize;
}
else {
- indentation -= options.indentSize;
+ indentation -= options.IndentSize;
}
if (formatting.SmartIndenter.shouldIndentChildNode(node)) {
- delta = options.indentSize;
+ delta = options.IndentSize;
}
else {
delta = 0;
@@ -72000,7 +71919,7 @@ var ts;
// edit should not be applied only if we have one line feed between elements
var lineDelta = currentStartLine - previousStartLine;
if (lineDelta !== 1) {
- recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter);
+ recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter);
}
break;
case 2 /* Space */:
@@ -72061,14 +71980,14 @@ var ts;
var internedSpacesIndentation;
function getIndentationString(indentation, options) {
// reset interned strings if FormatCodeOptions were changed
- var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize);
+ var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize);
if (resetInternedStrings) {
- internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize };
+ 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;
+ if (!options.ConvertTabsToSpaces) {
+ var tabs = Math.floor(indentation / options.TabSize);
+ var spaces = indentation - tabs * options.TabSize;
var tabString = void 0;
if (!internedTabsIndentation) {
internedTabsIndentation = [];
@@ -72083,13 +72002,13 @@ var ts;
}
else {
var spacesString = void 0;
- var quotient = Math.floor(indentation / options.indentSize);
- var remainder = indentation % options.indentSize;
+ var quotient = Math.floor(indentation / options.IndentSize);
+ var remainder = indentation % options.IndentSize;
if (!internedSpacesIndentation) {
internedSpacesIndentation = [];
}
if (internedSpacesIndentation[quotient] === undefined) {
- spacesString = repeat(" ", options.indentSize * quotient);
+ spacesString = repeat(" ", options.IndentSize * quotient);
internedSpacesIndentation[quotient] = spacesString;
}
else {
@@ -72126,7 +72045,7 @@ var ts;
}
// no indentation when the indent style is set to none,
// so we can return fast
- if (options.indentStyle === ts.IndentStyle.None) {
+ if (options.IndentStyle === ts.IndentStyle.None) {
return 0;
}
var precedingToken = ts.findPrecedingToken(position, sourceFile);
@@ -72142,7 +72061,7 @@ var ts;
// 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) {
+ 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;
@@ -72176,7 +72095,7 @@ var ts;
indentationDelta = 0;
}
else {
- indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0;
+ indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0;
}
break;
}
@@ -72187,7 +72106,7 @@ var ts;
}
actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options);
if (actualIndentation !== -1 /* Unknown */) {
- return actualIndentation + options.indentSize;
+ return actualIndentation + options.IndentSize;
}
previous = current;
current = current.parent;
@@ -72199,15 +72118,15 @@ var ts;
return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options);
}
SmartIndenter.getIndentation = getIndentation;
+ function getBaseIndentation(options) {
+ return options.BaseIndentSize || 0;
+ }
+ SmartIndenter.getBaseIndentation = getBaseIndentation;
function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) {
var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options);
}
SmartIndenter.getIndentationForNode = getIndentationForNode;
- function getBaseIndentation(options) {
- return options.baseIndentSize || 0;
- }
- SmartIndenter.getBaseIndentation = getBaseIndentation;
function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) {
var parent = current.parent;
var parentStart;
@@ -72242,7 +72161,7 @@ var ts;
}
// increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line
if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) {
- indentationDelta += options.indentSize;
+ indentationDelta += options.IndentSize;
}
current = parent;
currentStart = parentStart;
@@ -72452,7 +72371,7 @@ var ts;
break;
}
if (ch === 9 /* tab */) {
- column += options.tabSize + (column % options.tabSize);
+ column += options.TabSize + (column % options.TabSize);
}
else {
column++;
@@ -73066,30 +72985,6 @@ var ts;
getSignatureConstructor: function () { return SignatureObject; }
};
}
- 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;
- }
- ts.toEditorSettings = toEditorSettings;
- function isCamelCase(s) {
- return !s.length || s.charAt(0) === s.charAt(0).toLowerCase();
- }
function displayPartsToString(displayParts) {
if (displayParts) {
return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join("");
@@ -73658,12 +73553,12 @@ var ts;
return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments);
}
/// NavigateTo
- function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) {
+ function getNavigateToItems(searchValue, maxResultCount, fileName) {
synchronizeHostData();
var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles();
- return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles);
+ return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount);
}
- function getEmitOutput(fileName, emitOnlyDtsFiles) {
+ function getEmitOutput(fileName) {
synchronizeHostData();
var sourceFile = getValidSourceFile(fileName);
var outputFiles = [];
@@ -73674,7 +73569,7 @@ var ts;
text: data
});
}
- var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles);
+ var emitOutput = program.emit(sourceFile, writeFile, cancellationToken);
return {
outputFiles: outputFiles,
emitSkipped: emitOutput.emitSkipped
@@ -73820,35 +73715,31 @@ var ts;
}
function getIndentationAtPosition(fileName, position, editorOptions) {
var start = ts.timestamp();
- var settings = toEditorSettings(editorOptions);
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start));
start = ts.timestamp();
- var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings);
+ var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions);
log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start));
return result;
}
function getFormattingEditsForRange(fileName, start, end, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
- return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options);
}
function getFormattingEditsForDocument(fileName, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
- return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options);
}
function getFormattingEditsAfterKeystroke(fileName, position, key, options) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var settings = toEditorSettings(options);
if (key === "}") {
- return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options);
}
else if (key === ";") {
- return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options);
}
else if (key === "\n") {
- return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings);
+ return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options);
}
return [];
}
@@ -74821,12 +74712,6 @@ var ts;
}
return this.shimHost.getProjectVersion();
};
- LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () {
- if (!this.shimHost.getTypeRootsVersion) {
- return 0;
- }
- return this.shimHost.getTypeRootsVersion();
- };
LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () {
return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
};
@@ -75510,5 +75395,5 @@ var TypeScript;
// 'toolsVersion' gets consumed by the managed side, so it's not unused.
// TODO: it should be moved into a namespace though.
/* @internal */
-var toolsVersion = "2.0";
+var toolsVersion = "2.1";
/* tslint:enable:no-unused-variable */